Draft: Add SSOT-driven AI development principles and review sub-agents

What does this MR do and why?

This MR is a proof-of-concept, not intended for direct merge. The goal is to demonstrate the end-to-end direction -- from SSOT documentation to shared principles to multi-tool agent dispatch -- so developers and stakeholders can evaluate the approach, provide feedback, and agree on a path forward. The implementation is functional and can be tested locally, but aspects like file organization, ownership model, and Duo integration strategy should be settled collaboratively before any of this lands on master.

This MR introduces shared AI development principles distilled from docs.gitlab.com and stored in .ai/principles/distilled/*.md. These principles serve as the single source of truth for both coding agents (guiding code generation) and review agents (guiding code review) -- so the same rules apply in both directions.

To demonstrate the review side, the MR also includes 14 specialized reviewer agents that run in parallel, each checking a merge request diff from a domain-specific perspective. The agents work with both OpenCode and Claude Code today, with a path to generating GitLab Duo Code Review instructions from the same source.

The problem

AI coding assistants can review merge requests, but without structured guidance grounded in our actual documentation, the feedback tends to be generic and misses GitLab-specific conventions. Maintaining hand-written review instructions is tedious and they inevitably drift from the official guidelines. The existing hand-maintained mr-review-instructions.yaml (35 commits, all human-authored) faces this same drift problem.

This problem was already identified in !220216 (closed), where the consensus was clear: docs should be the SSOT.

The approach

  1. docs.gitlab.com as SSOT: Every checklist item is traceable to a specific docs page. The manifest (.ai/principles/sources.yml) lists the exact doc paths each principle was derived from.

  2. Shared principles (.ai/principles/distilled/*.md): 14 tool-agnostic markdown files containing domain-specific development rules. These are consumed by:

    • Reviewer agents -- for checking MR diffs against the rules
    • Coding agents -- via .ai/AGENTS.md context loading, so code generation follows the same principles
    • Claude Code loads principles automatically via file-scoped rules (.claude/rules/principles-*.md); OpenCode uses the Read tool at review time
  3. Shared principles delivery: .ai/principles/distilled/*.md files are surfaced to agents via:

    • Root AGENTS.md — Context Loading section lists each principle with the task type it applies to. OpenCode loads this at session start; agents read principles on demand based on the task.
    • Claude Code rules (.claude/rules/principles-*.md) — Auto-generated with paths: frontmatter so Claude Code loads the right principle automatically when editing matching files (e.g., spec/**/*_spec.rb triggers qa.md).
    • Directory-scoped AGENTS.md files were initially generated but removed after the A/B experiment (#597403) confirmed they benefit neither OpenCode (which per its own docs "doesn't automatically parse file references in AGENTS.md") nor Claude Code (which reads CLAUDE.md/.claude/rules/, not AGENTS.md).
  4. File-scoped Claude Code rules (.claude/rules/): Auto-generated from the manifest's file_filters. Each rule uses paths: frontmatter so Claude Code only loads principles when working with matching files (e.g., database principles only load when touching migration files). This provides finer-grained glob-based matching than directory-scoped AGENTS.md (e.g., spec/**/*_spec.rb vs just spec/).

  5. 14 specialized reviewer agents, each covering a distinct concern area, dispatched in parallel by an orchestrator skill.

  6. Multi-tool support: Both OpenCode (.opencode/skills/gitlab-review/) and Claude Code (.claude/skills/gitlab-review/) have orchestrator skills that auto-invoke when a user asks to review an MR. The 14 reviewer agents live in .opencode/agents/ and .claude/agents/ respectively. The markdown body is portable; only the YAML frontmatter differs per tool.

  7. Schema verification for database reviewers: The database and ClickHouse reviewer agents can verify schema details during reviews. Claude Code agents have scoped bash access (gdk psql, clickhouse client) for live read-only DB queries. OpenCode agents verify schemas via db/structure.sql and db/ci_structure.sql using Read/Grep (OpenCode sub-agents lack bash tool access).

  8. Intent alignment: The orchestrator fetches linked issues and assesses whether the changes match the stated goal -- going beyond best-practice checks to verify the spirit of the change.

  9. Baseline rules (.ai/principles/baselines/): Curated review rules from team experience (seeded from mr-review-instructions.yaml) that are not yet in docs.gitlab.com. Merged with SSOT rules during distillation. Baseline content is included in the checksum computation and Duo prompt, ensuring hand-curated rules are always reflected in the distilled output.

  10. Authoritative sources footer: Each distilled principle file ends with a ## Authoritative sources section listing the SSOT doc paths it was derived from, so agents know where to find the full documentation.

  11. Automated sync pipeline: A scheduled CI job computes content checksums of each principle's SSOT sources and baselines, compares against stored checksums, and re-distills affected principles via the GitLab Duo API. A post-distill diff noise filter uses word-level Jaccard similarity to preserve old wording when Duo merely rephrases items, keeping diffs focused on genuine content changes. The script retries failed Duo calls up to 3 times and exits with non-zero status if any principle fails after all retries.

  12. External distillation prompt (.ai/principles/distillation_prompt.md): The prompt governing how Duo distills principles lives in its own file for easy review and iteration, separate from the Ruby script.

The 14 principles and their SSOT sources

Principle Concern Area Key SSOT Documentation
code-review General review practices, acceptance checklist Code Review Guidelines
database PostgreSQL migrations, queries, schema Database Review Guidelines + 9 sub-pages
clickhouse ClickHouse schema, queries, migrations ClickHouse Reviewer Guidelines
security Injection, auth/authz, secrets, SSRF, deps Secure Coding Guidelines + Shell Commands + Auth Review
backend Ruby/Rails architecture, EE/CE, i18n Ruby Style Guide + i18n
rest-api REST API design, Grape DSL, backwards compat API Style Guide
graphql GraphQL types, resolvers, mutations, deprecation GraphQL Style Guide + GraphQL MR Checklist
workers Sidekiq idempotency, urgency, concurrency Sidekiq Guidelines (5 sub-pages)
frontend Vue, Pajamas, a11y, i18n (JS), CSS Frontend Guide + Style Guides + Accessibility
qa Test quality, testing pyramid, RSpec Testing Guide (6 sub-pages)
performance N+1, unbounded ops, caching, memory MR Performance Guidelines
documentation Style guide, structure, version history Documentation Style Guide
feature-flags FF type, naming, rollout, cleanup Feature Flags Guide
analytics Events, metrics, service ping, privacy Analytics Review Guidelines

Reviewer agent model tiering

Not all reviewer agents need the most capable (and expensive) model. Agents are tiered by the complexity of reasoning required:

Model Agents Rationale
Opus security, database, performance High stakes or complex reasoning (adversarial thinking, multi-file data flow tracing, migration safety analysis)
Sonnet code-review, backend, rest-api, graphql, clickhouse, workers, frontend, qa Good balance of capability and speed for pattern-matching against well-defined rules
Haiku documentation, feature-flags, analytics Mostly mechanical checks (style compliance, YAML field validation, naming conventions)

The parent orchestrator always runs on Opus.

Design decisions

Why 14 focused agents rather than fewer large ones?

  • LLM attention budget: A focused prompt with 30 rules in one domain outperforms a sprawling prompt with 150 rules across 8 domains.
  • Independent evolution: Each agent can be updated independently when its SSOT docs change.
  • Selective dispatch: If an MR only touches app/workers/, only the workers agent runs.

Why shared principles?

The reviewer agents' checklists are codified development principles -- the same rules a coding agent should follow. If these drift apart, you get the worst outcome: the coding agent writes code that the reviewer agent flags. Shared .ai/principles/ files ensure both stay aligned.

Why both directory-scoped AGENTS.md and file-scoped Claude Code rules?

They serve different mechanisms for the same goal:

  • Claude Code rules (.claude/rules/) use paths: frontmatter for fine-grained glob-based matching (e.g., spec/**/*_spec.rb). Auto-generated from sources.yml; do not edit manually.
  • Root AGENTS.md Context Loading section lists each principle by task type. OpenCode and any other tool that loads AGENTS.md at session start uses this to discover and load principles on demand.

Directory-scoped AGENTS.md files (spec/AGENTS.md, app/models/AGENTS.md, etc.) were removed after the A/B experiment proved they are unused — OpenCode does not auto-load them and Claude Code does not read AGENTS.md files.

Why a dedicated code-review agent?

Cross-cutting review concerns (acceptance checklist, inclusive language, MR hygiene, community contribution reviews) were previously bundled into the backend principle. Since these rules apply to all code -- not just Ruby/Rails -- they now live in a dedicated code-review principle with a **/* file filter (always triggered, like security). The backend agent focuses purely on Ruby/Rails architecture.

Relationship to mr-review-instructions.yaml

The existing file is hand-maintained in Duo's native format. Rules not covered by docs.gitlab.com have been seeded into .ai/principles/baselines/. A planned follow-up will add a script that generates mr-review-instructions.yaml from the principles, making it a generated artifact rather than hand-maintained.

Path to GitLab Duo native integration

The ai-gateway already has a SupervisorAgentComponent with delegate_task for orchestrating sub-agents, including SubagentComponent definitions with per-agent prompt templates, toolsets, and UI logging. Our architecture maps directly to this:

This MR Duo native equivalent
Orchestrator (gitlab-review) SupervisorAgentComponent with managed_agents
14 reviewer agents SubagentComponent per domain
Shared principles (.ai/principles/distilled/) prompt_template.system content
File-based dispatch inputs + router configuration

This means the .ai/principles/distilled/*.md files can feed directly into Duo SubagentComponent prompt templates when the time comes -- no architectural gap to bridge.

How the sync pipeline works

Sync pipeline flowchart (click to expand)
flowchart TD
    A[Hourly schedule on master] --> B[Compute SHA-256 checksums of each principle's sources + baselines + doc content]
    B --> C[Compare against stored checksums in distilled file frontmatter]
    C --> D{Any mismatches?}
    D -->|No| E[Exit: all principles up to date]
    D -->|Yes| F[For each affected principle]
    F --> G[Read SSOT docs + baseline rules]
    G --> H[Call GitLab Duo API to re-distill checklist]
    H --> H2{Valid response?}
    H2 -->|No| H3[Retry up to 3 times]
    H3 --> H
    H2 -->|Yes| I[Apply diff noise filter: keep old wording for rephrased lines]
    I --> J{Meaningful changes?}
    J -->|No| K[Skip principle]
    J -->|Yes| L[Write updated principles file + update frontmatter checksum]
    L --> M[Regenerate Claude Code rules from manifest]
    M --> M2[Regenerate directory-scoped AGENTS.md files]
    M2 --> N{Any failures?}
    N -->|Yes| O[Exit with error - no MR created]
    N -->|No| P[Create branch, commit, open batched MR]

File structure

File structure (click to expand)
.ai/
  README.md                              # Overview of the AI instruction system
  code-style.md                          # Code style guidelines (backend + frontend)
  code-review.md                         # Review guidelines referencing all principles
  ci-cd.md                               # CI/CD pipeline guidelines
  git.md                                 # Git workflow guidelines
  principles/                            # Everything principles-related lives here
    README.md                            # How the SSOT sync works
    sources.yml                          # SSOT manifest + file_filters + agents_md_dirs + baseline refs
    distillation_prompt.md               # Prompt governing how Duo distills principles
    distilled/                           # Auto-generated from docs.gitlab.com (checksums in frontmatter)
      code-review.md                     # General review practices + acceptance checklist
      database.md                        # Used by both database-reviewer agent AND coding agent
      backend.md, security.md, frontend.md, rest-api.md, graphql.md,
      workers.md, performance.md, qa.md, documentation.md,
      feature-flags.md, analytics.md, clickhouse.md
    baselines/                           # Curated rules not yet in docs.gitlab.com
      backend.md, clickhouse.md, database.md, documentation.md,
      feature-flags.md, frontend.md, qa.md, rest-api.md

AGENTS.md                                # Root fallback: context loading for all AI tools

.opencode/
  agents/*-reviewer.md                   # 14 OpenCode reviewer agents
  skills/gitlab-review/SKILL.md          # OpenCode orchestrator skill
  commands/review-mr.md                  # Thin alias to skill

.claude/
  agents/*-reviewer.md                   # 14 Claude Code reviewer agents
  rules/principles-*.md                  # 14 auto-generated file-scoped rules
  skills/gitlab-review/SKILL.md          # Claude Code orchestrator skill

scripts/ai/
  sync_principles.rb                     # Sync script (distillation + rule + AGENTS.md generation)
spec/scripts/ai/
  principles_sync_spec.rb               # Specs for sync script pure-logic methods

.gitlab/ci/
  sync-review-agents.gitlab-ci.yml       # CI job definition (stage: sync)

Known issues

  • OpenCode + Anthropic models: There is currently a bug in OpenCode when using Anthropic models through non-native providers that results in a This model does not support assistant message prefill error. Tracked at opencode#13768.
  • Directory-scoped AGENTS.md files removed: The OpenCode rules documentation explicitly states "opencode doesn't automatically parse file references in AGENTS.md" — the @ syntax is a manual convention requiring explicit prose instruction, not a parser feature. The A/B experiment (#597403) confirmed this: the OpenCode build agent never loaded any directory-scoped AGENTS.md file across multiple test runs. Claude Code also ignores AGENTS.md, reading only CLAUDE.md and .claude/rules/. The 35 auto-generated */AGENTS.md files and agents_md_dirs config have been removed (commit 4a46668f). The effective delivery mechanisms are: root AGENTS.md for OpenCode, .claude/rules/ for Claude Code.
  • Imperative voice required for agent compliance: Descriptive principle phrasings ("Feature flags are enabled by default in tests") are insufficient to override an agent's pattern-matching from existing code. Only imperative prohibitions ("DO NOT stub feature flags to true") reliably change agent behavior. The distillation prompt (rule 11) now requires all rules to use imperative framing, and a --rewrite flag was added to force a full rewrite when the prompt rules change. Discovered via A/B experiment (#597403).
  • OpenCode sub-agents lack bash access: The task() tool provides sub-agents with a fixed toolset (Glob, Grep, Ls, View) -- no Bash. This means database/ClickHouse reviewers in OpenCode verify schemas by reading structure files rather than querying the live database.

References

Screenshots or screen recordings

Claude Code OpenCode
asciicast asciicast

How to set up and validate locally

Both tools register a gitlab-review skill that auto-invokes when you ask to review an MR (e.g., "Review MR 226902" or "Review this MR"). You can also invoke the skill explicitly:

OpenCode:

  1. Install OpenCode if not already installed
  2. Ask naturally: "Review MR 226902" — the skill activates automatically
  3. Or invoke explicitly: /review-mr <MR-IID>

Claude Code:

  1. Ask naturally: "Review MR 226902" — the skill activates automatically
  2. Or invoke explicitly: /gitlab-review <MR-IID>

Sync script:

  1. ruby scripts/ai/sync_principles.rb --dry-run -- shows which principles need re-distillation based on content checksums; also regenerates Claude Code rules and directory-scoped AGENTS.md files
  2. GITLAB_DUO_API_TOKEN=<token> ruby scripts/ai/sync_principles.rb --distill-only -- runs distillation, writes updated principles, regenerates Claude Code rules and AGENTS.md files locally (no branch/MR)
  3. ruby scripts/ai/sync_principles.rb --force --distill-only -- force re-distillation of all principles ignoring checksums
  4. ruby scripts/ai/sync_principles.rb --force --distill-only --only backend,clickhouse -- selectively re-distill specific principles
  5. ruby scripts/ai/sync_principles.rb --force --distill-only --rewrite -- re-distill all principles from scratch without preserving existing wording (drops rule 9 and the CURRENT AGENT FILE from the prompt, allowing Duo to apply rule 11 imperative framing to every item)
  6. bundle exec rspec spec/scripts/ai/principles_sync_spec.rb -- run specs for the sync script

MR acceptance checklist

Evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.

Edited by Pedro Pombeiro

Merge request reports

Loading
Loading