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
-
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. -
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.mdcontext loading, so code generation follows the same principles - Claude Code loads principles automatically via file-scoped rules (
.claude/rules/principles-*.md); OpenCode uses theReadtool at review time
-
Shared principles delivery:
.ai/principles/distilled/*.mdfiles 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 withpaths:frontmatter so Claude Code loads the right principle automatically when editing matching files (e.g.,spec/**/*_spec.rbtriggersqa.md). - Directory-scoped
AGENTS.mdfiles 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 readsCLAUDE.md/.claude/rules/, notAGENTS.md).
- Root
-
File-scoped Claude Code rules (
.claude/rules/): Auto-generated from the manifest'sfile_filters. Each rule usespaths: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-scopedAGENTS.md(e.g.,spec/**/*_spec.rbvs justspec/). -
14 specialized reviewer agents, each covering a distinct concern area, dispatched in parallel by an orchestrator skill.
-
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. -
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 viadb/structure.sqlanddb/ci_structure.sqlusing Read/Grep (OpenCode sub-agents lack bash tool access). -
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.
-
Baseline rules (
.ai/principles/baselines/): Curated review rules from team experience (seeded frommr-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. -
Authoritative sources footer: Each distilled principle file ends with a
## Authoritative sourcessection listing the SSOT doc paths it was derived from, so agents know where to find the full documentation. -
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.
-
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/) usepaths:frontmatter for fine-grained glob-based matching (e.g.,spec/**/*_spec.rb). Auto-generated fromsources.yml; do not edit manually. - Root
AGENTS.mdContext Loading section lists each principle by task type. OpenCode and any other tool that loadsAGENTS.mdat 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 prefillerror. Tracked at opencode#13768. - Directory-scoped
AGENTS.mdfiles 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-scopedAGENTS.mdfile across multiple test runs. Claude Code also ignoresAGENTS.md, reading onlyCLAUDE.mdand.claude/rules/. The 35 auto-generated*/AGENTS.mdfiles andagents_md_dirsconfig have been removed (commit 4a46668f). The effective delivery mechanisms are: rootAGENTS.mdfor 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--rewriteflag 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
- Original SSOT discussion: !220216 (closed)
- Related discussion: gitlab-org/core-devops/internal-discussions#16 (comment 3162502807)
- Code Review Guidelines (approval matrix that guided vertical selection)
- MR Acceptance Checklist
- Claude Code memory documentation (file-scoped rules reference)
Screenshots or screen recordings
| Claude Code | OpenCode |
|---|---|
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:
- Install OpenCode if not already installed
- Ask naturally: "Review MR 226902" — the skill activates automatically
- Or invoke explicitly:
/review-mr <MR-IID>
Claude Code:
- Ask naturally: "Review MR 226902" — the skill activates automatically
- Or invoke explicitly:
/gitlab-review <MR-IID>
Sync script:
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-scopedAGENTS.mdfilesGITLAB_DUO_API_TOKEN=<token> ruby scripts/ai/sync_principles.rb --distill-only-- runs distillation, writes updated principles, regenerates Claude Code rules andAGENTS.mdfiles locally (no branch/MR)ruby scripts/ai/sync_principles.rb --force --distill-only-- force re-distillation of all principles ignoring checksumsruby scripts/ai/sync_principles.rb --force --distill-only --only backend,clickhouse-- selectively re-distill specific principlesruby 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)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.