Quality gates

From Kanevry/session-orchestrator · View interactive version

Quality gates is an AI agent skill from the GitHub repository Kanevry/session-orchestrator. Use this skill when referencing canonical quality check commands for typecheck, test, and lint. Defines 4 variants (Baseline, Incremental, Full Gate, Per-File) used by session-start, wave-executor, session-end, and session-reviewer. Reference skill — not invoked directly.

How to use this skill

Skill file

Quality Gates — Reference Skill

Plugin root: ${CLAUDE_PLUGIN_ROOT}. Claude Code replaces this with the plugin's absolute path when it loads this file. Where it appears unreplaced — in a file this skill reads with the Read tool, or on Codex, Cursor or Pi — the plugin root is the directory that contains this skill's skills/ folder (two levels above the folder of this SKILL.md). Write that absolute path literally into every command that starts a plugin script: the Bash tool has no plugin variable, and shell variables do not survive between tool calls.

This skill defines the canonical quality check commands. Do NOT invoke this skill directly.

Consuming skills (session-start, wave-executor, session-end, session-reviewer) reference the

variant they need and execute the commands inline.

Command Resolution (policy-file-first, #183)

Quality-gate commands are resolved in this priority order:

  1. .orchestrator/policy/quality-gates.json — canonical policy file (preferred). Schema: .orchestrator/policy/quality-gates.schema.json. Bootstrap writes a package-manager-aware default; hand-edit to customize.
  2. Session Config test-command / typecheck-command / lint-command in CLAUDE.md (Claude Code / Cursor) or AGENTS.md (Codex CLI) — fallback.
  3. Hardcoded defaults — last resort: npm test, npm run typecheck, npm run lint.

Loader: scripts/lib/quality-gates-policy.mjs exports loadQualityGatesPolicy(repoRoot) and resolveCommand(policy, key, fallback). The Node runner scripts/run-quality-gate.mjs performs the same resolution inline.

If any resolved command is set to the literal string skip, skip that check entirely.

Scope Policy (#320)

Lint, typecheck, and test commands MUST run with the project's canonical, unscoped invocation as resolved above (e.g., npm run lint, npm test, npm run typecheck). The resolved command's own configuration (eslint.config.*, tsconfig.json, vitest.config.*, package.json scripts) is the single source of truth for which files are checked.

Domain-split scoping is FORBIDDEN. Do NOT replace the canonical command with narrower variants such as:

This rule applies to every consumer of this skill: session-start Baseline, wave-executor Incremental, session-end Full Gate, session-reviewer Per-File, discovery probes, and repo-audit. It applies whether the command is invoked by an agent, by scripts/run-quality-gate.mjs, or by a human running it inline during triage.

Exception — Incremental Per-File (Variant 4) test runs: {test-command} MAY be invoked with explicit changed-file arguments (e.g., pnpm test -- auth.test.ts) per the per-file contract. Lint and typecheck have NO per-file exception — they always run the canonical command.

Why: Domain-split scoping was empirically shown (consumer-repo Deep-10 retro, 2026-05-20) to hide 2 errors and 17 warnings in tests/integration/ and tests/e2e/ that the canonical pnpm lint (841-file glob) catches. Narrowing scope to src/+scripts/ for "lint-triage" produced a green W1, but the W4 Full Gate then surfaced the hidden errors, forcing a W5 sweep. The narrow-scope variant is a foot-gun: it looks faster but leaks debt across waves.

Session Config Fields (legacy fallback)

Read these from the project's ## Session Config section when .orchestrator/policy/quality-gates.json is absent:

If a field is missing, use the hardcoded default.

Variant 1: Baseline

Used by: session-start (Phase 3)

Purpose: Quick health check at session start — non-blocking.

Commands:

  1. Run {typecheck-command} 2>&1 | tail -5
  2. Run {test-command} 2>&1 | tail -5

Behavior: Report results but do NOT block the session. Capture error counts and store them

as the session baseline for later comparison.

Script output schema (Baseline):

{"variant": "baseline", "typecheck": {"status": "pass|fail|skip"}, "test": {"status": "pass|fail|skip"}, "typecheck_output": "string", "test_output": "string"}

In every variant, each command object that was actually spawned also carries its per-command kill ladder: timed_out (boolean), kill_signals (string[]) and survivors (pid[]). A skipped or stubbed command has none of the three keys (absent, never false/[]). scripts/run-quality-gate.mjs joins them into orchestrator.quality_gate.{passed,failed} (#1457). A run whose joined timed_out is true is recorded as .failed in every variant, although Baseline, Incremental and Per-File still exit 0 (#1459, decided 2026-10-01).

Variant 2: Incremental

Used by: wave-executor (after implementation waves)

Purpose: Verify implementation waves did not break anything.

Commands:

  1. Run {test-command} on changed files only (e.g., pnpm test -- <changed-test-files>).
  2. Run {typecheck-command}.

Behavior: The Incremental runner reports check failures in its JSON and exits 0 (scripts/run-quality-gate.mjs, reporting variants). The wave-executor turns failures into fix tasks for the next wave and does not block wave progression (skills/wave-executor/references/wave-loop-review.md § 3 Adapt Plan). A wave that touched shared code is auto-promoted to the Full Gate (exit 2 when red; its failures follow the same Adapt Plan step), and the Full Gate after the Quality wave must pass (Variant 3). With verification-auto-fix.enabled: true, a failed inter-wave gate dispatches a fixer and reruns within max-retries (default 2), and the wave aborts if it is still red (#2189).

Metrics output (for consuming skills to capture):

{
  "variant": "incremental",
  "duration_seconds": null,
  "typecheck": {"status": "pass|fail|skip"},
  "test": {"status": "pass|fail|skip"},
  "errors": []
}

Variant 3: Full Gate

Used by: session-end (Phase 2); wave-executor (Quality wave — mechanically enforced via the waveRole parameter, #724)

Purpose: Final quality gate before commit — MUST pass.

Commands:

  1. Run {typecheck-command} — must produce 0 errors.
  2. Run {test-command} — must pass (exit code 0).
  3. Run {lint-command} — must pass (warnings OK, errors NOT OK).
  4. Check changed files for debug artifacts: console.log, debugger, TODO: remove.

Behavior: BLOCKING. Do not commit if any check fails. Fix quick issues (<2 min) inline.

For anything longer, create a priority::high issue and proceed without committing the

affected files.

What decides the verdict: the exit code of each command, with three exceptions (scripts/lib/gates/gate-helpers.mjs, scripts/lib/gates/gate-full.mjs): a command that is empty or skip is skipped and counts as passed; a command recognised as a stub (echo, no-op) counts as passed without running; and when every test failure of a run is a timeout, up to 10 of those files are re-run one at a time, and a re-run whose JSON report shows exactly those files passed turns the test step green (#1673). Otherwise a check is pass when its command exits 0 and fail when it does not. The counts parsed from the test output (passed, failed, total) are measurements that travel in the envelope and the orchestrator.quality_gate.passed event; they do not change the Full Gate verdict. So a {test-command} that prints failures but still exits 0 (for example because it ends in || true, or runs through a wrapper that swallows the exit code) counts as passed, and the envelope can then show failed > 0 next to status: pass. The Full Gate names that contradiction without changing the verdict or the exit code: test.failed_despite_pass: true in the envelope and one stderr line starting ⚠ test command exited 0, but its output counts N failed test(s) (scripts/lib/gates/gate-full.mjs, failedDespitePass). Both appear only when the first test run itself exited 0 and its output carries a Tests summary line, so a log line such as "1 failed request" from a runner without one never raises them; a step that turned green through the serial re-run does not get them, and a clean run carries neither. The count is read from free text (#1534) and can be misread. The remote pre-push route reads the count differently: scripts/lib/pre-push-remote-gate.mjs blocks the push when report.test.failed > 0 and no clean re-run explains it, so there such a run does not pass. Make sure the configured command exits non-zero on failure.

Broken-Window cross-reference (#730/H5): a Full-Gate PASS that ships with a documented exception (echo-stub, WARN-lint, overridden finding) feeds session-end Phase 2.6 — see skills/session-end/SKILL.md § Phase 2.6.

Metrics output (for consuming skills to capture):

{
  "variant": "full-gate",
  "duration_seconds": null,
  "typecheck": {"status": "pass|fail|skip", "error_count": 0},
  "test": {"status": "pass|fail|skip", "total": 0, "passed": 0},
  "lint": {"status": "pass|fail|skip", "warnings": 0},
  "debug_artifacts": []
}

Variant 4: Per-File

Used by: session-reviewer agent

Purpose: Targeted quality check on specific changed files.

Commands:

  1. Run {test-command} on specific file paths passed by the reviewer.
  2. Run {typecheck-command}.

Behavior: Report per-file pass/fail status. The reviewer uses these results to annotate

its review output.

Script output schema (Per-File):

{"variant": "per-file", "typecheck": {"status": "pass|fail|skip"}, "test": {"status": "pass|fail|skip"}, "files": ["string"]}

Graceful Degradation

Handle missing tools without aborting the session; a missing configured command is still reported as a failed check:

Always continue with the remaining checks — never abort a variant because one tool is missing.

How Other Skills Reference This

When a consuming skill needs quality checks, include this directive:

Quality Reference: Run [Baseline|Incremental|Full Gate|Per-File] quality checks

per the quality-gates skill. Read test-command, typecheck-command, and lint-command

from Session Config (defaults: npm test, npm run typecheck, npm run lint).

Replace the bracketed variant name with the specific variant required by that phase.

Script Alternative

Prefer scripts/run-quality-gate.mjs for deterministic execution with structured JSON output. The inline command approach is supported but produces unstructured output that downstream consumers cannot reliably parse.

# Baseline (session-start)
node "${CLAUDE_PLUGIN_ROOT}/scripts/run-quality-gate.mjs" --variant baseline --config "$CONFIG"

# Incremental (wave-executor)
node "${CLAUDE_PLUGIN_ROOT}/scripts/run-quality-gate.mjs" --variant incremental --config "$CONFIG" --files changed-file1.ts,changed-file2.ts

# Full Gate (Quality wave, session-end) — --receipt reuses a green run on the same content tree (#1897)
node "${CLAUDE_PLUGIN_ROOT}/scripts/run-quality-gate.mjs" --variant full-gate --config "$CONFIG" --session-start-ref "$SESSION_START_REF" --receipt

# Per-File (session-reviewer)
node "${CLAUDE_PLUGIN_ROOT}/scripts/run-quality-gate.mjs" --variant per-file --config "$CONFIG" --files specific-file.ts

The script handles graceful degradation (missing tools → skip), structured JSON output matching the schemas above, and proper exit codes (0=pass, 1=error, 2=gate-failed). Only Full Gate exits 2: the three reporting variants exit 0 after a failing or killed check, so their verdict is in the JSON envelope (a kill also turns the event into .failed; a plain failing check does not). stdout stays one JSON document; Full Gate's stderr carries the failure disclosure, the re-run summary and, when the test command exited 0 while its output counts failures, the one failed_despite_pass line (see What decides the verdict).

Baseline Cache (#258)

Quality gates historically ran 2–3× per session (session-start Baseline, per-wave Incremental, session-end Full Gate) even when nothing relevant to the gate had changed between waves. The Baseline Cache short-circuits Incremental only when the session-start Baseline result is still trustworthy.

Storage: .orchestrator/metrics/baseline-results.jsonl — append-only JSONL, one record per session baseline run (consistent with sessions.jsonl, events.jsonl, learnings.jsonl precedent at .orchestrator/metrics/).

Record schema (version 1):

{"version":1,"session_id":"<id>","session_start_ref":"<git-sha>","captured_at":"<ISO 8601 UTC>","dependency_hash":"<sha256 of package.json + lockfile>","results":{"typecheck":{"status":"pass|fail","error_count":0},"test":{"status":"pass|fail"},"lint":{"status":"pass|fail"}}}

Validity rules — a cache record is valid iff ALL of:

Invalid reason codes: no-record | session-ref-mismatch | dependency-changed | ttl-expired | baseline-had-failures.

Incremental-skip condition: shouldSkipIncremental() returns skip: true when the cache is valid AND git diff --name-only $SESSION_START_REF..HEAD | wc -l returns <50. Otherwise skip: false and Incremental runs as before. The function never throws — on any error (git failure, unreadable cache, missing dependency_hash) it fails safe by returning skip: false.

INVARIANT — Full Gate at session-end AND after the Quality wave is NEVER skipped, regardless of cache state. The cache only short-circuits Incremental in the Impl waves of wave-executor. Two consumers hold this invariant: (1) session-end (Phase 2) always runs the complete gate before commit; (2) the wave-executor Quality wave (#724 C6) — shouldSkipIncremental({ waveRole: 'Quality' }) hard-returns skip: false (reason quality-wave-full-gate-mandate) BEFORE any cache/diff logic, so the Quality-wave Full Gate is mechanically un-skippable, not merely prose-mandated. Full Gate remains the close-safety gate and always runs the complete typecheck + test + lint + debug-artifact scan. This is intentional and non-configurable.

Receipt, not a skip (#1897): both consumers call the Full Gate with --receipt. When a green Full Gate already ran on the identical content tree (tracked plus untracked, non-ignored files, keyed by git tree hash) with the identical gate definition (the three commands, Node and plugin version) within 12 hours, its receipt stands in for the run: the envelope and the orchestrator.quality_gate.passed event carry reused_from: {tree, at}, so the reuse is visible, never silent. The cache above can never cause this; only a receipt for the same content can. A receipt is written only after a green run during which the content tree did not change. On a clean tree (content tree = HEAD^{tree}) the Full Gate also reads and writes the navigator gate-run ledger as gate so:full-gate: a navigator receipt is read only when the SO-local store has none, and its reuse carries reused_from.source: 'navigator' plus entry_sha256 (no counts). Without navigator nothing changes. A later red run does not cancel a green receipt within its 12 hours (measured 0 of 20 re-runs, ceiling C13 in scripts/lib/gate-receipt.mjs, #1909). Store and ceilings: scripts/lib/gate-receipt.mjs. A receipt is a measurement, not an approval, and never replaces a CI pipeline.

The pre-push hook reads only receipts of the pushed tree (#1897). Before every route, .husky/pre-push runs run-quality-gate.mjs --receipt-check --pushed-sha <sha> in its temp clone: a read-only probe that passes the push on a receipt for exactly this clean commit tree and otherwise exits 10 without running, emitting or writing anything, so the remote, partial and full routes run as before. It accepts only records with context: 'pushed-tree' — minted by the hook's local fallback (--receipt-record: write-only, always runs the suite, never reads the store or navigator) or by the remote router after a verified green run — and compares the gate definition with Node neutralised, because the gate hosts run different Node versions. A receipt from the Quality wave or session-end does NOT answer pre-push: those run in the working copy, whose gitignored files and environment the hook exists to exclude. A hit carries reused_from: {tree, at, host, key: 'any-node'} and pushed_sha.

Implementation: scripts/lib/quality-gates-cache.mjs exports computeDependencyHash, saveBaselineResult, loadLatestBaselineResult, isCacheValid, shouldSkipIncremental. Stdlib-only (node:fs, node:path, node:crypto, node:child_process).

Validation (#266): Effectiveness confirmed under the Claude Code subprocess-per-call hook model. The JSONL file-based design persists across subprocess boundaries — 100% hit-rate across 8 independent Node.js processes in benchmarks. Median call latency: 0.45 ms (subprocess) / 0.07 ms (in-process warm). The cache is NOT in-process memory; hooks do not call this module directly. See docs/policy-cache-validation-2026-04-28.md for full findings and scripts/measure-policy-cache-effectiveness.mjs for the instrumentation script.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.