@gate-forge/cli 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +78 -1143
  2. package/dist/adapter-audit.d.ts +54 -0
  3. package/dist/adapter-audit.d.ts.map +1 -1
  4. package/dist/adapter-audit.js +48 -0
  5. package/dist/adapter-audit.js.map +1 -1
  6. package/dist/adapter-scaffold.d.ts +28 -3
  7. package/dist/adapter-scaffold.d.ts.map +1 -1
  8. package/dist/adapter-scaffold.js +145 -24
  9. package/dist/adapter-scaffold.js.map +1 -1
  10. package/dist/args.d.ts.map +1 -1
  11. package/dist/args.js +2 -0
  12. package/dist/args.js.map +1 -1
  13. package/dist/behavior-setup.d.ts.map +1 -1
  14. package/dist/behavior-setup.js +18 -5
  15. package/dist/behavior-setup.js.map +1 -1
  16. package/dist/commands/adapters.d.ts.map +1 -1
  17. package/dist/commands/adapters.js +73 -2
  18. package/dist/commands/adapters.js.map +1 -1
  19. package/dist/commands/adopt.d.ts +7 -0
  20. package/dist/commands/adopt.d.ts.map +1 -1
  21. package/dist/commands/adopt.js +35 -1
  22. package/dist/commands/adopt.js.map +1 -1
  23. package/dist/commands/blocking.d.ts +25 -1
  24. package/dist/commands/blocking.d.ts.map +1 -1
  25. package/dist/commands/blocking.js +64 -5
  26. package/dist/commands/blocking.js.map +1 -1
  27. package/dist/commands/check.d.ts.map +1 -1
  28. package/dist/commands/check.js +60 -2
  29. package/dist/commands/check.js.map +1 -1
  30. package/dist/commands/classify.d.ts +1 -1
  31. package/dist/commands/classify.d.ts.map +1 -1
  32. package/dist/commands/classify.js +63 -18
  33. package/dist/commands/classify.js.map +1 -1
  34. package/dist/commands/enforcement.d.ts.map +1 -1
  35. package/dist/commands/enforcement.js +81 -4
  36. package/dist/commands/enforcement.js.map +1 -1
  37. package/dist/commands/explain.d.ts +1 -1
  38. package/dist/commands/explain.d.ts.map +1 -1
  39. package/dist/commands/explain.js +162 -3
  40. package/dist/commands/explain.js.map +1 -1
  41. package/dist/commands/init-presets.d.ts +7 -0
  42. package/dist/commands/init-presets.d.ts.map +1 -1
  43. package/dist/commands/init-presets.js +10 -1
  44. package/dist/commands/init-presets.js.map +1 -1
  45. package/dist/commands/init.d.ts.map +1 -1
  46. package/dist/commands/init.js +386 -39
  47. package/dist/commands/init.js.map +1 -1
  48. package/dist/commands/next.d.ts.map +1 -1
  49. package/dist/commands/next.js +103 -5
  50. package/dist/commands/next.js.map +1 -1
  51. package/dist/commands/test-gates.js +1 -1
  52. package/dist/commands/tests.d.ts.map +1 -1
  53. package/dist/commands/tests.js +39 -7
  54. package/dist/commands/tests.js.map +1 -1
  55. package/dist/docs-exclusions.d.ts.map +1 -1
  56. package/dist/docs-exclusions.js +18 -3
  57. package/dist/docs-exclusions.js.map +1 -1
  58. package/dist/endpoint-compiler.d.ts.map +1 -1
  59. package/dist/endpoint-compiler.js +49 -1
  60. package/dist/endpoint-compiler.js.map +1 -1
  61. package/dist/evaluate.d.ts +16 -1
  62. package/dist/evaluate.d.ts.map +1 -1
  63. package/dist/evaluate.js +12 -2
  64. package/dist/evaluate.js.map +1 -1
  65. package/dist/gateforge-owned.d.ts +78 -0
  66. package/dist/gateforge-owned.d.ts.map +1 -0
  67. package/dist/gateforge-owned.js +254 -0
  68. package/dist/gateforge-owned.js.map +1 -0
  69. package/dist/git-hooks.d.ts +18 -0
  70. package/dist/git-hooks.d.ts.map +1 -1
  71. package/dist/git-hooks.js +21 -1
  72. package/dist/git-hooks.js.map +1 -1
  73. package/dist/git-ignored.d.ts +27 -0
  74. package/dist/git-ignored.d.ts.map +1 -0
  75. package/dist/git-ignored.js +102 -0
  76. package/dist/git-ignored.js.map +1 -0
  77. package/dist/glob.d.ts +33 -14
  78. package/dist/glob.d.ts.map +1 -1
  79. package/dist/glob.js +96 -5
  80. package/dist/glob.js.map +1 -1
  81. package/dist/index.d.ts +4 -1
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +2 -1
  84. package/dist/index.js.map +1 -1
  85. package/dist/io.d.ts +18 -5
  86. package/dist/io.d.ts.map +1 -1
  87. package/dist/io.js +5 -4
  88. package/dist/io.js.map +1 -1
  89. package/dist/pipeline.d.ts +16 -1
  90. package/dist/pipeline.d.ts.map +1 -1
  91. package/dist/pipeline.js +23 -3
  92. package/dist/pipeline.js.map +1 -1
  93. package/dist/planes-inference.d.ts +12 -5
  94. package/dist/planes-inference.d.ts.map +1 -1
  95. package/dist/planes-inference.js +13 -15
  96. package/dist/planes-inference.js.map +1 -1
  97. package/dist/repo-scan.d.ts +7 -0
  98. package/dist/repo-scan.d.ts.map +1 -1
  99. package/dist/repo-scan.js +109 -8
  100. package/dist/repo-scan.js.map +1 -1
  101. package/dist/route-plane-proposals.d.ts +100 -0
  102. package/dist/route-plane-proposals.d.ts.map +1 -0
  103. package/dist/route-plane-proposals.js +213 -0
  104. package/dist/route-plane-proposals.js.map +1 -0
  105. package/dist/scope.d.ts +20 -0
  106. package/dist/scope.d.ts.map +1 -1
  107. package/dist/scope.js +26 -5
  108. package/dist/scope.js.map +1 -1
  109. package/dist/singleton-guidance.d.ts +15 -6
  110. package/dist/singleton-guidance.d.ts.map +1 -1
  111. package/dist/singleton-guidance.js +30 -10
  112. package/dist/singleton-guidance.js.map +1 -1
  113. package/dist/unmatched-routes.d.ts +60 -0
  114. package/dist/unmatched-routes.d.ts.map +1 -0
  115. package/dist/unmatched-routes.js +131 -0
  116. package/dist/unmatched-routes.js.map +1 -0
  117. package/guides/CONNECT-YOUR-PROJECT.md +78 -20
  118. package/guides/QUICKSTART.md +55 -10
  119. package/guides/REFERENCE.md +1710 -0
  120. package/guides/TEST-ENVIRONMENT.md +8 -5
  121. package/guides/UPGRADE-0.8-to-0.9.md +104 -0
  122. package/package.json +10 -10
