Architecture: Enforced Code Conventions

Status Draft for review
Last updated 2026-12-04
Related Vision · Conventions catalog

1. Context and constraints

Constraint Impact on the design
Most new code is written by Claude Code and Codex agents Checks must run inside the agent’s edit loop, be fast, and return output the agent can act on.
Polyglot codebase (JS/TS/Svelte, CSS/SCSS, HTML web and email, PHP/WordPress, Python, Go, Shell, PowerShell, C#, plus config formats) We need a single runner that can call many language-specific tools.
Target: managed GitLab, early 2027; tier unknown The primary design uses Ultimate features. A Premium fallback is defined (§8).
Current GitLab CE 13.9.4 is not a target It can’t be upgraded. Nothing here is built for it. Only the parts that don’t depend on GitLab (§3.1–3.4) are usable before the migration.
Merge requests are not required today Mandatory MRs (PR-01) are a prerequisite for the merge gate.
Large legacy code, never linted Only changed files are gated; exceptions are recorded and approved.
Preference for established, pluggable tools Off-the-shelf formatters, linters, runners and GitLab features; custom code only as thin glue.

2. System overview

flowchart TB
  subgraph SOT["Conventions repository (single source of truth, semver-tagged)"]
    DOC["CONVENTIONS.md + language appendices"]
    CFG["Shared tool configs<br/>(npm config packages + config files)"]
    PIN["mise.toml<br/>(pinned tool versions)"]
    RUN["lefthook.yml<br/>(glob → tool commands, fix and check modes)"]
    CMP["CI/CD Catalog component<br/>(conventions, exceptions, coverage, AI-review jobs)"]
    IMG["CI image<br/>(built from mise.toml + config packages)"]
    AGT["Agent integrations<br/>(Claude Code plugin, Codex hooks, managed settings)"]
  end

  subgraph L1["1 · Generation time"]
    CC["Claude Code<br/>PostToolUse + Stop hooks"]
    CX["Codex<br/>PostToolUse + Stop hooks"]
  end
  subgraph L2["2 · Editor"]
    ED["Format on save<br/>linter extensions"]
  end
  subgraph L3["3 · Commit"]
    PC["lefthook pre-commit<br/>(can be bypassed)"]
  end
  subgraph L4["4 · Merge gate (the guarantee)"]
    PEP["Pipeline execution policy<br/>(group-scoped)"]
    MR["Mandatory MR + Pipelines must succeed<br/>+ CODEOWNERS on .conventions/"]
  end

  AGT --> CC & CX
  CFG --> ED
  RUN --> CC & CX & PC
  PIN --> CC & CX & PC
  CMP --> PEP --> MR
  IMG --> PEP

The design has four enforcement layers. Layers 1–3 give fast feedback; layer 4 is the guarantee. All four use the same rules, the same configs and the same tool versions, so their results match.

3. Components

3.1 Conventions repository

The single source of truth. It is versioned with semantic-version tags; a major version may add blocking rules.

conventions/
├── CONVENTIONS.md                 # rules: ID, rationale, examples, enforcement class
├── languages/<lang>.md            # per-language mapping of categories to tool rules and thresholds
├── configs/
│   ├── npm/                       # @cglife/eslint-config, @cglife/prettier-config, @cglife/stylelint-config
│   ├── ruff.toml  .golangci.yml  phpcs.xml  PSScriptAnalyzerSettings.psd1
│   ├── csharp/.editorconfig  csharp/Directory.Build.props
│   ├── .yamllint  .hadolint.yaml  .markdownlint-cli2.yaml  .sqlfluff  .ls-lint.yml
│   ├── html-validate/{web,email}.json
│   └── dependency-cruiser.cjs  knip.json  .jscpd.json  semgrep/  gitleaks.toml
├── mise.toml                      # pinned versions of non-Node tools
├── lefthook.yml                   # the runner definition
├── bin/                           # thin glue scripts (see §3.2)
├── ci/Dockerfile                  # CI image built from mise.toml + npm config packages
├── templates/conventions.yml      # CI/CD Catalog component
├── policy/pipeline-execution-policy.yml
├── agent/
│   ├── claude-plugin/             # hooks + skill
│   ├── codex/hooks.json
│   ├── managed-settings.json
│   └── AGENTS.md.snippet
├── fixtures/<lang>/{good,bad}/    # rule tests
└── scripts/onboard.py  scripts/audit.py

How configs reach projects: - The JS-ecosystem configs are published as npm packages to the GitLab package registry. Projects add one dev dependency and a one-line config that extends it. Type-aware ESLint rules need the project’s own node_modules and tsconfig, so they run in the project context. - Other configs are resolved by the runner from the conventions version pinned in the project’s .conventions/version. A project file of the same name extends or overrides the shared config only where the tool supports that, and the override is a CODEOWNED change (§6).

3.2 Runner: lefthook

lefthook is a mature, fast, polyglot hook and task runner. One lefthook.yml defines a conventions command group: each entry pairs a file glob with a tool command and has a fix mode and a check mode. The same definition runs in three places:

Caller Invocation
Agent PostToolUse hook lefthook run conventions-fix --file <path>, then lefthook run conventions --file <path>
Agent Stop hook and git pre-commit lefthook run conventions --files <changed files>
CI merge gate lefthook run conventions --files <MR diff files> inside the CI image

Glue scripts in bin/ cover the few checks that no standard tool provides: - inline-directive-check: rejects newly added suppression comments for tools that cannot ignore them. - placeholder-check: catches stubs such as TODO: implement, pass-only bodies and throw new Error("not implemented"). - tests-exist-check: a new or changed module needs a matching test file. - readme-sections-check. - changed-files: computes the diff against the merge base.

3.3 Tool version pinning: mise + npm

3.4 Agent integrations

Claude Code

Distributed as a plugin from an internal marketplace (the conventions repo) and force-enabled through managed settings, so users cannot disable it.

Hook Trigger Behavior
PostToolUse Edit\|Write\|MultiEdit on a source file Run fix mode on the file, then check mode. If violations remain, print them (file:line, rule ID, message, fix hint) to stderr and exit 2, which feeds them back to Claude to fix immediately. Target p95 under 2 s.
Stop The agent tries to finish Run check mode, plus the tests-exist and placeholder checks, on every file changed against the merge base. Any violation → exit 2, and the agent continues working. A loop guard (stop_hook_active plus an attempt counter) escalates to the user after N failed attempts instead of looping forever.
SessionStart Session begins Prints a short reminder of the A-class (judgment) conventions and the exception procedure.

Codex

The same hook scripts are registered as managed hooks (managed hooks run without a per-user trust prompt): - a PostToolUse hook on file-writing tools; - a stop hook.

The conventions summary goes in AGENTS.md. To verify during implementation: Codex’s exact matcher names, the payload format, and whether its stop event can block completion the way Claude Code’s can.

Agents without our hooks

Cloud agents and unmanaged installs don’t run the local hooks. They still have to pass the merge gate. Local hooks make agents faster to a passing state; they are not what guarantees compliance.

3.5 Editor and pre-commit

3.6 Merge gate: the CI/CD Catalog component

templates/conventions.yml is published to the CI/CD Catalog and pinned by version. It defines these jobs:

Job Runs Blocks?
conventions lefthook check mode on files changed against CI_MERGE_REQUEST_DIFF_BASE_SHA, with inline suppression comments ignored (see §6). Emits a Code Quality report (findings inline in the MR diff) and JUnit output. Yes (or warn, per ring)
conventions-exceptions Lists .conventions/ changes and added inline directives in the MR summary, so reviewers see them. Yes, if an inline directive is added
conventions-coverage Diff coverage of the changed lines, from the project’s Cobertura report, against the floor. Yes, once a project has a test job; warn before that
conventions-ai-review Claude Code headless reviews the diff against the A-class rules and posts MR comments. Never
GitLab SAST, Secret Detection, Dependency Scanning (Ultimate) GitLab’s own security scanners Configured through security policies

Component inputs: mode: warn|block, conventions_version, diff_coverage_floor, enable_ai_review.

3.7 Pipeline execution policy (Ultimate)

A security policy project holds policy/pipeline-execution-policy.yml. The policy: - uses the inject_policy strategy: it adds the component’s jobs to every pipeline in scope while keeping the project’s own jobs; - runs on merge request pipelines and default-branch pipelines; - is scoped to groups, which is how rings are rolled out (§7); - cannot be removed or edited by project maintainers.

4. Key flows

4.1 Agent edit loop

sequenceDiagram
  participant A as Agent (Claude Code / Codex)
  participant H as PostToolUse hook
  participant L as lefthook + pinned tools
  A->>A: Edit/Write src/foo.ts
  A->>H: tool result (file path)
  H->>L: fix mode (prettier, eslint --fix, ...)
  H->>L: check mode
  alt clean
    L-->>H: ok
    H-->>A: exit 0 (silent)
  else violations remain
    L-->>H: findings
    H-->>A: exit 2 + "src/foo.ts:42 CPX-02 cognitive complexity 22 > 15 ..."
    A->>A: refactors immediately
  end

4.2 Agent finish (Stop)

sequenceDiagram
  participant A as Agent
  participant S as Stop hook
  participant L as lefthook + glue checks
  A->>S: wants to finish
  S->>L: check every changed file + tests-exist + placeholders
  alt clean
    S-->>A: allow stop
  else violations (attempt < N)
    S-->>A: exit 2 + findings (keep working)
  else violations (attempt = N)
    S-->>A: allow stop + tell the user which violations remain
  end

4.3 Merge request

flowchart LR
  P[Push branch] --> MR[Open MR]
  MR --> PIPE[MR pipeline<br/>project jobs + policy-injected jobs]
  PIPE --> C{conventions<br/>on changed files}
  C -- violations --> RED[Pipeline fails<br/>findings inline in diff]
  RED --> FIX[Fix, or request exception] --> P
  C -- clean --> APPR{Approvals<br/>≥1 non-author<br/>+ code owners if .conventions/ changed}
  APPR -- ok --> MERGE[Merge]

4.4 Exceptions

  1. A finding is judged a valid exception: a false positive, generated code, or a deliberate trade-off.
  2. The author adds an entry to .conventions/ in the same MR: a tool-native per-file ignore or baseline entry, with a justification in .conventions/EXCEPTIONS.md (rule ID, path, reason, ticket).
  3. CODEOWNERS routes /.conventions/ to @cg-life/conventions-approvers, and code-owner approval is required. The MR cannot merge until an owner approves.
  4. Exceptions are reviewed periodically. Rules that attract many exceptions are reconsidered.

5. Legacy code: only changed files are gated

6. Making exceptions hard to sneak in

Tool Inline suppression handling in CI
ESLint --no-inline-config (inline disables ignored); exceptions via config overrides or bulk suppressions in .conventions/
Stylelint --ignore-disables
Ruff --ignore-noqa (per-file-ignores in .conventions/ruff.toml)
golangci-lint nolintlint requires a reason; plus inline-directive-check
ShellCheck, phpcs, PSScriptAnalyzer, Roslyn, html-validate, others inline-directive-check fails on any newly added suppression comment

The only working way around a rule is a .conventions/ change, and that requires a code owner’s approval.

7. Group-by-group rollout

Ring GitLab mechanics
0 – Pilot Policy scoped to the pilot project IDs, component mode: warn; protected-branch and MR settings applied to those projects
1 – Early adopters Policy scope gains 2–3 groups, mode: block; group-level protected-branch defaults and MR settings
2 – Active client groups Each group is added first under a warn-mode policy, then moved to the blocking policy after two weeks
3 – Everywhere Policy linked at the top level, mode: block; group defaults apply to every new project

8. Ultimate vs Premium

Capability Ultimate (primary) Premium (fallback)
Gate injected without project changes Pipeline execution policy, group-scoped ✗: each project includes the component (include: component:) through the onboarding MR
Gate can’t be removed by projects ✓ ✗: a scheduled scripts/audit.py flags projects missing the include or settings, and reports them to the owners
Ring rollout Policy scope The onboarding script runs per group; mode input in the include
Mandatory MRs, Pipelines must succeed, protected branches ✓ ✓
CODEOWNERS required approval for exceptions ✓ ✓
Code Quality findings Inline in the MR diff MR widget
Security scanning (category 17) GitLab SAST / Secret Detection / Dependency Scanning + Semgrep and gitleaks in the component Semgrep, gitleaks and osv-scanner in the component

9. Tool choices

Decision Choice Rejected alternatives and why
Runner lefthook MegaLinter: 4+ GB image; tens of seconds even for one file, so unusable as a per-edit agent hook; a CI-only MegaLinter would mean different tool versions locally and in CI. Trunk Check: strong product, but a commercial vendor dependency. pre-commit framework: good polyglot hooks, but awkward for Node plugin dependencies (ESLint plugins and type-aware rules).
Version pinning mise + npm packages Docker-only tooling (too slow and heavy locally and in agent sandboxes); per-developer installs (versions drift)
JS/TS formatter + linter Prettier + ESLint (typescript-eslint, eslint-plugin-svelte) Biome: fast, but less complete Svelte support and fewer complexity, documentation and a11y rules
Python Ruff (lint + format) + mypy flake8 + black + isort (slower, several tools doing what one does)
Central CI enforcement Pipeline execution policy Compliance pipelines (deprecated); per-project includes alone (projects can remove them)
Exceptions .conventions/ + CODEOWNERS Inline disable comments (can’t be reviewed centrally); a custom approval bot (unnecessary with code owners)
AI review Advisory only Blocking AI review (not deterministic; fails Vision principle “deterministic first”)
Skill alone Rejected as enforcement Prompt context can’t guarantee compliance; it supports the hooks and the gate

10. Guarantees and limits

Guaranteed Not guaranteed
Every merge to a protected branch passed the conventions gate on its changed files (Ultimate: no project can opt out) Rules marked A/H (meaningful names, comment quality, single responsibility) are checked only by advisory AI review and human review
Every exception was approved by a conventions owner Files never touched since rollout may still contain old violations
Agents on managed machines get immediate feedback and cannot finish with violations (bounded by the Stop-attempt limit) Agents outside managed setups get feedback only at the merge gate
Local, agent and CI checks give the same result (same pins) Changes pushed through a logged emergency bypass are checked afterwards, not before

11. Architecture Decision Records (stubs)

These will be written as docs/adr/NNNN-*.md when the decisions are confirmed:

  1. ADR-0001: Use lefthook as the single runner across agent hooks, git hooks and CI
  2. ADR-0002: Pin tool versions with mise and npm config packages; build the CI image from the same pins
  3. ADR-0003: Gate only changed files (whole-file); optional tool-native baselines at onboarding
  4. ADR-0004: Exceptions only through .conventions/ with CODEOWNERS approval; inline suppressions rejected
  5. ADR-0005: Enforce the merge gate with pipeline execution policies (Ultimate), with the Premium fallback
  6. ADR-0006: Make merge requests mandatory on protected branches (PR-01)
  7. ADR-0007: Enforce on agents with managed hooks; the skill provides context only
  8. ADR-0008: AI review is advisory and never blocks
  9. ADR-0009: Separate web and email HTML profiles; exclude generated output by path
  10. ADR-0010: Rule lifecycle: warn for one minor version, then block