@@ -0,0 +1,1710 @@
1
+ # Gateforge CLI reference
2
+
3
+ The reference for the `gateforge` CLI: every command, flag, exit
4
+ code, and protocol, plus the usage documentation that lived in the
5
+ repository README before the 0.9.0 documentation split. Both halves
6
+ moved verbatim from `packages/cli/README.md` and the root
7
+ `README.md`. The [CLI README](../README.md) covers install and the
8
+ first commands; the guides cover the walks:
9
+ [Quickstart](QUICKSTART.md), [Connect your project](CONNECT-YOUR-PROJECT.md),
10
+ [Test environment](TEST-ENVIRONMENT.md),
11
+ [Runners other than Playwright](RUNNER-NEUTRAL-EVIDENCE.md),
12
+ [Upgrade from 0.8 to 0.9](UPGRADE-0.8-to-0.9.md).
13
+
14
+ ## Contents
15
+
16
+ - [Commands](#commands)
17
+ - [Staged runtime (`.gateforge/runtime.yml`)](#staged-runtime-gateforgeruntimeyml)
18
+ - [Harness and run history](#harness-and-run-history)
19
+ - [Existing-test reuse (`gateforge tests`)](#existing-test-reuse-gateforge-tests)
20
+ - [Advisory pytest diagnostics](#advisory-pytest-diagnostics)
21
+ - [Enforcement](#enforcement)
22
+ - [Contract capabilities](#contract-capabilities)
23
+ - [Configuration](#configuration)
24
+ - [Plugin invocation](#plugin-invocation)
25
+ - [Endpoint plane rules (`.gateforge/planes.json`)](#endpoint-plane-rules-gateforgeplanesjson)
26
+ - [Endpoint capability rules (`.gateforge/endpoints.json`)](#endpoint-capability-rules-gateforgeendpointsjson)
27
+ - [Proposing planes at init (`gateforge init --planes`)](#proposing-planes-at-init-gateforge-init---planes)
28
+ - [test-gates protocol (G6 surface)](#test-gates-protocol-g6-surface)
29
+ - [Limitations](#limitations)
30
+ - [Pick a goal, not a wall of flags](#pick-a-goal-not-a-wall-of-flags)
31
+ - [Agent loop](#agent-loop)
32
+ - [Fix a failing test without a full run](#fix-a-failing-test-without-a-full-run)
33
+ - [What the gate catches that ordinary tests can miss](#what-the-gate-catches-that-ordinary-tests-can-miss)
34
+ - [Running in CI](#running-in-ci)
35
+ - [Gate strictness and flaky tests](#gate-strictness-and-flaky-tests)
36
+ - [Run the whole proof with one command](#run-the-whole-proof-with-one-command)
37
+ - [The witnessed CI job](#the-witnessed-ci-job)
38
+ - [Known limitations](#known-limitations)
39
+
40
+ ## Commands
41
+
42
+ | Command | Purpose | Exit codes |
43
+ | --- | --- | --- |
44
+ | `gateforge init [--preset light\|normal\|strict] [--explain-presets] [--languages <comma,list>] [--plugins <comma,list>] [--accept-recommended] [--no-scan] [--proof overlay\|observe] [--blocking] [--no-blocking] [--pre-commit] [--no-pre-commit] [--ci] [--no-ci] [--planes] [--no-planes] [--strict-e2e] [--docs-exclude <folder,...>] [--docs-exclude-file <path>] [--confirm-doc-exclusions]` | Scan the repo (heuristics, no network), print the recommended install (plugins, persistence policy, transport-only HTTP policy for consumed endpoints, overlay proof), and write the standard Gateforge scaffold. Idempotent — never overwrites existing files unless `--confirm-doc-exclusions` approves an exclusion update. It also appends Gateforge's own engine state (`.gateforge/test-gates/`) to `.gitignore`, and on a repository that already has code it names `gateforge adopt` as the way through the debt the first commit will meet. `pack-task` is opt-in only (`--plugins`); `--proof observe` skips the overlay scaffold and prints the observe wiring checklist instead. Default language: `python`. `--preset` applies one goal in one step (`light` -> `mode: warn`, no hooks; `normal` -> `mode: changed` + pre-commit hook + CI job; `strict` -> `mode: strict` + staged gate + pre-push receipt check + CI job) and prints what it wrote plus `undo:` lines for created and in-place-changed files; `--explain-presets` prints that mapping and writes nothing. In a terminal init asks the same question instead; with no terminal and no `--preset` it writes `light` only and says so on one line with the `--preset` flag that changes it. The negative forms (`--no-blocking`, `--no-pre-commit`, `--no-ci`, `--no-planes`) answer the matching question without a prompt. A preset never writes a waiver, an adopted baseline or a plane rule, and an existing `.gateforge.yml` is never rewritten. `--strict-e2e` writes the `enforcement` block and refuses unavailable required proof channels. | 0/1/2 |
45
+
46
+
47
+
48
+ | `gateforge next [--changed] [--json]` | Print the ONE blocking next action (`next`/`cause`/`why`/`do`; `--json` adds `remainingBlocking` and route-specific `guidance` when relevant). For an endpoint with no plane, ask which boundary owns its data and show the owner-reviewed choices; internality remains owner-only. Navigation, not the gate: never requires an E2E receipt. Exit 0 clean, 1 next action, 2 config/usage. | 0/1/2 |
49
+ | `gateforge discover [--json]` | Run every configured detector over the expanded `project.paths` and dump the resource graph (default: human listing; `--json`: GF-canonical JSON). | 0 |
50
+ | `gateforge classify [--json] [--write-snapshot <path>]` | Recompute effective classifications from detector signals and print decisions, traces, and typed blocks. `classify plane` previews or explicitly appends an owner-reviewed endpoint plane rule to the existing `.gateforge/planes.json`; snapshots are derived review artifacts and never pipeline input. | 0/1/2 |
51
+ | `gateforge explain <resourceId\|path> [--json]` | Show one resource's detector signals, classification rules, decision fingerprint, typed blocks, and generated obligations. A repo-relative PATH is also a target: when no resource matches it, the command prints what the file is and what governs it (Gateforge policy input, declared gate input, owner-declared documentation folder, known source of a resource, or an unclassified change) with the steps that attribute it — this is the answer an unmapped `CHANGE_UNMAPPED` file needs. An unknown target stays unknown (exit 1). | 0/1/2 |
52
+ | `gateforge tests discover [--json] [--pytest]` | Inventory existing tests into the derived run-state catalog: static analysis reconciled with native Playwright enumeration (`--list`). Unresolved wrappers, parse errors, and inventory gaps are DATA (never an empty catalog — failed native enumeration is exit 2). `--pytest` additionally collects the configured diagnostic suites' node ids (`--collect-only`). Playwright enumeration runs ONE config (a repo-root config wins; otherwise the alphabetically first config one directory deep), and when the repo holds more than one the runner line names every config, the one used, why, and the ones NOT inventoried. `inventoryComplete=false` means a reconciliation gap (an enumerated-vs-static mismatch, an unresolved case, or a not-inventoried extra config), not a partial success. | 0/2 |
53
+ | `gateforge tests suggest [--changed] [--json]` | Resolve mappings for the run's obligations and produce reuse-ordered existing-test candidates with typed causes (`TEST_MAPPING_MISSING` / `TEST_KIND_UNKNOWN` / `TEST_MAPPING_AMBIGUOUS` / `TEST_MAPPING_STALE`). Candidates are RANKED by the evidence their catalog row carries (explicit tag, resource token in title/file, operation word, route segment, unmocked folder, minus mocks) with the matching reason printed as `why:`; the text surface prints the top five and names how many it hid, `--json` carries every candidate with its `rank` and `score`. With a candidate present the next action is to MARK it `observed-e2e` and run it under the witness — the overlay instruction belongs to `newTestNeeded: true`. When Playwright reports load errors and enumerates no tests, report one `TEST_INVENTORY_INCOMPLETE` with the error count and first error instead of stale-mapping fan-out; the action is to install the missing dependency and rerun Gateforge. An inspection surface, NOT a gate: exit 0 even with blocking problems. | 0/2 |
54
+ | `gateforge tests mark --test <key> --kind <kind> [--category <c>]... --obligation <id>... --reason "<text>"` | Declare an existing test in `.gateforge/test-map.yml` (see the test-reuse workflow below). Validates against the CURRENT catalog and obligation registry, writes atomically and idempotently, prints the exact diff. Never edits test files, never adds waivers, refuses contradictions. | 0/2 |
55
+ | `gateforge tests sync [--json]` | AST-only scan of test annotations; updates generated `source: annotation` entries in `.gateforge/test-map.yml` and leaves handwritten entries unchanged. Reports unresolved helpers with source locations; does not run tests. | 0/1/2 |
56
+ | `gateforge tests explain --test <key> [--json]` | Per-test report: requirements, existing-test identity, mapping origin, honest execution status, next action, `New test needed`. | 0/2 (unknown key → 2) |
57
+ | `gateforge tests diagnose [--suite <name>] [--json]` | Run the configured pytest diagnostic suites once per suite, isolated (own process, `GATEFORGE_*` stripped, finite timeout). Advisory: exit 0 completed run (≥1 pass, no unexpected failures), 1 test failures, 2 unavailable/incomplete (collection error, timeout, missing interpreter, interruption, zero tests, or only skipped/xfail). Never E2E proof. | 0/1/2 |
58
+ | `gateforge obligations [--json]` | Evaluate policies against the automatically classified graph and dump obligations, blocking entries, and claim assessments. | 0/1/2 |
59
+ | `gateforge check [--changed] [--staged] [--candidate-commit <sha>] [--require-e2e] [--timing] [--no-cache] [--format text\|json\|sarif]` | The full gate: discover → classify → obligations → claims → verdicts → report. `--timing` appends per-step wall-clock timings (detectors, test collection, TS scan, planning, total) — an additive report key in json and one line in text, never an input to any verdict. Detector and pytest-collection results are cached under the excluded run-state dir. Detector keys include plugin config, executable module/script bytes, Python import environment, inputs, interpreter packages, and Gateforge engine version; pytest keys include all Python/config file bytes, collector argv/environment, interpreter identity, and engine version. Unchanged successful pytest collections reuse their node ids; any changed Python byte recollects. Any uncertainty runs fresh. The report carries additive `cache: {hits, misses}` counts. `--no-cache` (or `GATEFORGE_NO_CACHE=1`, or a CI environment) disables cache reads and writes. | 0 clean/waived, 1 unresolved, 2 config/usage error |
60
+
61
+ | `gateforge test-gates [--changed] [--scope full\|changed] [--progress stderr\|file:<path>\|off] [--result-only] [--suite <cmd>] [--out <dir>] [--format F] [--witness-url <url>] [--run-token <token>]` | The progress stream (additive, `--progress`, or the `run.progress` config key) prints the registered expected-set size, one line per finished test with exact `N/M` counters and the catalog title, an alive line per quiet minute, and the finish line before grading. It is built from witness-side facts only and never from runner output; a failing test's first error line passes a credential guard and is replaced whole when it matches, and the full guarded diagnosis lands in `.gateforge/test-gates/failures.json`. `auto` (the default) is stderr under `CI=true` and off locally. The stream is not evidence and no gate reads it. Supervised `--changed` plans and runs mapped Playwright tests through the trusted adapter, checks planned/executed completeness, and seals an authenticated receipt only after complete success. `--scope changed` limits a sealed slice to obligations affected by changed files; incomplete mappings block, and `check --require-e2e` accepts it only when it covers every currently changed obligation. `--result-only` requires `--changed --scope changed`, reports selected results plus repository debt, and has no gate authority: without an external witness it uses private temporary state; with `--witness-url` it requires `--out` + `--run-token` shared with the external witness in a separate state directory (not the configured authoritative state directory). It never creates or clears a receipt. `--suite` remains legacy and cannot combine with `--changed` or redefine strict expected cases. Verifier keys use `GATEFORGE_WITNESS_VERIFIER_KEY` or the external key ring selected by `GATEFORGE_WITNESS_VERIFIER_KEY_FILE`. | 0/1/2 (suite failure forces 1) |
62
+ | `gateforge test-gates --chaos <seed> --result-only` | Timing chaos (additive, opt-in, E63): the witness observation proxy releases proxied app RESPONSES on a schedule derived from `<seed>` — a delay in `[0, maxDelayMs]` per response, and, for requests sharing a route key inside one test session, the option of releasing a later response before an earlier one. Only timing changes; bytes, status, headers and evidence semantics never do. The schedule is a pure function of (seed, session identity, route key, k), so the same seed replays it exactly, and the report plus the sealed execution result carry `chaos: { seed, maxDelayMs, reorder, schedule }` (route key = method + pathname, query stripped) with the text line `timing chaos: seed <n>`. Accepted only with `--result-only`: a chaos run finds races, it never seals a receipt. `run.chaos: { maxDelayMs, reorder }` tunes the bounds of a witness the run spawns itself (default 400 ms, reorder on) and never enables chaos by itself — without the flag every run, report and execution result is byte-identical to before. With `--witness-url` nothing is configured on the witness side: the plan travels with the supervisor-authenticated run-context binding (`options.chaos`), which the witness applies before the first session opens, so `run.chaos` tunes the bounds in both cases. A NORMAL run against a witness that was itself started with `GATEFORGE_CHAOS_SEED` exits 2 before any test runs, naming the variable to unset (a perturbed witness can never seal), and a witness too old to accept run options is refused for `--chaos` rather than reporting a schedule it never applied. A normal run against a witness with no plan — including one too old to have the route — is byte-identical to before. A seed that is not a non-negative integer exits 2 with one plain line. |
63
+ | `enforcement.twinPaths` (with `enforcement.twinQueryKeys`) | Twin path coverage (additive, opt-in, E64): links a raw test and its witnessed twin — by `twinOf` in `.gateforge/test-map.yml` or by the title convention `X [witnessed]` next to `X raw` (or the one `X raw: <description>`) — and compares the REQUEST SHAPES each side exercised (method, route template, and the values of the allowlisted query keys; never a URL, a body or a non-allowlisted value). A pair that disagrees is reported as `TWIN_PATH_DIVERGENT`, naming both tests and the exact differing value; `advisory` reports it and leaves the exit code alone, `block` makes it a blocking entry (exit 1). The raw twin's session is marked OBSERVATION-ONLY engine-side, so every submission from it is refused with 403: it can issue no record, no attestation and satisfy nothing, and contributes only its shapes. Absent (or set with no pair linked), nothing is wired, no state file is written and the report is byte-identical. With `--witness-url` the shape plan travels with the run-context binding (`options.twinShapes`: the allowlist and the route inventory as templates), so a repository's own witness needs no twin environment; a witness too old to accept run options records nothing and the run says so in one line instead of reporting twins that agree because nobody looked. |
64
+ | `gateforge broker commit --workspace <dir> --message <msg> [--receipt <path>] [--ref <ref>]` | Managed-mode commit broker (MECHANISM, not deployment): snapshots the workspace bytes into a throwaway index, recomputes the input + trusted-policy digests, verifies a valid non-stale gate receipt for EXACTLY those bytes, then creates the commit via compare-and-swap `git update-ref`. Typed rejections (`ENFORCEMENT_UNTRUSTED` / `EVIDENCE_STALE` / `RUN_INCOMPLETE` / `KEY_UNKNOWN` / `BROKER_CAS_MISMATCH` / `BROKER_UNSAFE_MESSAGE`); symlinks/submodules are typed rejections. Verifier keys use either supported environment source; the key file must be outside authority, workspace, and receipt artifact roots. | 0/2 |
65
+ | `gateforge key create|import-env|rotate|retire [--file <path>] --confirm` | Owner-only key ceremony. With no `--file` the ring is `${XDG_CONFIG_HOME:-$HOME/.config}/gateforge/verifier-keyring.json` — the parent directory is created, mode `0600` — and every later command reads that same path, so no `GATEFORGE_WITNESS_VERIFIER_KEY_FILE` export is needed; pass `--file <path>` AND export that variable only when the ring lives elsewhere. Creates, imports, rotates, or retires keys without printing secrets. | 0/2 |
66
+ | `gateforge pre-commit --scope staged\|full` | The witnessed commit gate: freezes the Git index, materializes it into a scratch checkout, prepares the candidate's staged runtime (`.gateforge/runtime.yml` — below), runs the supervised witness gate INSIDE that checkout (`staged`: only tests mapped to obligations affected by the staged paths, `EVIDENCE_SCOPE_INCOMPLETE` blocks an unmapped affected obligation; `full`: the complete relevant mapped suite), validates the fresh receipt against the same checkout, rechecks the original index/HEAD/MERGE_HEAD, and copies only Gateforge audit artifacts (run state incl. runtime logs) back. Runtime preparation/readiness failures are typed (`RUNTIME_PREPARATION_FAILED` / `RUNTIME_READINESS_FAILED`); child process groups are cleaned up on every exit path. Install via `gateforge init --blocking --witnessed staged\|full`. | 0/1/2 |
67
+ | `gateforge enforcement doctor [--json]` | Reports verified enforcement `level` (0–3), hook activation, wired CI templates, and read-only GitHub/GitLab branch-protection results; missing credentials or uncertain responses remain `not verified`. A local hook never counts as server protection. Its `engine:` line reports the install provenance npm's own metadata proves: a tarball/directory install (read from `node_modules/.package-lock.json`, or the manifest's `_resolved`) is named as such instead of claiming the registry, and an install with no readable metadata is reported as unproven rather than as an all-clear. The receipt's `engine.source` is receipt-bound and keeps its meaning. Diagnostic only: exit 0 whenever it runs. | 0/2 |
68
+ | `gateforge enforce [--ci github\|gitlab]` | Add blocking wiring to an initialized repository. The provider defaults to GitLab unless GitHub is the only detected CI provider; the explicit flag selects GitHub Actions or GitLab CI. Appending to an EXISTING `.pre-commit-config.yaml` is announced as an action on one line, naming the file as the repository's own and printing the exact way back (`git restore -- .pre-commit-config.yaml` for a tracked file; for an untracked one, which has nothing to restore, the line says to delete the appended entry). The generated GitHub workflow installs `@gate-forge/cli@<version>` from the registry unless `GATEFORGE_CI_ENGINE_SOURCE` is set when the generator runs: it then installs that one npm specifier (a `.tgz` path, a directory, or any specifier) through the step environment, for a release that is not on the registry. Unset the variable and rerun for the registry install. | 0/2 |
69
+ | `gateforge adopt` | Adopt an EXISTING repository: run it once, after `init`, on a project that already has code and therefore already has findings. Records today's blocking findings (pin-#2 obligation fingerprints, blocking entries, and the classification-blocked resource identities) into `.gateforge/baselines/obligations.json`, sanctioned by a dated, count-annotated receipt `.gateforge/baselines/adoption.json` — without that receipt a baseline forgives nothing — then applies the blocking wiring through the same idempotent path as `init --blocking`. It is the ONE sanctioned bulk-add and only once per repository: a second `adopt` is a no-op success. The recorded set is shrink-only (`gateforge baseline update` shrinks it) and never forgives new work. With `enforcement.strictE2E: true`, a baselined E2E obligation is not proof and blocks with `ENFORCEMENT_UNTRUSTED` again as soon as a change touches it. `adopt --help` prints this contract. | 0/2 |
70
+ | `gateforge baseline update <fp...>` | Shrink the baseline to a strict subset (invariant 4). | 0/2 |
71
+ | `gateforge baseline diff <before> <after>` | Compare adopted obligations by ID without printing fingerprints. | 0/2 |
72
+
73
+ On a repo that already has Gateforge files, `init` reports only what THAT run did: it keeps an existing `.gateforge.yml` and says so instead of claiming to write a preset, and the `undo:` lines it prints name every path the run created (`rm -rf`) and every file it changed in place (`git restore --`, for an appended `.gitlab-ci.yml` include, an appended `.pre-commit-config.yaml` entry, or an added ignore rule) — so following them can never delete pre-existing config, baselines, waivers, hooks or CI files, and a run that changed nothing prints no undo line at all. A preset that wires no local hook says whether your existing commit hook and/or CI job still decide what blocks your commits.
74
+
75
+ `init` also adds Gateforge's own engine state to `.gitignore` (`.gateforge/test-gates/` — the run catalog, plugin caches, receipts and history the engine regenerates on every run). Without it the first `git add -A` stages the run cache and the gate then blocks on its own files. The file is created when absent and appended to when present, your own lines are preserved, and a second run reports it as already ignored instead of appending again. The same run prints the `undo:` line for it.
76
+
77
+ `init` reads the repository to recommend detectors, and prefers quoting evidence from application code: hidden dot-folders (agent tooling, tool caches, leftover working directories) are not scanned at all, and a file inside an `archive/`, `vendor/`, `generated/`, `fixtures/`-style directory is only quoted when no application file carries the same signal. The generated `.gateforge.yml` carries the matching default excludes, so the detectors make the same choice.
78
+
79
+ `init` on a repository that ALREADY has code says so and names the way through the debt it will report on day one: `gateforge adopt` records today's findings as forgiven, shrink-only, and — under `strictE2E` — still blocks on an adopted E2E obligation as soon as a change touches it. A fresh, empty project never sees that block.
80
+
81
+ `--docs-exclude <folder,...>` and `--docs-exclude-file <path>` are the same owner assertion in two spellings (the file holds one folder per line; blank lines and `#` comments are ignored); they combine into one deduplicated list, and the interactive prompt says the flag exists so a long list does not have to be typed into one prompt.
82
+
83
+ `--unmatched-routes block|warn` answers, ahead of the terminal question, the
84
+ one thing a NEW repository must say about routes whose name matches no
85
+ discovered table: gate commits on them, or only report them. In a terminal
86
+ `init` asks once ("Routes whose name matches no table: block commits, or
87
+ warn only? [block/warn]"); headless it writes `warn` and prints the exact
88
+ key that turns blocking on. A repository that already has a
89
+ `.gateforge.yml` is never asked and never rewritten here — it keeps saying
90
+ nothing, which the `check`/`next` banner keeps pointing at.
91
+
92
+ The cache is disabled by `--no-cache`, `GATEFORGE_NO_CACHE=1`, or recognized CI-provider markers (`GITHUB_ACTIONS`, `GITLAB_CI`, `BUILDKITE`, `CIRCLECI`, `JENKINS_URL`, `TF_BUILD`). A bare `CI=true` does not disable it.
93
+
94
+ Global flags: `--help`, `--version`. Exit codes per architecture contract 4:
95
+ `0` clean/waived, `1` unresolved obligations (or a failed/supervision-blocked
96
+ run), `2` config/usage error. `tests diagnose` has its own advisory contract
97
+ (0/1/2 above).
98
+
99
+ ### Result-only with an external witness
100
+
101
+ Start the witness with a dedicated state directory, then pass that same
102
+ directory and its run token to `test-gates`. The directory must be separate
103
+ from the configured authoritative `.gateforge/test-gates` directory:
104
+
105
+ ```sh
106
+ gateforge test-gates --changed --scope changed --result-only \
107
+ --witness-url "$GATEFORGE_WITNESS_URL" \
108
+ --out "$GATEFORGE_STATE_DIR" \
109
+ --run-token "$GATEFORGE_RUN_TOKEN"
110
+ ```
111
+
112
+ `test-gates` claim planning reads current Playwright annotations using a
113
+ disposable `GATEFORGE_STATE_DIR`, plus the tracked `test-map.yml`. It never
114
+ treats a previous run's `claims.json` as a declaration source.
115
+
116
+ The report remains `authority: non-authoritative`. The external-witness
117
+ state may contain this run's report and attestation, but this command never
118
+ creates, replaces, or clears a gate receipt. Pre-commit, hook, and CI gate
119
+ paths remain authoritative and do not accept `--result-only`.
120
+
121
+ ### Re-check one failing test in seconds (`--test`)
122
+
123
+ To re-confirm a handful of hand-picked tests you do not need a whole
124
+ suite. `--test` names them, and the run is witnessed exactly like a full
125
+ gate run — the same supervisor, the same run token, the same server-side
126
+ evidence:
127
+
128
+ ```sh
129
+ # one test (a logical key, or any unique substring of one)
130
+ gateforge test-gates --test 'backend/tests/test_x.py::test_commits' --result-only
131
+
132
+ # several at once — --test is repeatable
133
+ gateforge test-gates --test UC-53 --test UC-51 --result-only
134
+ ```
135
+
136
+ `--test` is accepted **only** together with `--result-only`. A
137
+ hand-picked list never seals a receipt, so combining `--test` with a
138
+ sealing run exits 2 and says so. The named run never reads, writes, or
139
+ clears a gate receipt, so `check --require-e2e` is unaffected, and it
140
+ carries `authority: non-authoritative` plus `outcome: partial-selection`
141
+ in the report.
142
+
143
+ A selector is resolved against the **planned** rows — the expected set
144
+ fixed before the run — never against raw runner output, so it can only
145
+ name a test the gate already planned. An exact logical key always wins;
146
+ otherwise a unique case-insensitive substring is used. An unknown or
147
+ ambiguous selector exits 2 and lists the candidate logical keys, because
148
+ a narrower selection is never guessed:
149
+
150
+ ```sh
151
+ $ gateforge test-gates --test 'session proxy' --result-only
152
+ gateforge: the selector 'session proxy' matches 2 planned tests — pick one exact logical key. Run `gateforge tests discover --json`. [TEST_SELECTOR_AMBIGUOUS]
153
+ candidate logical keys:
154
+ - tests/green.test.mjs#creates account through the session proxy
155
+ - tests/second.test.mjs#creates the billing account through the session proxy
156
+ ```
157
+
158
+ The report gains an additive `selectors` field naming exactly what each
159
+ selector resolved to, and the run uses the `named-selection` selection
160
+ mode, so it can never collide with a full or a diff-linked slice:
161
+
162
+ ```json
163
+ { "outcome": "partial-selection", "selectors": [{ "selector": "UC-53", "logicalKeys": ["pytest:backend/tests/test_x.py::test_commits"] }] }
164
+ ```
165
+
166
+ Selection works for every runner (Playwright, pytest, vitest, Cypress)
167
+ through the shared runner-adapter contract. Because it works from the
168
+ plan, it does not need the changed-file set — that is why `--test` is
169
+ useful when a fix touches a `.env`, a fixture, or a helper that no test
170
+ links to.
171
+
172
+ Each runner narrows to the named tests as far as it honestly can:
173
+ Playwright, pytest and vitest receive the exact `file:line` / node id /
174
+ anchored test name, so a named test never drags its file neighbours
175
+ along. Cypress cannot filter below the spec without a plugin the gate
176
+ refuses to trust, so it executes the whole spec, drops every unselected
177
+ outcome and session (an unselected test never becomes evidence), and
178
+ says `also ran N other test(s) in the same file — not graded`.
179
+
180
+ #### What a named run grades, and its exit codes
181
+
182
+ A named run grades **only the selection**: the obligations its selected
183
+ tests declare through the sidecar or native annotations. Everything else
184
+ — repository-wide policy, mapping and inventory findings, the coverage
185
+ policy — is still reported, under `repositoryDebt` and as
186
+ `not graded in a named run: N obligation(s)`, but never blocks: the run
187
+ never observed it. What still blocks is everything about the run itself
188
+ (supervision findings, lifecycle conflicts, intent failures, the witness
189
+ channel, evidence-context failures) and any finding that names a graded
190
+ obligation. The report and the diagnostic context both carry
191
+ `scope: "named"`, and the execution summary keeps the whole-repository
192
+ counts next to the selection's own.
193
+
194
+ | Exit | Meaning |
195
+ | --- | --- |
196
+ | `0` | every selected test passed and every obligation it declares is satisfied (or waived by the owner), with a complete run and no run-execution finding |
197
+ | `1` | anything else: a red selected test, an unproven graded obligation, an incomplete run, changed inputs, or a workspace that moved during the run |
198
+ | `2` | the selector could not be resolved (unknown or ambiguous) — nothing ran |
199
+
200
+ A named run never carries gate authority: it is `--result-only` only,
201
+ never creates, replaces or clears a receipt, and `check --require-e2e`
202
+ keeps reading the seal the authoritative run left. A run without
203
+ `--test` is unaffected by any of this.
204
+
205
+ ## Staged runtime (`.gateforge/runtime.yml`)
206
+
207
+ `gateforge pre-commit` executes the candidate inside a materialized checkout
208
+ that contains TRACKED bytes only — no installed dependencies, no built
209
+ assets, no application processes. The reviewed staged-runtime document
210
+ declares how that checkout becomes a runnable candidate. It is
211
+ security-sensitive: its bytes are hashed into the trusted policy digest and
212
+ the authenticated input snapshot, so a candidate that edits its own runtime
213
+ commands cannot approve the edit in the same commit.
214
+
215
+ ```yaml
216
+ schemaVersion: 1
217
+ prepare:
218
+ command: npm ci --offline # or pnpm/bun/uv — frozen install, build steps
219
+ reuse: [node_modules] # dependency dirs EXPLICITLY allowed to link from the user repo
220
+ timeoutSeconds: 600
221
+ preflight: # optional cheap checks before prepare
222
+ - { name: lint, command: npm run lint, timeoutSeconds: 60 }
223
+ health: # optional probes before/after the suite
224
+ - { name: database, tcp: '127.0.0.1:5432', timeoutSeconds: 5 }
225
+ - name: worker-startup
226
+ logAbsent:
227
+ command: ./tools/recent-worker-logs.sh
228
+ pattern: 'worker startup failed'
229
+ services: # candidate-owned app/database/worker processes
230
+ - id: app
231
+ command: node server.js --port ${service:app:port}
232
+ attested: true # fronted by the gate's attestation proxy
233
+ fingerprint: prod-v1 # GF-13 marker (reviewed adapters must declare the same)
234
+ target: true # this proxy URL becomes the run's attested target
235
+ ready: { log: 'listening on', timeoutSeconds: 60 } # or http: <url>
236
+ envAllowlist: [DATABASE_URL] # operator env names for services and supervised tests
237
+ executionTimeoutSeconds: 1800 # whole-run budget handed to the supervised gate
238
+ ```
239
+
240
+ Contract highlights:
241
+
242
+ - Services start from the CHECKOUT bytes (never the worktree) in their own
243
+ process groups; readiness (`log` regex or `http` 2xx), startup, and
244
+ execution timeouts are bounded; stdout/stderr are captured to
245
+ `<run-state>/runtime/<id>.log`; teardown happens on success, failure,
246
+ timeout, and interruption (SIGINT/SIGTERM kill the whole groups).
247
+ - `prepare.preflight` checks run in order before `prepare`; the first
248
+ non-zero exit blocks preparation with `PREFLIGHT_FAILED <name>` and the
249
+ command's last 30 output lines.
250
+ - `health` supports one `tcp`, `http`, `command`, or `logAbsent` probe per
251
+ entry. `logAbsent` runs its declared log command after startup and blocks
252
+ when the configured regex is found. A failed startup probe blocks with
253
+ `FIXTURE_UNHEALTHY <name>`; the post-run probe is advisory and does not
254
+ change test verdicts. HTTPS uses normal certificate verification.
255
+ - Every `prepare.reuse` tree is constrained to a normalized repository-relative
256
+ path. Its reachable dependency bytes are hashed into the authenticated
257
+ input identity, so changing an ignored reused dependency invalidates the
258
+ receipt even though the checkout uses a link.
259
+ - `${service:<id>:port}` / `${service:<id>:url}` placeholders are
260
+ substituted by the supervisor and injected into every service's
261
+ environment (`GATEFORGE_SERVICE_PORT_<ID>` / `GATEFORGE_SERVICE_URL_<ID>`).
262
+ - The attested target is the process THE GATE started from the frozen
263
+ candidate — a bare target URL proves nothing. The receipt binds the raw-
264
+ ingested tree of the prepared checkout (`targetArtifactDigest`), and the
265
+ user's index is rechecked before authorization.
266
+ - ABSENT document = no bridge, no services (fail closed): discovery that
267
+ needs installed dependencies blocks honestly instead of silently reusing
268
+ the worktree's environment.
269
+
270
+ ## Harness and run history
271
+
272
+ The optional `.gateforge.yml` `harness` section declares `up`, `reset`,
273
+ `seed`, `health`, and `down` shell commands. Supervised runs invoke configured
274
+ setup commands in that order before the suite; the first failure blocks the
275
+ suite, prints its last 30 output lines, and still attempts `down`. Gateforge
276
+ executes these commands but does not manage containers or other infrastructure.
277
+ Absent `harness` preserves current behavior.
278
+
279
+ ```yaml
280
+ harness:
281
+ up: ./tools/test-up.sh
282
+ reset: ./tools/test-reset.sh
283
+ seed: ./tools/test-seed.sh
284
+ health: ./tools/test-health.sh
285
+ down: ./tools/test-down.sh
286
+ serviceLogs:
287
+ command: docker compose logs --no-color --tail ${lines} ${service}
288
+ services: [database, worker]
289
+ lines: 100
290
+ ```
291
+
292
+ On a failed supervised run, `serviceLogs` runs the declared log command for
293
+ each service and saves the configured tail to
294
+ `<run-state>/diagnostics/service-logs.txt`. Log capture is advisory and does
295
+ not change test verdicts.
296
+
297
+ Each `verifyPersistence` adapter call is timed in
298
+ `<run-state>/diagnostics/adapter-timing.jsonl`; calls over two seconds also
299
+ print a warning. Timed-out tests report the observed app/runner time separately
300
+ from their summed witness-adapter time. These diagnostics do not alter the
301
+ receipt or verdict.
302
+
303
+ Run history is opt-in through `.gateforge.yml` `history`; when configured,
304
+ retention defaults to 14 days and is capped at 90. Set `retentionDays: off`
305
+ to disable it. History is stored beneath the ignored test-gates state and is
306
+ not receipt input. Query it with `gateforge history [--test TEXT] [--failed]
307
+ [--since ISO-8601]`.
308
+
309
+ ## Existing-test reuse (`gateforge tests`)
310
+
311
+ The reuse-first workflow: inspect what exists, declare what is unclear, run
312
+ it, and add a new test only for a confirmed behavior gap. The fixed agent
313
+ sequence is: `tests discover` → `tests suggest` → `tests sync` for annotated
314
+ tests or `tests mark` for hand-written sidecar mappings → run the suite under
315
+ supervision → `check --require-e2e`.
316
+
317
+ `tests discover` writes the catalog to `.gateforge/test-gates/test-catalog.json`
318
+ — a DERIVED artifact under the excluded run-state directory, never a pipeline
319
+ input and never beside the tests it inventories. Logical keys are stable
320
+ (`playwright:<project>:<file>:<title path>`; `-` when the runner has no
321
+ project) so manual mappings survive comment edits; source digests still move,
322
+ so old evidence goes stale. Renamed/deleted tests and removed parameters
323
+ surface as stale or ambiguous mappings — never a silent reassignment.
324
+
325
+ `tests sync` statically resolves direct Gateforge annotations and local pure
326
+ helpers that return literals. It never loads a test runner or executes a test.
327
+ Entries marked `source: annotation` are regenerated; handwritten entries are
328
+ preserved. Unresolvable annotations are printed as `UNRESOLVED` with the test
329
+ file and location. `check` reports missing/extra generated claims as the
330
+ non-blocking `TEST_MAP_OUT_OF_SYNC` advisory for this release period; run
331
+ `gateforge tests sync` to reconcile them.
332
+
333
+ `tests mark` validates the declaration against the current catalog AND the
334
+ current obligation registry (an unknown obligation id or test key is a
335
+ precise exit-2 error) before writing `.gateforge/test-map.yml`:
336
+
337
+ ```yaml
338
+ schemaVersion: 1
339
+ tests:
340
+ - key: playwright:chromium:e2e/accounts.spec.ts:deletes an account
341
+ selector:
342
+ runner: playwright
343
+ project: chromium
344
+ file: e2e/accounts.spec.ts
345
+ titlePath: [Accounts, deletes an account]
346
+ kind: browser-e2e
347
+ categories: [persistence.delete]
348
+ claims: [tenant.accounts:persistence:delete]
349
+ reason: Existing journey deletes the selected account.
350
+ ```
351
+
352
+ `--kind` is one of `browser-e2e`, `observed-e2e`, `api-e2e`, `unit`, `integration`,
353
+ `component`, `unknown`. A declaration is INTENT, never proof:
354
+
355
+ - Native `{ type: 'gateforge', description: '<obligation id>' }` annotations
356
+ keep working; sidecar entries and native claims normalize through ONE
357
+ resolver. Exact duplicate claims deduplicate; contradictions block with
358
+ both source locations (`TEST_MAPPING_AMBIGUOUS`).
359
+ - An explicit kind may resolve `unknown` — and `observed-e2e` may refine an
360
+ inferred `browser-e2e` (same journey, witness-watched instead of
361
+ engine-driven) — but cannot override observed mocking or any other
362
+ strong code-signal inference — `tests mark` refuses with
363
+ both locations instead of writing the file.
364
+ - Agents may edit the sidecar directly; both paths receive identical
365
+ validation. `mark` is idempotent: re-running an exact declaration writes
366
+ nothing and reports `no changes`.
367
+ - Nothing here waives, weakens, or satisfies anything: a mapped test with no
368
+ witnessed evidence for this change grades `EVIDENCE_NOT_COLLECTED` —
369
+ blocking.
370
+
371
+ `tests suggest` emits `newTestNeeded: true` only when no suitable existing
372
+ candidate survives resolution. An unsupported proof channel produces a
373
+ capability task (`VERIFIER_UNSUPPORTED`), never a request to generate more
374
+ tests.
375
+
376
+ ### Ranked candidates
377
+
378
+ Candidates are RANKED by the evidence the catalog row itself carries, not
379
+ listed alphabetically: an explicit `@crud(...)` tag, a resource token in the
380
+ title path or the file, the obligation's operation word, a route segment from
381
+ the run's route inventory, a `real/` (unmocked) folder, minus a mock signal.
382
+ Every weight is additive and printed as a `why:` line, so the order explains
383
+ itself — the score is never a bare number. Ties break on the logical key, so
384
+ the list is deterministic. The text surface prints the top five and says how
385
+ many it hid; `--json` carries every candidate with its `rank` and `score`:
386
+
387
+ ```text
388
+ obligation: tenant.accounts:persistence:create cause: TEST_MAPPING_MISSING
389
+ candidates (ranked by evidence):
390
+ - #1 playwright:chromium:tests/e2e/real/account_create_matrix.spec.js:company tenant persists (tests/e2e/real/account_create_matrix.spec.js)
391
+ why: explicit tag names this obligation's resource 'accounts'
392
+ why: lives in a 'real' folder (unmocked)
393
+ ... and 286 more candidate(s) — run `gateforge tests suggest --json` for the full ranked list
394
+ ```
395
+
396
+ In `--json`, each candidate's `overlaps` lists the obligations that
397
+ DECLARE that test (a `test-map.yml` entry or a `@gateforge` annotation) —
398
+ not every obligation the test merely came up as a candidate for. The
399
+ candidate list itself is unchanged and still carries every candidate.
400
+
401
+ `already declared for: …` is printed only when a DECLARATION exists (a
402
+ `test-map.yml` entry or an `@gateforge` annotation). An inferred or
403
+ prior-run binding is a suggestion, never a declaration, and no longer prints
404
+ that line.
405
+
406
+ ### One instruction, not two
407
+
408
+ When a candidate exists, the suggestion's next action is to MARK that
409
+ existing test `observed-e2e` and run it under the witness
410
+ (`gateforge tests mark --test <key> --kind observed-e2e --obligation <id>
411
+ --reason "…"` then `gateforge test-gates --changed`). The overlay
412
+ instruction — write `tests/e2e/gateforge/<resource>.<op>.spec.js` — belongs
413
+ to `newTestNeeded: true`, i.e. no existing test fits. A suggestion block
414
+ never tells you to write a new overlay test and, in the same breath, to
415
+ reuse the test it just listed.
416
+
417
+ ### A declared mapping is visible in `check`
418
+
419
+ After `tests mark`, `check` says `mapped to: <test keys> (not yet witnessed)`
420
+ for every obligation whose test ids are declared but whose records were not
421
+ consulted, and its next action names the command that collects the evidence
422
+ (`gateforge test-gates --changed`) instead of the generic "write a test"
423
+ advice. The JSON report adds `declaredTests` and
424
+ `mappingState: "declared" | "declared-not-witnessed"`. Only DECLARED ids
425
+ appear there — an inferred or prior-run binding never does.
426
+
427
+ ### Runner file scope (`tests discover`)
428
+
429
+ The static scan is seeded from Gateforge's own include globs, so it finds
430
+ test-shaped calls anywhere in the repository — including files no configured
431
+ runner would ever collect. Each runner's OWN file selection is therefore read
432
+ as data and decides the row's runner:
433
+
434
+ - Playwright: the enumeration's project-graph reporter records each
435
+ project's resolved `testDir`, `testMatch` and `testIgnore`. A file outside
436
+ every project's selection is not a playwright test and is not catalogued as
437
+ one.
438
+ - Vitest: `vitest.config.*` / `vite.config.*` (at any depth, bounded) are read
439
+ with the TypeScript AST only — `test.include`, `test.exclude`,
440
+ `test.globals` literals, never an evaluated expression. A vitest suite
441
+ inside a playwright-configured repository is catalogued as a vitest row
442
+ with a `runner-file-scope` weak signal naming the evidence; with
443
+ `globals: true`, a bare `describe`/`it` is a registration the runner owns,
444
+ not an `unresolved-test-alias` gap.
445
+
446
+ Every selection is FAIL-OPEN and says so. A pattern that cannot be translated
447
+ (`!`-negated class, unbalanced group), a computed value, a function-valued
448
+ selector, or a missing config makes the scope select everything — today's
449
+ behaviour — and the runner summary line states which selection could not be
450
+ read. A file that NO runner's selection claims keeps the configured runner
451
+ and stays a blocking row (`reconciliation-static-only`, carrying a
452
+ `no-runner-claims-file` weak signal that says so): ownership is never
453
+ invented.
454
+ `inventoryComplete` is judged over the CONFIGURED runner's unresolved rows.
455
+
456
+ ## Advisory pytest diagnostics
457
+
458
+ Register existing pytest suites under `diagnostics.suites` in
459
+ `.gateforge.yml` (explicit, tracked configuration — gateforge never scans
460
+ directories or executes commands on its own; only the `pytest` runner has an
461
+ adapter today):
462
+
463
+ ```yaml
464
+ diagnostics:
465
+ suites:
466
+ - name: backend-pytest
467
+ runner: pytest
468
+ cwd: server
469
+ argv: [python, -m, pytest]
470
+ testPaths: [tests]
471
+ timeoutMs: 600000
472
+ hostLoad: true # opt-in: sample load average, CPU count, and disk space
473
+ ```
474
+
475
+ `gateforge tests diagnose` runs each configured suite once against the
476
+ current inputs (drift around discovery refuses the run) and prints a SEPARATE
477
+ diagnostic report with `DIAGNOSTIC_TEST_FAILURE` /
478
+ `DIAGNOSTIC_RUN_INCOMPLETE` / `DIAGNOSTIC_RESULT_STALE` causes. Skips and
479
+ expected failures stay explicit counters; a run of only skipped/xfail cases
480
+ is INCOMPLETE (exit 2), never a passing alarm. Diagnostic results are never
481
+ fed into claims, witness records, baselines, waivers, or E2E satisfaction,
482
+ and are never merged into E2E pass counts — 100 passing pytest tests do not
483
+ clear one missing browser obligation. When the supervised run executes the
484
+ same suites, their results are displayed separately without changing the E2E
485
+ exit decision.
486
+
487
+ When enabled, the supervised run writes `diagnostics/host-load.json` at start,
488
+ every 30 seconds, and at completion. Failed tests completed while load exceeds
489
+ 1.5× CPU count get a note with the nearest preceding sample. Free disk below
490
+ 5% at start emits a warning; load and disk data are diagnostic only.
491
+
492
+ ## Enforcement
493
+
494
+ Two named modes (ADR 0005 D1); the CLI never reports a hook as more than it
495
+ is.
496
+
497
+ When a witnessed pre-commit run reaches a blocking result, Gateforge reports
498
+ how many tests the current commit selected and, when recorded, how long the
499
+ last full run took. This is cost context only; the current run and its receipt
500
+ still decide whether the commit passes.
501
+
502
+ **Standard mode** — an active local hook PLUS a mandatory trusted server
503
+ check:
504
+
505
+ - `gateforge init --blocking` installs a static pre-commit check and, for
506
+ new configs (`enforcement.receiptStage: pre-push`), a pre-push hook that
507
+ checks each pushed commit tip with `check --candidate-commit <sha>
508
+ --require-e2e`. The static lane does not require a receipt; the pre-push
509
+ lane does. Existing configs without `receiptStage` keep their previous
510
+ pre-commit behavior. Hook activation is verified; foreign hooks are never
511
+ overwritten.
512
+ By default, `init --blocking` writes `.gateforge/ci/gitlab-gateforge.yml`
513
+ plus the `.gitlab-ci.yml` include. `gateforge enforce --ci github` writes
514
+ `.github/workflows/gateforge.yml` instead. Both strict templates run
515
+ `test-gates --changed`, then verify the exact CI commit with
516
+ `check --changed --candidate-commit "$CI_COMMIT_SHA"` (GitLab) or
517
+ `--candidate-commit "$GITHUB_SHA"` (GitHub). The verifier key and policy
518
+ pin come from protected CI secrets.
519
+ `init --blocking` prints exact GitHub/GitLab protection commands for
520
+ owner review; it never runs server mutations itself.
521
+ Protect the branch, require its Gateforge pipeline to succeed (skipped jobs
522
+ do not count), exclude agent roles from direct pushes, and use an
523
+ organization-controlled pipeline execution policy so a candidate cannot
524
+ remove the gate job. THE HONEST LIMIT: `--no-verify`, an alternate
525
+ `core.hooksPath`, direct plumbing, or an unrelated clone bypass any local
526
+ hook — keeping bypassed commits out of protected history is the server's
527
+ job, not the hook's.
528
+ `gateforge enforcement doctor` reports level 0–3. It reports level 3 only
529
+ when a read-only provider API confirms branch protection plus a required
530
+ Gateforge status check or passing-pipeline setting.
531
+ - The CI template checks that the installed `@gate-forge/cli` version equals
532
+ the version that generated it. Add that exact version as a root
533
+ `devDependency`. The template uses a package-manager lockfile when present;
534
+ without one, it installs from the manifest. Set
535
+ `GATEFORGE_CI_NESTED_PACKAGE_DIRS` to a space-separated list such as `e2e`
536
+ when the Playwright config imports dependencies from nested packages.
537
+ `enforce` and `adopt` use the same install and version checks, then run the
538
+ static `check --changed` gate. They do not recommend gating on report counts.
539
+ - A generated hook uses `GATEFORGE_DEV_ENGINE` when set, then the
540
+ repository-pinned CLI, `.gateforge/engine`, and `GATEFORGE_CLI`. A global
541
+ `gateforge` on `PATH` is a last-resort fallback with a warning.
542
+ - `check --staged [--require-e2e]` gates the EXACT staged bytes: the index
543
+ tree is frozen, materialized into an isolated scratch checkout, and the
544
+ regular gate runs against those bytes (never the worktree). The candidate
545
+ is re-checked after the gate — any index/HEAD drift during the run is a
546
+ typed `ENFORCEMENT_UNTRUSTED` block. Partial staging is fine; symlinks,
547
+ submodules, and unmerged index entries are typed blocks, never fallbacks.
548
+ - `check --changed --require-e2e` is the CI-side strict gate over the checked-
549
+ out candidate.
550
+ - `--strict-e2e` (config `enforcement.strictE2E`) makes waived or baselined
551
+ in-scope E2E obligations NOT proof (they block with `ENFORCEMENT_UNTRUSTED`
552
+ — no automatic debt forgiveness), and blocks unclassified changed files as
553
+ `CHANGE_UNMAPPED` until a resolved mapping covers them. Candidate edits to
554
+ policies, classification, adapters, waivers, baselines, or the mapping
555
+ sidecar cannot authorize weaker checks: gates evaluate under the trusted
556
+ policy digest, so a weakened candidate fails closed until a separate
557
+ trusted update is accepted.
558
+
559
+ **Gateforge's own files are policy inputs.** The config, the policy,
560
+ classification, behavior and runtime documents, the exclusion declarations,
561
+ the mapping sidecar, the adapter/waiver/baseline/quarantine records, the
562
+ generated gate wiring (hook script, CI job templates, `GATEFORGE.md`, the
563
+ overlay-proof README, the engine reference) and your CI/pre-commit config
564
+ *while they still carry Gateforge's managed block* are policy inputs, not
565
+ product files: a change to one of them is never an unmapped `CHANGE_UNMAPPED`
566
+ change, and a change set that contains only those files cannot change product
567
+ behavior — so it does not drag your adopted E2E obligations into a strict
568
+ re-grade, and the setup/adopt commit passes `check --changed` without
569
+ `--no-verify`. Their integrity is governed exactly as before: they are inside
570
+ the approved policy digest, so a change to them needs your pin to be
571
+ re-approved, and a mismatching pin still blocks. Deleting the gate job from
572
+ your CI config, or
573
+ the entry from `.pre-commit-config.yaml`, is not a policy input — it goes back
574
+ to blocking. Everything Gateforge does not own (your source, tests, runner
575
+ config, manifests, ignore controls, documentation you did not exclude) keeps
576
+ today's treatment, including the scope expansion that makes a policy change
577
+ re-check the whole repository.
578
+
579
+ **Receipts (the strict saved-state gate).** `check --require-e2e` accepts
580
+ only an authenticated gate receipt sealed by a COMPLETE supervised run for
581
+ the current input digest and trusted policy digest:
582
+
583
+ - no receipt (old record bundles included) → `RUN_INCOMPLETE`;
584
+ - receipt for different bytes/inputs → `EVIDENCE_STALE` (rerun for the
585
+ exact candidate);
586
+ - forged/tampered receipt → `ENFORCEMENT_UNTRUSTED`.
587
+
588
+ Receipts sealed by newer Gateforge versions add the `engine` identity
589
+ (`version`, `source`, and `unpublished`) inside the authenticated envelope.
590
+ When present, `check --require-e2e` requires the installed CLI version to
591
+ match the version that sealed the receipt. Legacy receipts without `engine`
592
+ continue to verify as before.
593
+
594
+ `test-gates --changed` seals a receipt only after planned-vs-executed
595
+ completeness, evidence grading, and a successful runner exit: zero selected
596
+ tests, skips, `.only`, retries, teardown failures, and incomplete shards all
597
+ fail the run. Identical authenticated inputs may reuse a prior receipt
598
+ (printed as `reused receipt <id>`); any changed input forces a fresh run.
599
+ Without the verifier key in the trusted environment nothing can be sealed
600
+ and `--require-e2e` blocks — it never downgrades to a weaker pass.
601
+
602
+ **Owner-declared documentation exclusions (explicit trust mode).** By default,
603
+ Gateforge hashes all inputs and all candidate files. On a terminal, the first
604
+ `gateforge init` asks for documentation-only folders to exclude. Automation can
605
+ use `gateforge init --docs-exclude docs,handbook`; a non-interactive run with no
606
+ option keeps the default. Gateforge writes the approved declaration to
607
+ `.gateforge/docs-exclusions.yml` and prints the candidate trusted-policy digest
608
+ to approve through the protected `GATEFORGE_APPROVED_POLICY_DIGEST` setting.
609
+ Gate checks refuse to use the exclusions until that external pin matches. A
610
+ later change to the exclusion declaration changes the digest; use
611
+ `--confirm-doc-exclusions` when `init` changes an existing approval.
612
+
613
+ The project states these folders do not affect the product or its tests.
614
+ Gateforge does not prove this. If application or test code reads an excluded
615
+ file, a later edit can make old evidence look valid without running the tests
616
+ again. Reports show the approved folders, pin identity, and this reduced
617
+ guarantee. Gateforge rejects exclusions that contain configured scan inputs,
618
+ source files, gate or trust metadata, manifests, lockfiles, or symlinks.
619
+ Every file must also use a supported document, data, or raster-image format.
620
+ Besides Markdown, reStructuredText, plain text, PDF, and static raster images,
621
+ an excluded folder may hold `.json`, `.yaml`, `.yml`, `.csv`, and `.html`
622
+ files. Refusal is by name first, so `package.json`, `tsconfig.json`,
623
+ `.pre-commit-config.yaml`, `.gitlab-ci.yml`, `pnpm-workspace.yaml`,
624
+ `composer.json`, any `*.config.*` file, and lockfiles stay refused inside an
625
+ excluded folder. MDX, WASM, SVG, and unknown formats fail closed. HTML is
626
+ accepted only as content of a declared folder; elsewhere it keeps full
627
+ evidence identity. This format allowlist does not prove that an allowed file
628
+ cannot affect application or test behavior; the project assertion and its
629
+ reduced guarantee still apply.
630
+
631
+ **Owner-declared Python bytecode exclusions (explicit trust mode).** By
632
+ default, Python bytecode remains part of candidate and input identity. To
633
+ exclude only exact generated cache files, run
634
+ `gateforge init --cache-exclude src/__pycache__/module.cpython-313.pyc`.
635
+ The command writes `.gateforge/cache-exclusions.yml` and prints the trusted
636
+ policy digest to approve outside the repository. A matching protected
637
+ `GATEFORGE_APPROVED_POLICY_DIGEST` pin is REQUIRED before a gate uses the
638
+ list; changing an existing list requires `--confirm-cache-exclusions`.
639
+ Only exact `.pyc` or `.pyo` files directly under `__pycache__` are allowed;
640
+ globs, symlinks, configured inputs, and other file types fail closed. Reports
641
+ show the exact files, pin status, and reduced trust guarantee. This is an
642
+ owner assertion, not proof that the excluded bytecode cannot affect runtime
643
+ behavior.
644
+
645
+ **Managed mode** (config `enforcement.mode: managed`) — the literal
646
+ no-bypass guarantee requires putting the authoritative Git metadata, commit
647
+ service, gate executable, policy authority, and signing material OUTSIDE the
648
+ agent's write/process boundary. `gateforge broker commit` ships the
649
+ MECHANISM — verify a receipt for the exact workspace bytes, then commit via
650
+ compare-and-swap ref update — not the deployment. Running the broker inside
651
+ the agent's own boundary provides NO managed guarantee.
652
+ `gateforge enforcement doctor` reports which boundary is actually active:
653
+ hook activation, runner/browser readiness, capability availability, trusted
654
+ binary/policy ownership, snapshot mode, and — in managed mode — an
655
+ agent-writable authoritative Git directory is a `fail`, never a pass.
656
+ When `.pre-commit-config.yaml` exists, the doctor runs its hooks twice in a
657
+ temporary checkout, reports files they modify, and recommends placing
658
+ `gateforge-check` before mutating hooks. Hook commands still run with the
659
+ caller’s system permissions; review them as you would any local command.
660
+
661
+ ### Owner-operated systemd deployment recipe
662
+
663
+ This is an operator deployment pattern, not an installed Gateforge service.
664
+ Use a dedicated authority account and keep the bare authoritative repository,
665
+ trusted config, CLI binary, and verifier key outside the agent's writable
666
+ process boundary. Give agents write access only to unique inbox workspaces;
667
+ allow them to request this one fixed unit, never arbitrary systemd units.
668
+ Do not pass candidate-controlled environment variables to the service.
669
+
670
+ Create an owner-only key ring and approved config as the authority account:
671
+
672
+ ```sh
673
+ sudo install -d -o gateforge-authority -g gateforge-authority -m 0700 /etc/gateforge
674
+ sudo -u gateforge-authority gateforge key create --file /etc/gateforge/verifier-keyring.json --confirm
675
+ ```
676
+
677
+ Install `/etc/systemd/system/gateforge-broker@.service` (replace the
678
+ root-owned CLI path and ref for your installation):
679
+
680
+ ```ini
681
+ [Unit]
682
+ Description=Verify and commit one Gateforge workspace
683
+
684
+ [Service]
685
+ Type=oneshot
686
+ User=gateforge-authority
687
+ Group=gateforge-authority
688
+ WorkingDirectory=/srv/gateforge/authority.git
689
+ Environment=GATEFORGE_WITNESS_VERIFIER_KEY_FILE=/etc/gateforge/verifier-keyring.json
690
+ Environment=GATEFORGE_TRUSTED_CONFIG=/etc/gateforge/approved.yml
691
+ ExecStart=/usr/local/bin/gateforge broker commit --workspace /srv/gateforge/inbox/%i --message "verified candidate" --ref refs/heads/main
692
+ ProtectSystem=strict
693
+ ProtectHome=true
694
+ PrivateTmp=true
695
+ NoNewPrivileges=true
696
+ ReadOnlyPaths=/srv/gateforge/inbox
697
+ ReadWritePaths=/srv/gateforge/authority.git
698
+ ```
699
+
700
+ Provision `/srv/gateforge/authority.git`, `/srv/gateforge/inbox/<opaque-id>`,
701
+ and `/etc/gateforge/approved.yml` with owner-controlled permissions. Restrict
702
+ service activation to the agent role via an exact polkit rule; do not grant
703
+ general `sudo systemctl` access. The broker verifies the workspace receipt,
704
+ current approved policy, raw tree bytes, and compare-and-swap target ref
705
+ before committing. A missing, stale, forged, or wrong-key receipt fails
706
+ closed. `enforcement doctor` can verify the local boundary only; the owner
707
+ must separately audit the service account, polkit rule, filesystem
708
+ permissions, and immutable engine/config deployment.
709
+
710
+ ## Contract capabilities
711
+
712
+ What the engine can grade today (single source of truth: the core capability
713
+ registry; `init --strict-e2e` preflight rejects setups that require anything
714
+ else):
715
+
716
+ | Namespace | Status |
717
+ | --- | --- |
718
+ | `persistence:create\|read\|update\|delete` | AVAILABLE — engine-observed same-entity persistence reads with the exact-value echo requirement (`EVIDENCE_VALUE_MISMATCH` on a mismatched echo, even when the status was 2xx) |
719
+ | `http:request-observed`, `http:response-status-ok` | AVAILABLE — transport semantics only: a witness-observed exchange plus a provenance-verified claimed `ui.action` anchor from the declaring test |
720
+ | `http:frontend-request-observed` | UNAVAILABLE — no independent browser/test attribution channel; explicit selection remains blocking `missing` with `VERIFIER_UNSUPPORTED` |
721
+ | `crud:*` (UI-semantic) | FAIL-CLOSED — the tested suite owns the browser; use `persistence:*` |
722
+ | `http:effect-verified`, `http:read-result-verified` | AVAILABLE (behavior-case channel) — graded across the approved required cases with witness-issued `behavior.case` records; needs a compiled `behaviorPolicy` requirement set |
723
+ | `auth:*`, `validation:*`, `task:*`, `webhook:*`, `workflow:*` | AVAILABLE (behavior-case channel) — same required-case aggregation over engine-controlled requests with independent state scopes. A repository that declares no case for the obligation stays blocking `missing`: the grader never falls back to transport evidence |
724
+
725
+
726
+ A behavior case may declare a `signatureProfile` on its `request`
727
+ action: an algorithm plus bounded `;key=value` parameters
728
+ (`header`, `timestampHeader`, `toleranceMs`, `attemptHeader`,
729
+ `attempt`, `forgery`). One parser serves both the config schema and
730
+ the witness driver, so `hmac-sha256;forgery=signature` is understood
731
+ identically at parse time and at run time and an unknown parameter is
732
+ refused rather than defaulted. The signing secret is read only from
733
+ the trusted lease; the signature always covers the exact bytes on the
734
+ wire.
735
+
736
+ Unsupported proof stays blocking. Nothing silently replaces browser proof
737
+ with HTTP status proof.
738
+ `gateforge init` includes the available transport-only contracts for consumed
739
+ HTTP endpoints in new installations. Existing policies are unchanged;
740
+ explicitly requiring `http:frontend-request-observed` still blocks. The init
741
+ scan names that unavailable channel once as not yet provable.
742
+
743
+ ### Observation scope for HTTP endpoints (opt-in policy option)
744
+
745
+ By default an `http.endpoint` owes the observation contracts
746
+ (`http:request-observed`, `http:response-status-ok`) only when a
747
+ `consumed: true` policy matches it — the static join with the frontend.
748
+ A brand-new route that no UI calls therefore owes nothing, and "you
749
+ forgot a test" stays invisible: `check` exits 0.
750
+
751
+ The pinned policies document (`.gateforge/policies.yml`, the trusted
752
+ policy) takes one additive option that widens that scope:
753
+
754
+ ```yaml
755
+ schemaVersion: 1
756
+ options:
757
+ 'http.endpoint.requireObservation': all # or 'consumed' (the default)
758
+ policies:
759
+ - id: frontend-consumed-endpoints-transport-only
760
+ when:
761
+ kind: http.endpoint
762
+ consumed: true
763
+ require:
764
+ - http:request-observed
765
+ - http:response-status-ok
766
+ ```
767
+
768
+ - Absent (or `consumed`): today's behavior, byte for byte. A document
769
+ without the `options` section generates the same obligations, the same
770
+ report and the same exit code it always did.
771
+ - `all`: EVERY discovered endpoint owes the observation contracts of a
772
+ `consumed: true` endpoint policy. An unmapped one is `missing` with the
773
+ existing `TEST_MAPPING_MISSING` cause and the existing overlay next
774
+ action. Existing routes are not re-litigated: run `gateforge adopt`
775
+ once (the sanctioned bulk-add) and the adopted baseline forgives them,
776
+ so only NEW routes block.
777
+ - The option never widens a `consumed: false` policy, a policy that does
778
+ not name the `http.endpoint` kind, or anything that is not a route; it
779
+ adds no contract, cause code or exit code.
780
+ - It lives in the pinned policy document, so an agent cannot widen or
781
+ narrow the scope by itself — that is a policy revision.
782
+ - `gateforge next` names the option on the one item it explains (an
783
+ unmapped obligation on a route the frontend never calls while the
784
+ option is `all`) and stays silent everywhere else.
785
+
786
+
787
+
788
+ ## Configuration
789
+
790
+ `.gateforge.yml` is loaded fail-closed from the working directory (the repo
791
+ root); see `@gate-forge/core` for the pinned schema. All paths are
792
+ repo-root-relative. `changed.provider: auto` (the default) picks
793
+ `github-pr` when `GITHUB_BASE_REF` is set, `gitlab-mr` when
794
+ `CI_MERGE_REQUEST_DIFF_BASE_SHA` is set, else `local-staged`
795
+ (`git diff --cached --name-only`). `clock.mode: fixed` freezes the run
796
+ instant for deterministic reports; `system` (default) freezes it at run
797
+ start.
798
+
799
+ Enforcement-relevant sections:
800
+
801
+ - `enforcement:` — `mode: standard | managed` (default `standard`),
802
+ `strictE2E: boolean` (default `false`), and optional
803
+ `receiptStage: pre-push | pre-commit | ci`. New configs choose `pre-push`;
804
+ omission preserves legacy behavior.
805
+ - `coveragePolicy:` (opt-in, fail closed) — the closed-world CRUD coverage
806
+ policy: enumerated user-facing tables (validated against the run's
807
+ resource inventory on EVERY run — an unknown table name is a config error,
808
+ a silently dropped inventory table is a violation), required operations,
809
+ and owner dispositions (`read-only-surface`, `admin-plane-unreachable`,
810
+ `not-user-facing`, `other`, with a note). With the policy enabled, an
811
+ uncovered, undispositioned required operation blocks with
812
+ `CRUD_COVERAGE_MISSING`. Recording or approving a disposition is a
813
+ trusted-policy act — the policy participates in the trusted policy
814
+ revision, so an agent edit never self-approves.
815
+ - `diagnostics.suites:` — the advisory pytest suites (see above).
816
+ - `runner:` — the test runner the supervised gate drives:
817
+ `playwright` (the default when the key is absent), `pytest`, `vitest` or
818
+ `cypress`. `check`, `next`, `tests`, `test-gates`, `doctor` and `init`
819
+ all follow it. See `guides/RUNNER-NEUTRAL-EVIDENCE.md`.
820
+
821
+ ## Plugin invocation
822
+
823
+ Every configured plugin runs over the same expanded include path list
824
+ (`project.paths.include` minus `exclude`; `.git` and `node_modules` are
825
+ never scanned):
826
+
827
+
828
+ - **subprocess** (GPP/3): `command` argv is spawned via
829
+ `@gate-forge/plugin-protocol`'s `PluginSession` — pinned handshake, one
830
+ lock-step `discover`, shutdown handshake, fail-closed on any protocol
831
+ violation. Plugins run without network.
832
+ - **in-process**: `module` is dynamically imported and its *default
833
+ export* must provide `discover(paths)` returning
834
+ `{resources, unresolved, findings}` in the pinned discovery shape.
835
+ Relative module specifiers resolve against the repo root; the result is
836
+ schema-validated and fails closed on invalid output.
837
+
838
+ The plugin's `discover` receives repo-relative file paths; in-process
839
+ plugins resolve them against the process working directory, which for a
840
+ CLI run is the repo root.
841
+
842
+ **Gitignored files are not scanned.** Untracked files Git ignores —
843
+ anything a `.gitignore` at any depth, or `.git/info/exclude`, excludes —
844
+ never enter the detector input list, so a dirty working copy (a built
845
+ `playwright-report/`, a cache tree, local output) produces exactly the
846
+ scan a clean clone of the same commit does. TRACKED files are always
847
+ scanned, even when an ignore pattern matches them: Git's own semantics.
848
+ The user's global excludes file is deliberately not consulted, so the
849
+ same repository scans identically on every machine; only repository
850
+ state decides. Outside a Git work tree (or without `git` on `PATH`)
851
+ nothing is skipped. The evidence digest still hashes configured scan
852
+ inputs even when Git ignores them, so an edit to an ignored file still
853
+ invalidates old evidence — the digest is a deliberate superset of the
854
+ scan, never a subset.
855
+
856
+ ## Endpoint plane rules (`.gateforge/planes.json`)
857
+
858
+ The same declarative plane document the packs apply to business tables
859
+ also carries endpoint-plane evidence. It is consumed by the endpoint
860
+ compiler (the pipeline stage that builds `http.endpoint` resources) with
861
+ the same strict reader, the same schema
862
+ (`{ rules: [{ match?, tables?, plane, reason }] }`), and the same
863
+ fail-closed posture.
864
+
865
+ **Endpoint plane rules are explicit human declarations keyed on the
866
+ router SOURCE FILE path — not automatic filename inference.** The config
867
+ IS the documented evidence (mirroring the classification policy's
868
+ declaration channels): a rule whose `match` glob (repo-root-relative,
869
+ posix, core classifier glob semantics) matches an endpoint's router file
870
+ asserts that endpoint's `plane` (`tenant` | `master` | `global`) with a
871
+ required non-empty `reason` as the review artifact. `tables` rules never
872
+ apply to endpoints — endpoints carry no table identity.
873
+
874
+ Evaluation per endpoint, deterministic and fail closed:
875
+
876
+ - **All matching rules agree** → the plane is applied as a plane-dimension
877
+ declaration signal (`gateforge.endpoint-compiler:config`), the same
878
+ evidence channel the classifier's inheritance pass uses, so the graph
879
+ qualifies the endpoint id as `plane.<name>`.
880
+ - **Matching rules disagree** → a blocking `PLANE_RULE_CONTRADICTION`
881
+ entry is emitted (the required `reason` of each matching rule rides the
882
+ diagnostic) and NO plane is applied — never first-match-wins.
883
+ - **No rule matches** → no evidence; the endpoint stays on the existing
884
+ channels (linked-resource inheritance, operational `global`, else
885
+ `PLANE_UNRESOLVED`).
886
+
887
+ Interaction with the other plane channels: the config plane participates
888
+ as EVIDENCE, never as a blanket override. When the plane the classifier
889
+ would derive for the endpoint (exactly one linked business resource, or
890
+ the operational `global` rule) is already derivable from the detector
891
+ contributions and CONTRADICTS the config plane, the compiler emits both
892
+ assertions so the classifier blocks with `PLANE_CONTRADICTION`; when they
893
+ agree, one plane remains and the endpoint resolves.
894
+
895
+ Absence of `.gateforge/planes.json` is normal and byte-identical to not
896
+ having this channel; a malformed document (bad JSON, unknown keys, a rule
897
+ without `plane`/`reason`, an absolute or `..`-escaping `match`) fails the
898
+ run closed at startup (exit 2).
899
+
900
+ ### Review an endpoint plane
901
+
902
+ When `next` cannot resolve a route's plane, it asks which data boundary owns
903
+ the route and prints one command for each supported choice. Run only the
904
+ choice the owner has reviewed. `classify plane` takes one repo-relative
905
+ file path, FOLDER, or glob, one plane, and a non-empty reason:
906
+
907
+ ```sh
908
+ # one router file (as before)
909
+ gateforge classify plane 'src/routes.js' tenant \
910
+ --reason 'Owner review confirms tenant-owned records for this route.'
911
+
912
+ # a whole router folder — written as the rule 'src/routes/**'
913
+ gateforge classify plane 'backend/api/v1' tenant \
914
+ --reason 'Every router in this folder serves tenant-owned records.'
915
+
916
+ # your own glob, matched verbatim
917
+ gateforge classify plane 'backend/api/v1/*_admin.py' master \
918
+ --reason 'These admin routers serve operator-managed records.'
919
+ ```
920
+
921
+ The default is a dry run: it prints the exact config diff and does not write.
922
+ Add `--confirm` to append the rule to an **existing**
923
+ `.gateforge/planes.json`. The command never creates another trust file,
924
+ replaces a rule, or writes an internality declaration; a source outside the
925
+ repository (absolute, drive-qualified, backslashed, or `..`-escaping) is
926
+ refused, and a new rule that would overlap an existing one with a different
927
+ plane is refused too — conflicting rules must be resolved by editing the
928
+ owner-reviewed config. This file is a classification input, so changing it
929
+ changes the trusted-policy digest; an approved policy pin must be
930
+ re-approved before strict gates run.
931
+
932
+ The alternative in `next` is owner-only: use the existing
933
+ `.gateforge/classification-policy.yml` `internalRules` declaration only when
934
+ the route is genuinely internal. Internal rules still require the existing
935
+ internality certificate; they are not overrides.
936
+
937
+ ## Endpoint capability rules (`.gateforge/endpoints.json`)
938
+
939
+ Capability derivation uses detector FACTS only (method, canonical path,
940
+ handler simple name, schema symbols, resource linkage). A handler whose
941
+ logic lives behind a service call has no positive evidence and fail-closes
942
+ with `ENDPOINT_SEMANTICS_UNRESOLVED` — the compiler cannot see through
943
+ service-layer delegation, by design, and will not guess. This document is
944
+ the escape hatch that the blocking message names: an explicit, human
945
+ assertion of what an endpoint DOES.
946
+
947
+ A rule carries at least one selector (AND semantics when several) plus a
948
+ capability from the closed compiler vocabulary and a required non-empty
949
+ `reason` (the review artifact):
950
+
951
+ - `match` — repo-root-relative glob on the ROUTER SOURCE FILE path;
952
+ - `handlers` — globs on the handler SIMPLE name (case-sensitive; a route
953
+ with no handler symbol never matches);
954
+ - `paths` — globs on the canonical path (`/analytics/**`; must start
955
+ with `/`);
956
+ - `method` — optional exact verb (`GET`…`DELETE`, never `ANY`).
957
+
958
+ ```json
959
+ {
960
+ "rules": [
961
+ {
962
+ "handlers": ["get_analytics_*"],
963
+ "capability": "crud-read",
964
+ "reason": "delegates to analytics_service; declared by the service owner"
965
+ },
966
+ {
967
+ "match": "backend/api/v1/accounts.py",
968
+ "method": "DELETE",
969
+ "capability": "crud-archive",
970
+ "reason": "sets archived_at via the service; soft delete by design"
971
+ }
972
+ ]
973
+ }
974
+ ```
975
+
976
+ Resource linkage accepts the path-derived name or its singular form with
977
+ one trailing `s` removed: `/items/{id}` can link to model `item`.
978
+ Exactly one discovered model must match, and a schema symbol or whole
979
+ handler-name word must corroborate it. Name coincidence alone never links;
980
+ if both `items` and `item` exist, the compiler blocks the ambiguity rather
981
+ than preferring one.
982
+
983
+ Evaluation per endpoint identity, deterministic and fail closed:
984
+
985
+ - **All matching rules agree** → the capability is declared (composed
986
+ with detected ones; overlapping agreeing rules are one declaration).
987
+ A declared `crud-delete`/`crud-archive` on a DELETE endpoint resolves
988
+ the archive-vs-hard question the linked model could not prove.
989
+ The declaration also supplies that evidence to the linked model's
990
+ classifier. Conflicting model/route semantics still block; an archive
991
+ declaration still needs the model's archive-state evidence.
992
+ - **Matching rules disagree** → a blocking
993
+ `ENDPOINT_CAPABILITY_CONTRADICTION` entry names every matching rule,
994
+ its capability, and its reason; NOTHING is applied — never
995
+ first-rule-wins.
996
+ - **No rule matches** → the endpoint stays on detector-fact evidence
997
+ only (and blocks if that is nothing).
998
+
999
+ The vocabulary is the compiler's own: `health-operations`,
1000
+ `auth-session`, `webhook-callback`, `workflow-command`, `task-async`,
1001
+ `search-query`, `validation-preview`, `file-transfer`, `ai-automation`,
1002
+ `realtime`, `crud-create`, `crud-read`, `crud-update`, `crud-delete`,
1003
+ `crud-archive`. Absence of the file is normal and byte-identical to not
1004
+ having the channel; a malformed document fails the run closed at startup
1005
+ (exit 2).
1006
+
1007
+ ### Answering `ENDPOINT_SEMANTICS_UNRESOLVED`
1008
+
1009
+ When `gateforge next` prints that code, the run has found an endpoint and
1010
+ cannot tell what it DOES; the remedy is an owner-authored rule, not
1011
+ another read-only command. The printed block carries the whole answer for
1012
+ THAT endpoint: its own method and canonical path as the selectors, the two
1013
+ owner-chosen fields (`capability`, `reason`) marked in the snippet, and the
1014
+ allowed values. Answer it by replacing the two marked fields and writing
1015
+ the file (append the rule to `rules` when the file already exists), then
1016
+ prove it applied with the printed `gateforge explain <endpoint-id>` — its
1017
+ `capabilities:` line names the capability and its trace says
1018
+ `endpoints.json`.
1019
+
1020
+ The shortest useful file — one exact endpoint, no glob at all — is:
1021
+
1022
+ ```json
1023
+ {
1024
+ "rules": [
1025
+ {
1026
+ "method": "DELETE",
1027
+ "paths": ["/items/{item_id}"],
1028
+ "capability": "crud-archive",
1029
+ "reason": "The handler sets archived_at; the row is never removed."
1030
+ }
1031
+ ]
1032
+ }
1033
+ ```
1034
+
1035
+ `paths` patterns are globs on the canonical path (`*` within a segment,
1036
+ `**` across segments, `?` one character); a path with no wildcard is an
1037
+ exact selector, which is what you want for one route. On a `DELETE`, the
1038
+ capability is the archive-vs-hard answer (`crud-archive` /
1039
+ `crud-delete`) and nothing else resolves that block; on any other verb it
1040
+ is the closed vocabulary above. A rule left with a placeholder capability
1041
+ fails the run closed at startup (exit 2) with the allowed values named.
1042
+
1043
+ ### Answering `ENDPOINT_RESOURCE_CANDIDATE_UNMATCHED`
1044
+
1045
+ This code says one thing: the route reads a single entity, and the name
1046
+ its path carries is not a name Gateforge found among your resources.
1047
+ `GET /api/v1/reports/logs/{}` served by a table called `report_logs` used
1048
+ to produce nothing at all, which read like a route that does not
1049
+ exist. The entry names the route, the name it derived, and up to three
1050
+ discovered resources whose last `_`-segment could be the same thing.
1051
+
1052
+ Those names are CANDIDATES, never links. Gateforge links an endpoint to a
1053
+ resource only on an exact name plus a corroborating fact (a response or
1054
+ request schema named after it, or a handler named after it), and it does
1055
+ not do that here. If one of the candidates is right, give the route the
1056
+ evidence: name the response model or the handler after the resource, or
1057
+ declare the missing mapping. If none is right, the route genuinely serves
1058
+ something the resource graph does not model. A route that links, a route
1059
+ with nothing near it, and any collection route are unaffected.
1060
+
1061
+ Whether the entry BLOCKS is the owner's call, in `.gateforge.yml`:
1062
+
1063
+ ```yaml
1064
+ endpoints:
1065
+ unmatchedRoutes: warn # the default; `block` gates commits on them
1066
+ ```
1067
+
1068
+ Absent the key means `warn`: the entries are reported under this same code
1069
+ in the advisory channel, `check --changed` does not block on them, and
1070
+ `check` and `next` print a banner at the top with the count, the first
1071
+ three examples and the key above — a repository that upgraded must not
1072
+ start failing commits over a finding it never chose. `warn` says the same
1073
+ thing with the "you have not chosen" sentence gone; `block` makes the entry
1074
+ a blocking entry like any other. `gateforge init` asks once in a terminal
1075
+ and takes `--unmatched-routes block|warn`.
1076
+
1077
+ ## Proposing planes at init (`gateforge init --planes`)
1078
+
1079
+ `gateforge init --planes` runs discovery over the repo's own include and
1080
+ exclude configuration and PROPOSES `.gateforge/planes.json` from the
1081
+ directories the discovered tables live in: one non-overlapping `match`
1082
+ glob per model tree, `master` for trees whose path names a control-plane
1083
+ segment (`admin`, `master`, `control`, `root`, `operator`), `tenant`
1084
+ otherwise, and a reason on every rule naming the directory it was
1085
+ inferred from. The keyword mapping IS a heuristic — that is why the file
1086
+ is a review artifact: it is written only after explicit consent (flag,
1087
+ or the TTY prompt), only when absent, and must be reviewed before the
1088
+ next run reads it.
1089
+ Tables under test directories are excluded from the proposal (fixtures are
1090
+ not business surface) and never enter the resource graph at all, so a
1091
+ fixture that re-declares a real table's name cannot collide with it. The
1092
+ same rule (a `test/` or `tests/` directory segment) is generic — it names
1093
+ no repository. Non-interactive runs without `--planes` propose nothing and
1094
+ print the tip.
1095
+
1096
+ ### Route folders get their own question
1097
+
1098
+ Model folders alone leave every discovered endpoint `PLANE_UNRESOLVED`, so
1099
+ `--planes` also asks ONE question per ROUTE folder — the directory of the
1100
+ file that declares the handlers, e.g. `backend/api/v1` — and writes one
1101
+ `match: 'backend/api/v1/**'` rule per answer. A route's plane is never
1102
+ inferred from the model it links to (an `accounts` route can serve master
1103
+ data): the question may SHOW that model's plane as a hint, and only when
1104
+ every model behind the folder's routes has the same resolved plane —
1105
+ otherwise no hint is shown and the owner answers from the routes.
1106
+
1107
+ Nothing is applied without an answer. In a non-interactive run init prints
1108
+ each folder, its unresolved route count, the hint (labelled as a hint) and
1109
+ the exact command to run later:
1110
+
1111
+ ```sh
1112
+ gateforge classify plane 'backend/api/v1' tenant \
1113
+ --reason 'These routers serve tenant-owned records.'
1114
+ ```
1115
+
1116
+ ## test-gates protocol (G6 surface)
1117
+
1118
+ `gateforge test-gates` writes a run state directory (default
1119
+ `.gateforge/test-gates/`, `--out` overrides):
1120
+
1121
+ | File | Content |
1122
+ | --- | --- |
1123
+ | `manifest.json` | Pin #4 RunManifest (runId, injected-clock startedAt, gitSha, provider, plugin registrations, plus the `test-gates`-minted `invocationId` and tested `inputDigest`). At shutdown the witness appends `recordIds` + the v2 `attestation` envelope (never a legacy `recordIdsMac`). |
1124
+ | `obligations.json` | Every obligation the suite must cover, with pin #2 fingerprint and resource source/location. |
1125
+ | `env.json` | `GATEFORGE_RUN_ID`, `GATEFORGE_RUN_TOKEN`, `GATEFORGE_STATE_DIR`, `GATEFORGE_OBLIGATIONS`, `GATEFORGE_WITNESS_URL`. |
1126
+ | `claims.json` / `records.json` | Reporter output consumed by the verifier (written by the suite). |
1127
+ | `execution-result.json` / `receipt.json` / `diagnostics.json` | Supervised `--changed` mode: the sealed execution result (planned vs executed instances, outcomes, native claim inventory, runner exit, completeness), the authenticated gate receipt issued after complete success, and the separate advisory diagnostic report. |
1128
+ | `report.json` | Canonical json-format run report after evaluation. |
1129
+ | `last-full-run.json` | Advisory test count and measured duration for the latest completed full run; used only to explain commit cost, never as gate evidence. |
1130
+
1131
+
1132
+ The legacy suite command (`--suite`) runs with those env vars; its reporter
1133
+ extracts claims from `{type: 'gateforge', description: '<obligation id>'}`
1134
+ annotations and posts evidence through the witness service (pin #7, header
1135
+ `x-gateforge-run: <token>`; `GATEFORGE_WITNESS_URL` is set when a witness
1136
+ service URL is provided via `--witness-url`). `gateforge check` reads
1137
+ run-state evidence but takes native bindings only from `claimInventory`
1138
+ in an execution result authenticated by a receipt for the current inputs;
1139
+ it combines those with the current tracked `test-map.yml`. Raw
1140
+ `claims.json` cannot add current declarations. Receipts created before
1141
+ `claimInventory` existed remain valid, but supply no native bindings.
1142
+ Records whose provenance does not verify never satisfy (GF-23). The
1143
+ legacy escape hatch can never redefine the strict gate's expected cases
1144
+ or turn an arbitrary exit-zero command into E2E proof — the hook and CI
1145
+ run `check --staged/--changed --require-e2e`, which accept only supervised
1146
+ receipts.
1147
+
1148
+ Before supervised execution, Gateforge compares Playwright's scrubbed
1149
+ inventory with a second `--list` using the safe run variables supplied to
1150
+ the runner. A difference stops the run before tests start and names each
1151
+ project, file, and title present in only one inventory. Static discovery
1152
+ also warns when `process.env.GATEFORGE_*` controls test registration.
1153
+
1154
+ ### Provenance trust model (GF-23, audited 2026-08-31, three rounds)
1155
+
1156
+ `records.json` and `manifest.json` live in the suite-writable state
1157
+ directory, so NEITHER proves anything on its own: a hostile suite can
1158
+ fabricate records (the id hash `recordIdOf` is public) and can write any id
1159
+ list into the manifest. Two layers close this.
1160
+
1161
+ **Layer 1 — trust follows origin.** A record's `origin` is part of its
1162
+ hashed identity:
1163
+
1164
+ - `suite-submitted` (`ui.action`, `ui.visible-result` POSTed by the
1165
+ suite): the witness RECEIVED the assertion but cannot verify it
1166
+ happened — the suite owns the browser and holds the run token. These
1167
+ records are stamped `trust: 'claimed'` at issuance and only ANCHOR a
1168
+ claim (entity + operation).
1169
+ - `engine-observed` (`persistence.entity`, stamped by the witness from
1170
+ its own adapter read): the only `trust: 'witnessed'` origin. This is
1171
+ where `satisfied` is earned — the engine requires a witnessed
1172
+ persistence record for the claimed entity, so fabricated outcomes can
1173
+ never satisfy.
1174
+
1175
+ **Supervised session binding (Phase 1).** The trusted reporter opens ONE
1176
+ witness session per started test (`runId`, `sessionId`, `testId`,
1177
+ `worker`), and the evidence fixture's five primitives (`ui`, `visible`,
1178
+ `persistence`, `http`, `finalize`) submit only under that OPEN session:
1179
+ the witness rejects submissions without a session and forces each record's
1180
+ testId onto the session's supervisor-registered value; sealing rejects all
1181
+ late submissions. Every UI action runs inside a witness-recorded
1182
+ observation interval (supervisor-issued session clock), so proxy exchanges
1183
+ observed outside the action's interval — direct setup calls, stray
1184
+ navigation — are never credited as browser evidence. For a mutation whose
1185
+ journey collects input in the UI, the `ui.action` record's `fields` are
1186
+ the declared input, and the independent engine-observed persistence read
1187
+ must echo those values EXACTLY on the same entity identity: a mismatched
1188
+ echo fails the obligation with `EVIDENCE_VALUE_MISMATCH` even when the
1189
+ status was 2xx. Primitive receipts are frozen and branded — hand-rolled
1190
+ forgeries fail closed (GF-22).
1191
+
1192
+ **UI-semantic `crud:*` contracts fail closed (audit round 5).** The suite
1193
+ still owns the browser, so a claimed UI action cannot be verified at the
1194
+ DOM level; the namespace advertises no gradable contract. The gradable
1195
+ surface is the lifecycle-gated `persistence:*` namespace, graded on the
1196
+ witness's OWN engine-side observation
1197
+ (`{resourceId, entityId, found, fields, before}`) with expectations that
1198
+ NEVER come from the tested suite:
1199
+
1200
+ - `persistence:create`: an engine-side id-set PRE-OBSERVATION (`POST
1201
+ /witness/pre-observation`, backed by the adapter's optional `list`)
1202
+ shows the entity absent before the action; the post-read shows it
1203
+ present.
1204
+ - `persistence:update`: an engine-side entity pre-observation exists,
1205
+ the engine observed an actual before/after field delta, AND the delta
1206
+ touches at least one classification-declared `updateableFields` entry
1207
+ (audit round 6) — bookkeeping drift such as `updated_at` alone never
1208
+ satisfies, and a resource whose classification omits
1209
+ `updateableFields` fails closed for update obligations.
1210
+ - `persistence:read`: the entity is present in the engine-observed state.
1211
+ - `persistence:delete`: a hard delete observes the entity ABSENT; an
1212
+ archive observes it present and matching the classification's
1213
+ owner-declared `archiveFields` (e.g. `{status: archived}`) — the suite
1214
+ cannot bless an unarchived entity by declaring its current state as
1215
+ the expected result.
1216
+
1217
+ An adapter may declare an optional literal `fields: [...]` projection.
1218
+ Anchored persistence fails before consuming its pre-observation when the
1219
+ action changes a field outside that projection. `check` also reports
1220
+ model updateable fields missing from a statically readable projection.
1221
+ Adapters without this metadata keep their existing behavior.
1222
+
1223
+ Presence alone, contradicted observations, missing pre-observations, or
1224
+ absent deltas grade `invalid` — even when every provenance check passes.
1225
+
1226
+
1227
+ When the complete endpoint inventory contains no update-capable route linked
1228
+ to the resource, the failure also says that no observed UI request writes the
1229
+ fields and the feature may be unreachable from the UI. This is diagnostic only;
1230
+ it does not change the verdict.
1231
+
1232
+ **Layer 2 — versioned attestation binding evidence to tested inputs.** A witnessed record is authorized only by ONE validated
1233
+ v2 envelope that simultaneously matches its run id, the expected input
1234
+ digest, the required invocation identity, and its record id:
1235
+
1236
+ - the durable manifest `attestation` (`attestationVersion: 2` with
1237
+ `runId`, `invocationId`, `inputDigest`, sorted unique `recordIds`, and
1238
+ `mac` — HMAC-SHA256 over the domain-tagged body
1239
+ `gateforge.ledger.v2`), written by the witness at shutdown from its
1240
+ FROZEN bound context plus EXACTLY its own ledger (pre-seeded forged
1241
+ ids are discarded, never signed), or
1242
+ - the live `GET /ledger-attestation` response: the SAME signed object,
1243
+ fetched (and MAC-verified) by `test-gates` from a still-running wired
1244
+ witness and persisted into the manifest as the durable fallback
1245
+ before the witness stops (401 to the run token alone).
1246
+
1247
+ The `inputDigest` is a deterministic snapshot of everything the
1248
+ pipeline examines (all Git-tracked files, nonignored untracked files,
1249
+ configured scan inputs even when ignored, `.gateforge.yml`,
1250
+ policies/classification/pack configs, adapters, local plugin modules,
1251
+ manifests/lockfiles, effective obligations/classifications/routes —
1252
+ `packages/cli/src/input-snapshot.ts`). A deleted file, an untracked
1253
+ file, a policy edit, or a lockfile change all move the digest, so old
1254
+ evidence blocks after any source/configuration change. The
1255
+ `invocationId` is fresh per `test-gates` run, so a restored old bundle
1256
+ cannot satisfy a new invocation. `check` (no suite) reuses a completed
1257
+ signed run only for byte-identical inputs — it never equates its own
1258
+ fresh manifest UUID with the evidence run UUID.
1259
+
1260
+ The witness never signs what a suite-writable file says: `test-gates`
1261
+ binds the context with authenticated `POST /run-context` (run token
1262
+ AND verifier key) BEFORE the suite starts, and the witness freezes it
1263
+ in memory. Binding is allowed only before any observation or issuance;
1264
+ a used witness answers 409, an identical rebind is idempotent, any
1265
+ change is 409, and an unbound witness issues no attestation. A proxy
1266
+ exchange in flight at bind time refuses the bind, and observations
1267
+ that completed before binding are never consumable under the new
1268
+ context.
1269
+
1270
+ The legacy v1 `recordIdsMac` (HMAC over `{runId, recordIds}` with no
1271
+ digest binding) NEVER authorizes evidence — even when it verifies.
1272
+ Invalid durable envelopes contribute nothing; live and durable
1273
+ contexts are validated independently and never merged; mismatches
1274
+ surface as explicit `evidence-context` blockers (missing vs malformed
1275
+ vs forged stay distinguished) that waivers cannot hide.
1276
+
1277
+ The key comes from one trusted source: the protected
1278
+ `GATEFORGE_WITNESS_VERIFIER_KEY` environment variable, an external
1279
+ owner-only key ring named by `GATEFORGE_WITNESS_VERIFIER_KEY_FILE`, or the
1280
+ default `$XDG_CONFIG_HOME/gateforge/verifier-keyring.json` (otherwise
1281
+ `~/.config/gateforge/verifier-keyring.json`) when present. Do not set both
1282
+ explicit sources. The file must be a regular file owned by the current
1283
+ user, with mode `0600` or stricter, and it must not be a symlink. Store
1284
+ it outside the candidate repository, Git directory, run state, `--out`
1285
+ directory, workspace, and receipt-artifact directory. Gateforge refuses
1286
+ unsafe paths and permissions. File mode is not supported on Windows;
1287
+ use the protected environment source there.
1288
+ Create and rotate keys only after an owner review:
1289
+
1290
+ If you already use an environment key, keep it in the protected environment
1291
+ while you import it. Do not place key material in shell history or argv.
1292
+
1293
+ ```sh
1294
+ gateforge key create --confirm
1295
+ gateforge key import-env --confirm
1296
+ unset GATEFORGE_WITNESS_VERIFIER_KEY
1297
+ gateforge key rotate --confirm
1298
+ gateforge key retire --key-id key-old-id --confirm
1299
+ ```
1300
+
1301
+ Create the parent directory first. `key import-env` retains an existing
1302
+ environment key under its stable id before switching to the file source.
1303
+ Key commands print only a non-secret
1304
+ key id. Rotation keeps old keys so their receipts still verify. Retire an
1305
+ old key only when its receipts no longer need to verify. Gateforge stores
1306
+ the key id, not the secret, in new receipts. A receipt for a removed id
1307
+ fails with `KEY_UNKNOWN`. The key ring file contains raw signing keys, so
1308
+ protect its backups with the same care as the original.
1309
+
1310
+ `test-gates` strips both key-source variables from the suite child's
1311
+ environment. The supervised browser runner and candidate runtime also
1312
+ refuse both sources, and Gateforge does not write either value or file
1313
+ path into run state. The trusted witness process receives the active key
1314
+ to authenticate records. A suite-owned Playwright global setup therefore
1315
+ cannot bootstrap trusted issuance by inheriting the key — it fails closed
1316
+ unless an externally wired trusted witness is provided. Residuals (not
1317
+ eliminable by env hygiene alone): a same-uid process can read environ when yama
1318
+ `ptrace_scope=0`, and env vars never isolate hostile same-user OS
1319
+ processes — for strong isolation run the suite as a distinct user or
1320
+ container. File-change capture is snapshot-based, not an OS sandbox:
1321
+ it guards changes visible at capture points, not a malicious process
1322
+ that changes and restores files between snapshots.
1323
+
1324
+ ### The operator's fixture/actor provider
1325
+
1326
+ A declared behavior case names a `fixture` recipe and an `actor`, and the
1327
+ witness — not the test suite — must materialize them before it drives the
1328
+ case. `GATEFORGE_FIXTURE_PROVIDER` names the module that does that. The
1329
+ CLI-spawned witness loads it at startup; a repository that declares no
1330
+ behavior cases is unaffected.
1331
+
1332
+ The module's default export is `{ prepare(input), release(leaseId),
1333
+ resolveCredential(credentialRef) }`:
1334
+
1335
+ - `prepare` provisions the case's subjects and actor identities and returns
1336
+ `{ leaseId, namespace, subjects, actors }`. Subjects are server-issued
1337
+ identities; a lease namespace keeps concurrent cases isolated.
1338
+ - `release` drops what that lease provisioned.
1339
+ - `resolveCredential` turns a lease `credentialRef` into request material.
1340
+ It runs in the witness process, so a secret stays there; a declared
1341
+ `credentialVariant: valid` that cannot resolve fails closed rather than
1342
+ degrading.
1343
+
1344
+ The provider is ENGINE-SIDE code and is the only caller of its own
1345
+ provisioning HTTP calls — the suite never imports it, and nothing it
1346
+ returns can mint evidence, only supply the subjects a case drives. Because
1347
+ of that, a repository should exclude the provider from its product scan
1348
+ scope (`.gateforge.yml` `project.paths.exclude`, matching
1349
+ `classification-policy.yml` `scanRoots`): its calls are fixture
1350
+ provisioning, not application call sites, and scanning them reports the
1351
+ engine's own traffic as unresolved frontend targets. See
1352
+ `example/behavior/fixtures/fixture-provider.mjs` for a working provider.
1353
+
1354
+ Fail closed: without the key, or when no envelope validates for the
1355
+ expected context, every witnessed record demotes to claimed-tier
1356
+ (blocking, never satisfied).
1357
+
1358
+ ### Evidence migration (v1 → v2, no auto-migration)
1359
+
1360
+ - Existing evidence bundles need a FRESH run: there is no command
1361
+ that signs old records into the new format without observations, and
1362
+ none will be added (signing old records would certify untested code).
1363
+ - Gate receipts (ADR 0005 D3) are a separate versioned, domain-separated
1364
+ envelope — never a repurposed v2 attestation, and never a mutable
1365
+ `passed` flag on a claim. `check --require-e2e` rejects old record
1366
+ bundles that lack the required complete-run receipt.
1367
+ - Policies and waivers keep their explicit semantics: snapshot binding
1368
+ never rewrites their IDs to evade blockers — and in strict E2E mode an
1369
+ in-scope waived/baselined E2E obligation is not proof at all
1370
+ (`ENFORCEMENT_UNTRUSTED`).
1371
+ - External witness setup: start `gateforge-witness` (or `startWitness`)
1372
+ with the run id/token from a TRUSTED parent env carrying
1373
+ `GATEFORGE_WITNESS_VERIFIER_KEY`, pass `--witness-url`/`--run-token`
1374
+ to `test-gates`, and start a FRESH witness per invocation (a witness
1375
+ used by an older invocation rejects binding with 409).
1376
+ - Non-Git checkouts keep discovery but fail evidence authorization
1377
+ with a `snapshot-unavailable` diagnostic; submodules, escaping
1378
+ symlinks, and `--out` overlapping source fail closed with explicit
1379
+ diagnostics.
1380
+
1381
+ ## Limitations
1382
+
1383
+ - Staged candidates containing symlinks or submodules (and unmerged index
1384
+ entries) are typed blocks in `check --staged` and `broker commit` —
1385
+ explicit, never fallbacks; support is not implemented.
1386
+ - A Playwright config with NO named project yields native rows with an
1387
+ empty project name, which the strict catalog schema rejects as an
1388
+ internal error (exit 2) instead of a typed row. The documented consumer
1389
+ shape uses named projects; a typed empty-project row is open work.
1390
+ - Run-state hygiene is enforced, not forgiven: a committed run-state
1391
+ directory (it overlaps source inputs) or config include globs that omit
1392
+ the spec directories produce fail-closed diagnostics — gitignore
1393
+ `.gateforge/test-gates/` and include the spec globs.
1394
+ - Consumer-worktree migration (writing `.gateforge` configuration,
1395
+ `coveragePolicy`, or `test-map.yml` into the inventoried ERP consumer
1396
+ worktree) and the server-side GitLab enforcement settings are pending
1397
+ owner actions — the complete template and settings list ship from
1398
+ `init --blocking`, but a local simulation does not complete a server
1399
+ rollout (`docs/plans/immediate/20260913_consumer_migration_record.md`).
1400
+
1401
+ ## Pick a goal, not a wall of flags
1402
+
1403
+ `gateforge init` asks ONE question — what should Gateforge do for you — and
1404
+ maps the answer to settings:
1405
+
1406
+ | Goal | Meaning | Writes |
1407
+ | --- | --- | --- |
1408
+ | `light` | show me code nothing has proven yet, block nothing | `mode: warn` |
1409
+ | `normal` | block a commit that adds untested endpoints or models (about a second) | `mode: changed`, pre-commit hook, CI job |
1410
+ | `strict` | every push needs a real test run Gateforge watches (the witness) plus a receipt, the signed record of that run | `mode: strict`, staged gate, pre-push receipt check, CI job |
1411
+
1412
+ ```sh
1413
+ gateforge init --explain-presets # print this table
1414
+ gateforge init --preset normal # or: light, or strict
1415
+ ```
1416
+
1417
+ In a terminal, `gateforge init` asks the goal question instead. With no
1418
+ terminal and no `--preset` (an AI agent or CI), it writes `light` only and
1419
+ prints that a human must choose: Gateforge never guesses `normal` or `strict`
1420
+ for someone who is not there. Existing flags (`--blocking`, `--strict-e2e`,
1421
+ `--pre-commit`, `--witnessed`, `--mode`) keep working exactly as before and
1422
+ win over a preset. Re-running `init` never rewrites an existing
1423
+ `.gateforge.yml`; to change the goal later, edit the `mode:` key.
1424
+
1425
+ The core flow:
1426
+
1427
+ ```text
1428
+ Source change
1429
+ -> Detector recognizes a resource
1430
+ -> Classifier establishes resource properties
1431
+ -> Policy produces test obligations
1432
+ -> Existing tests are inventoried, suggested, and declared against
1433
+ obligations (`gateforge tests discover|suggest|mark`); a new test is
1434
+ the last step for a confirmed behavior gap, never the default
1435
+ -> `gateforge test-gates --changed` supervises a complete run of the
1436
+ selected existing suite and seals an authenticated gate receipt
1437
+ -> `gateforge check --require-e2e` accepts only a valid, non-stale
1438
+ receipt for the exact candidate bytes
1439
+ -> The pre-commit hook, the commit broker, and the CI gate block
1440
+ everything else
1441
+ ```
1442
+
1443
+ CRUD coverage is the first proof case, not the final architecture. The broader
1444
+ product is a user-extensible test-policy compiler: creating or modifying code
1445
+ artifacts automatically creates auditable testing responsibilities.
1446
+
1447
+ ## Agent loop
1448
+
1449
+ Blocked agents run `gateforge next` (or `gateforge next --json`): exactly
1450
+ one blocking next action (`next`/`cause`/`why`/`do`), never a dump. Do the
1451
+ single `do:` line and stop. New proof tests go in `tests/e2e/gateforge/`
1452
+ (overlay, engine-driven fixture — wizard creates via surface v2 steps);
1453
+ existing suite-driven browser tests prove persistence via the Observe
1454
+ channel once mapped `--kind observed-e2e`. Never rewrite existing
1455
+ `tests/e2e/**` journeys, never `tests mark` as proof, never edit policies
1456
+ or waivers to self-approve. `GATEFORGE.md` (written by `gateforge init`)
1457
+ carries the full loop contract.
1458
+
1459
+ ## Fix a failing test without a full run
1460
+
1461
+ Fixing one failing test changes the candidate, so the run that found it no
1462
+ longer describes it. When only test code changed, you can re-run just the
1463
+ affected tests and carry the rest, with `enforcement.reseal: true` in
1464
+ `.gateforge.yml` (off by default in every mode, on in any mode including
1465
+ `strict` when you set it):
1466
+
1467
+ ```sh
1468
+ gateforge test-gates --changed --scope changed
1469
+ # only test files changed: re-ran 1 test(s), kept 562 from the previous receipt
1470
+ ```
1471
+
1472
+ Gateforge diffs the two sealed trees itself, classifies every changed path
1473
+ from the runner's catalog and the import graph (test files and test
1474
+ helpers only; importers of a changed file re-run too, and a dynamic
1475
+ import with a literal specifier is an ordinary edge), and otherwise falls
1476
+ back to the plain changed-scope run with one reason line — app code, a
1477
+ deleted file, a setup-stage test, a computed or unresolvable import.
1478
+ A whole-suite run that
1479
+ failed a test seals no receipt, so it leaves a MAC'd run record instead
1480
+ and the same command re-seals from it. A re-seal is itself a whole-suite
1481
+ proof, so **consecutive re-seals chain**: fix one test, commit, run; fix
1482
+ the next, commit, run. Each re-seal's parent is the previous re-seal, the
1483
+ chain retains every hop's outcomes and each contributing run's witnessed
1484
+ evidence, and a test no hop re-ran keeps its original proof. The parent is
1485
+ the previous run **in `.gateforge/test-gates/`** — no CI variable is
1486
+ involved (`CI_MERGE_REQUEST_DIFF_BASE_SHA` names a merge base, never the
1487
+ commit the previous pipeline tested, and is ignored), so a CI run must
1488
+ **persist the state directory between pipelines**, cached by branch; with
1489
+ a cold cache there is no parent and the run is the ordinary run. The chain
1490
+ is bounded at five consecutive re-seals — the sixth prints
1491
+ `test-gates: the run state already retains 5 consecutive re-seals, the bound this path may chain to → changed-scope run`
1492
+ — and `check --require-e2e` and `broker commit` recompute the whole chain
1493
+ with their own key before accepting it. See
1494
+ [`Fix one test without a full run`](TEST-ENVIRONMENT.md#fix-one-test-without-a-full-run)
1495
+ for the rules, the exact reason lines, and the residual risk.
1496
+
1497
+ If your run writes into the workspace — a witnessed login stage saving
1498
+ its storage state, a runner cache — those gitignored bytes are part of
1499
+ every sealed tree, so the re-seal refuses on them every time. Declare
1500
+ them with `enforcement.resealRuntimeFiles` (repo-relative globs, off by
1501
+ default):
1502
+
1503
+ ```yaml
1504
+ enforcement:
1505
+ reseal: true
1506
+ resealRuntimeFiles:
1507
+ - 'e2e/.auth/*.json'
1508
+ ```
1509
+
1510
+ A matching path is disregarded only while **neither sealed commit tracks
1511
+ it**; a committed one is source, and a declaration can never hide a
1512
+ source change. The run prints
1513
+ `test-gates: re-seal disregards 2 declared runtime file(s): …`, the
1514
+ receipt records the list in `resealDisregarded`, and CI recomputes that
1515
+ exact list or rejects the receipt.
1516
+
1517
+ ## What the gate catches that ordinary tests can miss
1518
+
1519
+ Mocks and passing clicks can miss bugs in the real path:
1520
+
1521
+ - A UI request succeeded, but the server response dropped a persisted source fingerprint. The mocked test checked the request only.
1522
+ - An update control changed only a synchronization timestamp, not the user-editable setting the test claimed to update.
1523
+ - Two journeys reused a shared tenant fixture, hiding a missing tenant boundary that appeared when the real application handled separate records.
1524
+
1525
+ Gateforge connects existing journeys to obligations, then checks witness evidence from the configured run. It complements the test suite; it does not replace it.
1526
+
1527
+ ## Running in CI
1528
+
1529
+ A long witnessed run used to be a blank CI screen. The runner log does
1530
+ carry the app env, the request bodies and the seed credentials, so the
1531
+ job redirects it to a private file — and then nothing distinguishes a
1532
+ healthy 45-minute run from a hung one.
1533
+
1534
+ `gateforge test-gates` now prints a progress stream of its own:
1535
+
1536
+ ```
1537
+ gateforge: run started — 563 tests expected (runner playwright, scope full)
1538
+ gateforge: ✓ 214/563 Accounts > creates an account
1539
+ gateforge: ✘ 215/563 Accounts > archives the account — Expected: 200
1540
+ gateforge: alive — 214/563 done, 3 running, 12m04s elapsed
1541
+ gateforge: run finished — 561 passed, 1 failed, 1 skipped in 44m05s; grading…
1542
+ ```
1543
+
1544
+ It is on automatically under `CI=true` and off everywhere else, so a
1545
+ local run's output is unchanged. `--progress stderr|file:<path>|off`, and
1546
+ the `run.progress` config key, say so explicitly; an unusable target is a
1547
+ usage error, never a silently dropped stream.
1548
+
1549
+ **Why it is safe to show.** The stream is built from witness-side facts
1550
+ only — how many tests were registered before the run, which test the
1551
+ supervisor has open, its title as declared in the committed catalog, and
1552
+ its outcome. It never reads, filters, or tails runner output, so no
1553
+ secret can reach it by construction: a filter over secret text is not
1554
+ secret-free. The one runtime value it carries is a failing test's first
1555
+ error line, and that is matched against credential shapes and REPLACED
1556
+ whole (a prefix of a secret is a secret) — the line becomes
1557
+ `(message withheld: looks like a secret)`, and a title that itself looks
1558
+ like a secret is replaced by its own digest. The stream decides nothing:
1559
+ it is not evidence, no gate reads it, and a write failure is reported
1560
+ once and then ignored.
1561
+
1562
+ **Failing tests in CI.** A red witnessed test used to ship nothing but a
1563
+ browser snapshot. Its error message and a short `file:line` stack now
1564
+ land in `.gateforge/test-gates/failures.json`, behind the same guard, so
1565
+ a job never has to publish the runner log to explain a failure. Request
1566
+ and response bodies are never included.
1567
+
1568
+ **Two numbers, one meaning.** Reports used to print
1569
+ `repository debt: 192 blocking` next to a gate line that said zero
1570
+ blockers: both were true and neither was actionable. `repositoryDebt`
1571
+ now derives its split from ONE definition, the graded verdicts, so
1572
+ `baselined` and `newlyBlocking` are the same two numbers in the text and
1573
+ in the JSON, and `newlyBlocking` is exactly what this run's exit code
1574
+ blocks on. A changed- or named-scope run grades a slice, so debt outside
1575
+ it is reported in its own words — `not graded by this changed-scope run:
1576
+ 96 blocking obligation(s) — this run never observed them; a full run
1577
+ grades them` — and never counted as new. A run is never printed twice:
1578
+ the in-runner reporter grades claims only, so it names no debt count of
1579
+ its own (`repository debt: graded by gateforge after the run`) instead of
1580
+ contradicting the CLI's line seconds later. A named or changed run never
1581
+ verdicts debt it did not observe — the in-runner reporter prints
1582
+ `GATEFORGE GATE: SELECTION (N satisfied, 0 blocking; repository verdict
1583
+ not graded here)` instead of contradicting the CLI's exit code.
1584
+
1585
+ **A merge-request pipeline with no base commit** used to resolve the
1586
+ `auto` changed-file provider to the local staged diff — zero changed
1587
+ files in a CI job, and a gate that failed an hour later on debt nobody
1588
+ changed. `test-gates --scope changed` and `check --changed` now refuse in
1589
+ seconds with exit 2 and the fix.
1590
+
1591
+ ## Gate strictness and flaky tests
1592
+
1593
+ The gate is strict by default, and that stays the default: a config
1594
+ without `mode` behaves exactly as it always has. The owner can soften
1595
+ the GATE (never the evidence) with `mode: changed` (block only on debt
1596
+ this change touches; the full debt is still reported) or `mode: warn`
1597
+ (evaluate and report everything, exit 0, with an additive `wouldBlock`),
1598
+ and can quarantine an individual flaky test with `gateforge quarantine`
1599
+ — owner-approved, expiring, never proof, never blocking, always visible
1600
+ in the report and in `gateforge enforcement doctor`. Both settings live
1601
+ inside the pinned trusted policy: an agent cannot soften the gate or
1602
+ quarantine a test to make its own commit pass.
1603
+
1604
+ ## Run the whole proof with one command
1605
+
1606
+ Reproducing a witnessed proof locally used to mean hand-building every
1607
+ precondition: the verifier key, the policy pin, the interpreter paths, the
1608
+ bytecode guard, the services, the database reset, the seed, the freeze, the
1609
+ strict check. One missed precondition cost the whole run.
1610
+
1611
+ `gateforge run` owns the generic lifecycle; your app owns the recipe:
1612
+
1613
+ ```sh
1614
+ gateforge run -- --changed --scope full # preflight, recipe, full supervised suite, strict check, teardown
1615
+ gateforge run -- --changed --scope changed # prove only the changed slice
1616
+ gateforge enforcement doctor # every precondition as one PASS/FAIL line with its fix command
1617
+ ```
1618
+
1619
+ Keep `-- --changed`: `run` forwards only the arguments after `--`, and
1620
+ `test-gates` needs `--changed` to supervise the tests and seal a receipt.
1621
+ `--scope full` proves the whole suite; `--scope changed` proves a changed slice.
1622
+
1623
+ The order is fixed: a **strict preflight** (the first failing precondition
1624
+ ends the run before a minute is spent), then the optional recipe
1625
+ `prepare → reset → seed → services_up → healthcheck`, then the supervised
1626
+ `test-gates` with your flags, then `check --require-e2e`, then
1627
+ `services_down` — always, after success and after failure. Every step prints
1628
+ one line with its duration, and the exit code is the first failing step's own
1629
+ code (2 for a usage/config/recipe error, 1 for a preflight failure or a
1630
+ failing gate, the command's own code for a recipe step, 124 for a step
1631
+ timeout).
1632
+
1633
+ `gateforge run` adds no authority: it only SEQUENCES commands you could run
1634
+ yourself, and every verdict still comes from the same engine. Recipe command
1635
+ output never reaches the console — it goes to a log file under
1636
+ `.gateforge/test-gates/run-recipe/`, because your commands may print secrets.
1637
+
1638
+ The recipe is optional and lives in `.gateforge/runtime.yml` (absent = today’s
1639
+ behavior, byte for byte). It holds **paths, never secrets**:
1640
+
1641
+ ```yaml
1642
+ schemaVersion: 1
1643
+ env_files:
1644
+ - .gateforge/test.env # paths only; the values are never printed
1645
+ reset:
1646
+ commands: [['./scripts/reset-db.sh']]
1647
+ timeoutSeconds: 300
1648
+ seed:
1649
+ commands: [['./scripts/seed.sh']]
1650
+ retries: 1
1651
+ services_up:
1652
+ commands: [['./scripts/start-stack.sh']]
1653
+ healthcheck:
1654
+ commands: [['./scripts/health.sh']]
1655
+ timeoutSeconds: 60
1656
+ retries: 5
1657
+ services_down:
1658
+ commands: [['./scripts/stop-stack.sh']]
1659
+ ```
1660
+
1661
+ An unknown key, a malformed step, or an inline value in `env_files` is a
1662
+ plain error with exit 2 — Gateforge never runs a half-understood recipe. See
1663
+ the [test environment guide](TEST-ENVIRONMENT.md) for the
1664
+ full schema, the exit-code table, and how the recipe relates to the
1665
+ witnessed pre-commit staged runtime.
1666
+
1667
+ ## The witnessed CI job
1668
+
1669
+ `gateforge enforce --ci gitlab|github` writes the **static** check job.
1670
+ Add `--witnessed` and it writes the **witnessed** job next to it — the
1671
+ lane that actually seals a receipt in CI:
1672
+
1673
+ ```sh
1674
+ gateforge enforce --ci gitlab --witnessed # .gateforge/ci/gitlab-witnessed.yml
1675
+ gateforge enforce --ci github --witnessed # .github/workflows/gateforge-witnessed.yml
1676
+ ```
1677
+
1678
+ One job, one proof. It installs the pinned Gateforge, forwards the
1679
+ merge-request base sha into BOTH supervised commands (without it the
1680
+ scope provider falls back to a local diff and can select zero changed
1681
+ files), runs `gateforge run -- --changed --scope full` so your recipe
1682
+ owns the services, reads the verdict out of `report.json`, and uploads
1683
+ `report.json`, `receipt.json`, `execution-result.json` and the run log as
1684
+ artifacts. Job-scoped stack/image names and a private per-job workspace
1685
+ come from the CI job id, so two concurrent jobs never collide.
1686
+
1687
+ You fill in exactly two things: the recipe (`.gateforge/runtime.yml`)
1688
+ and the secret variables (`GATEFORGE_WITNESS_VERIFIER_KEY`,
1689
+ `GATEFORGE_APPROVED_POLICY_DIGEST` as protected/masked CI variables or
1690
+ GitHub secrets). The generated files are plain YAML you review and edit
1691
+ yourself; an existing file is never overwritten, and without the flag
1692
+ every generated file is byte-identical to what it always was. No secret
1693
+ variable is ever echoed, and the recipe log is deliberately NOT an
1694
+ artifact — it may contain your app's secrets.
1695
+
1696
+ ## Known limitations
1697
+
1698
+ - Staged candidates containing symlinks or submodules (and unmerged index
1699
+ entries) are explicit typed blocks in `check --staged` and the broker —
1700
+ not fallbacks; support is not implemented.
1701
+ - A Playwright config without any NAMED project yields native rows with an
1702
+ empty project name that the strict catalog schema rejects as an internal
1703
+ error (exit 2) instead of a typed row; the documented consumer shape uses
1704
+ named projects, and a typed empty-project row is open work.
1705
+ - Writing `.gateforge` configuration or `test-map.yml` into the inventoried
1706
+ consumer worktree, and the server-side GitLab enforcement settings
1707
+ ("Pipelines must succeed", protected branches, pipeline execution policy),
1708
+ are pending owner actions — the complete configuration ships from
1709
+ `init --blocking`, but a local simulation does not complete a server
1710
+ rollout (internal migration record).