@sabaiway/agent-workflow-kit 23.5.0 → 23.6.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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,27 @@ Semantically versioned ([semver](https://semver.org)), newest first. The `versio
4
4
  is the current release. `upgrade` mode reads a project's `docs/ai/.workflow-version` and applies
5
5
  every `migrations/<version>-<slug>.md` newer than it, in semver order.
6
6
 
7
+ ## 23.6.0 — a changed file that a test runs elsewhere can be committed through the final run (AD-234)
8
+
9
+ **After `/agent-workflow-kit upgrade`, a project can list in `docs/ai/coverage-declared.json` the changed files that
10
+ nothing runs at their own path** — a fixture a test copies out and runs in a temporary folder, for example — each with
11
+ a reason. Before, such a file had no executed line in the coverage data, so `coverage-check` failed it on every
12
+ `run-gates --final` and the commit could not pass the guard.
13
+
14
+ - **The list is written by hand**, one exact path per entry:
15
+ `{ "schema": 1, "entries": [{ "path": "tools/fixture.mjs", "reason": "copied out and run by fixture.test.mjs" }] }`.
16
+ - **An entry can remove a coverage failure**: a listed changed file with no executed line in the coverage data is
17
+ not judged and is printed with its reason; a listed file that the run does execute is judged as any other file.
18
+ An entry naming a path git knows that is not a regular file (a link, a folder) fails the check, changed or not.
19
+ - **Every run prints the list's lines** (`coverage-check: declared list — …`), and `run-gates` echoes them under a
20
+ green coverage gate, so nothing is skipped silently.
21
+ - **The final run binds the list**: `run-gates --final` records its hash in the receipt, and `commit-guard` refuses a
22
+ list edited, created or deleted after that run. A list that is not valid fails the check with one line naming the
23
+ defect.
24
+ - **Without the file nothing changes.** One exception: `run-gates --final` now stops before it starts unless git
25
+ names one work tree for the project (a git environment pointing elsewhere included, which the commit guard
26
+ already refused), and its refusal names the git location it found and why.
27
+
7
28
  ## 23.5.0 — a rotation run that fails no longer loses journal entries or resolved issues (AD-233)
8
29
 
9
30
  **After `/agent-workflow-kit upgrade`, `run.mjs archive-changelog` and `run.mjs archive-issues` keep every entry and
package/README.md CHANGED
@@ -257,8 +257,8 @@ file), or run the guarded `/agent-workflow-kit uninstall`.
257
257
  | `/agent-workflow-kit rules` | any time | **your project rules** — the kit lays down default rules per theme (the first is project layout: where code, tests and specs live) in `docs/ai/rules/<theme>.md`; your own rules go into `docs/ai/rules/local/<theme>.md` and win where they differ. Tell the agent in plain words what to change: it shows the exact text first and writes your local file only on your yes, then rebuilds the effective file `docs/ai/rules/effective/<theme>.md` that agents read (merging your rules over the kit’s by meaning) and checks it is current. It also drops your local rules on request. Never commits. |
258
258
  | `/agent-workflow-kit grounding` | any time | **grounded-review facts assembler** — mechanizes populating `agy-review --facts @f`: slices your entry-point's **Hard Constraints** section verbatim (exactly one match, else a loud stop) and/or a plan's three canon sections (`## Goal and boundary` + `## Module ledger` + `## Verification`, each required; duplicates stop), under the same byte budget the agy wrapper enforces (minus `--reserve-bytes` for the artifact share), with a loud tail-trim on overflow. `--autonomy` (AD-044) appends the COMPUTED effective autonomy policy from the git-top `docs/ai/autonomy.json` (every red-line + per-activity level, stated source line; absent file → the computed defaults ARE the policy, exit 0; a malformed policy fails CLOSED, exit 1). `--extra <text|@file>` (repeatable) appends your own facts **byte-verbatim** after the mechanical sections, so the merge is a tool input rather than a shell append — an `@file` must sit inside the proven git work tree (never the git dir) or the system temp surface, and is read through a no-follow descriptor (a FIFO cannot block it, a symlink leaf cannot substitute its target). Prints to stdout; `--out` writes **one scratch file only** — system-temp outside the repo ($TMPDIR / /tmp, rewritable) or a **fresh** gitignored in-repo path (create-only, exclusive write; an existing in-repo file, even gitignored, is refused — the `.env` clobber class); tracked, not-ignored-in-repo, other outside-repo, and symlink/non-regular destinations are all refused. Never commits, never runs a subscription CLI. |
259
259
  | `/agent-workflow-kit core-evidence` | any time | **the ONE loop-evidence writer** (strip-the-kit) — every core evidence record lands in a single append-only JSONL store inside the git dir (never committable; versioned schema, latest-per-key supersession, byte-identical duplicates refused, malformed lines fail every reader closed). `red-proof "<file>#<pattern>"` declares an observed-red **BEFORE a bugfix** (N/N red runs + content custody + base + the pre-fix fingerprint; green/mixed/timeout are DISTINGUISHED refusals — nothing written); `degrade --backend --reason` is the ONLY escape for an unavailable review backend (per-tree, never all backends); `summary` renders the whole loop state statelessly (gate result · per-backend verdicts · red-proofs · degrades) — no ledger, no rounds, nothing remembered. Honest residual: records are forgeable — self-discipline, not a security boundary. Never commits, never runs a subscription CLI. |
260
- | `/agent-workflow-kit coverage-check` | any time | **the final-run checker** (D3(c)+(d)) — **certifies coverage ONLY inside the `--final` run that owns the lcov** (ownership is exclusive by CONVENTION over the fixed path, not enforced — a concurrent writer to it is a stated residual, queued as LCOV-EXCLUSIVE-OWNERSHIP): an artifact on disk proves nothing about the tree it came from, so a standalone run prints its findings and states `attested=no` / `NO VERDICT` rather than a PASS (an lcov that predates an edit would otherwise certify a line the suite never executed). `attested=` claims a verdict was ISSUED, pass or fail — a run over uncovered lines still reads `attested=yes` and still exits 1, and a run whose coverage arm never executed (no lcov) reads `attested=no` even inside `--final`, because nothing was read and nothing is certified. The runner passes a nonce whose one-way commitment over `{nonce, fingerprint, base}` is the `final-start.attempt` it recorded; a context describing another tree, or matching no recorded attempt, is a REFUSAL, never a verdict. Findings are unchanged — reads the lcov the declared `unit-tests` gate produced at the FIXED git-dir path and fails on any uncovered CHANGED executable Node line (listed `file:line`; a changed file absent from the map is a file-level red; out-of-domain/unsupported files are LISTED — the claim narrowed honestly); VERIFIES every current-base red-proof declaration (bound test exists · custody hash unchanged · green N/N now · pre-fix fingerprint differs); prints `lcov-sha256=<hex|none>` of the exact bytes it consumed — the sha the `--final` receipt binds and re-hashes. An absent lcov is a LOUD `skipped-no-lcov`; a symlinked path is a refusal. `--check` is the gate exit code — declare it as the LAST gate (`run-gates --final` refuses otherwise). Read-only. |
261
- | `/agent-workflow-kit commit-guard` | any time | **the read-only pre-commit guard** (D10) — makes the commit capture the whole current working tree, so «verified» and «about to be committed» are the same bytes (the receipt itself has a stated residual — see the mode doc). FIRST it refuses an **INDEX that lags the verified working tree** (the gates and the fingerprint describe the WORKING tree while `git commit` takes the INDEX alone, and the fingerprint cannot tell them apart — so a lagging index used to ship a strict subset of what was verified): unstaged tracked paths or reviewable untracked-not-ignored paths, named up to a bounded cap with the remainder stated, a dirty tracked **submodule** named separately with its own recovery, and fail-closed on an undecidable probe. This deliberately blocks a partial commit. Then it binds the LATEST completed `run-gates --final` receipt to the EXACT current tree: refuses on a missing/red/stale receipt, fingerprint drift under the run, a dangling later attempt, declaration content drift, evidence-hash or lcov drift, or unsatisfied review obligations (the same review-state decision, recomputed over a sanitized env — forged out-of-repo stores never satisfy). Re-runs NO gate or test. Wire it into `.git/hooks/pre-commit` (the installer writes the RESOLVED invocation). `git commit --no-verify` stays the stated residual. |
260
+ | `/agent-workflow-kit coverage-check` | any time | **the final-run checker** (D3(c)+(d)) — **certifies coverage ONLY inside the `--final` run that owns the lcov** (ownership is exclusive by CONVENTION over the fixed path, not enforced — a concurrent writer to it is a stated residual, queued as LCOV-EXCLUSIVE-OWNERSHIP): an artifact on disk proves nothing about the tree it came from, so a standalone run prints its findings and states `attested=no` / `NO VERDICT` rather than a PASS (an lcov that predates an edit would otherwise certify a line the suite never executed). `attested=` claims a verdict was ISSUED, pass or fail — a run over uncovered lines still reads `attested=yes` and still exits 1, and a run whose coverage arm never executed (no lcov) reads `attested=no` even inside `--final`, because nothing was read and nothing is certified. The runner passes a nonce whose one-way commitment over `{nonce, fingerprint, base}` is the `final-start.attempt` it recorded; a context describing another tree, or matching no recorded attempt, is a REFUSAL, never a verdict. Findings are unchanged — reads the lcov the declared `unit-tests` gate produced at the FIXED git-dir path and fails on any uncovered CHANGED executable Node line (listed `file:line`; a changed file absent from the map is a file-level red; out-of-domain/unsupported files are LISTED — the claim narrowed honestly); VERIFIES every current-base red-proof declaration (bound test exists · custody hash unchanged · green N/N now · pre-fix fingerprint differs); prints `lcov-sha256=<hex|none>` of the exact bytes it consumed — the sha the `--final` receipt binds and re-hashes. An absent lcov is a LOUD `skipped-no-lcov`; a symlinked path is a refusal. A file nothing runs at its repository path (a fixture a test copies out and runs elsewhere) can be listed by hand, with a reason, in `docs/ai/coverage-declared.json`: when the lcov records no executed line for that changed file it is not judged and is printed with its reason on every run, and `--final` binds the list into its receipt. `--check` is the gate exit code — declare it as the LAST gate (`run-gates --final` refuses otherwise). Read-only. |
261
+ | `/agent-workflow-kit commit-guard` | any time | **the read-only pre-commit guard** (D10) — makes the commit capture the whole current working tree, so «verified» and «about to be committed» are the same bytes (the receipt itself has a stated residual — see the mode doc). FIRST it refuses an **INDEX that lags the verified working tree** (the gates and the fingerprint describe the WORKING tree while `git commit` takes the INDEX alone, and the fingerprint cannot tell them apart — so a lagging index used to ship a strict subset of what was verified): unstaged tracked paths or reviewable untracked-not-ignored paths, named up to a bounded cap with the remainder stated, a dirty tracked **submodule** named separately with its own recovery, and fail-closed on an undecidable probe. This deliberately blocks a partial commit. Then it binds the LATEST completed `run-gates --final` receipt to the EXACT current tree: refuses on a missing/red/stale receipt, fingerprint drift under the run, a dangling later attempt, declaration content drift, evidence-hash or lcov drift, a declared coverage list (`docs/ai/coverage-declared.json`) the receipt did not bind, or unsatisfied review obligations (the same review-state decision, recomputed over a sanitized env — forged out-of-repo stores never satisfy). Re-runs NO gate or test. Wire it into `.git/hooks/pre-commit` (the installer writes the RESOLVED invocation). `git commit --no-verify` stays the stated residual. |
262
262
  | `/agent-workflow-kit recommendations` | any time (every `upgrade` ends with it) | **read-only deployment advisor** (AD-044) — computes what in THIS deployment is configured sub-optimally (allowlist not seeded, autonomy render drifted, OS sandbox unavailable, gates undeclared, bridge friction, sandbox-mask clutter, a feature-spec layer never adopted) and renders **verdict-first**: one composed verdict line (does anything need attention?), then each item as **{severity · what · one-line benefit · an optional `recipe:` line (the bridge-tier item's missing-entries line — each missing entry by kind: allow rules, exclusions, hosts, state dirs, then what the execution wrapper codex-exec needs, then the host condition; the worktrees-dir ack fallback for a host that ignores the settings key, the agents hidden-mode reconcile follow-up, a user item's own facts, the spec-adoption decline preview, or another offer's decline preview) · the exact consent-gated apply one-liner}**; `references/advisor-writers.md` names each variant's writer or user step. The agent PRESENTS the section in the user's conversational language — every fact and count, nothing added or dropped; commands, paths, hosts and rule strings byte-exact; raw tool block on request — and runs EXACTLY the rendered one-liners and the follow-up commands required by the mode doc, only on the answer authorizing that step — your yes to apply or your explicit decline to record it — with a second yes where the mode doc requires it, surfacing each item's posture note first; a kit item it applies with no question, its check line first, the harness's own dialog the only ask, or the one plain step where auto mode refuses its check or apply. Renders **present-even-when-empty** (`no recommendations — flow optimal.`); a failed probe degrades to a stated skip line. Registry strings are fact-true frozen one-line data (posture/risk notes live in the mode doc at the consent moment); `velocity --bridge-tier` seeds the used bridges' review allow rules, `<wrapper> *` exclusions (`codex-exec *` where an execute slot delegates, keeping its permission prompt), declared hosts into `sandbox.network.allowedDomains`, and home-relative state dirs into `sandbox.filesystem.allowWrite`; hosts and dirs come from the kit service fragments (`agent-workflow-kit/tools/services/`) each bridge's `capability.json` names in `services`, then from your own services list (`services.json` beside the bridge settings file, Mode: setup), and the advisor's `bridge-tier` item counts and names each missing one. `--cwd` is required (the target project is explicit); writes nothing, never commits, never runs a subscription CLI. |
263
263
  | `/agent-workflow-kit doc-parity` | any time | **read-only doc-parity lint** (AD-049) — kills the doc-drift class where a mode-contract doc silently lags a code constant (a `--check` doc still reading `300` after the diff cap moved to `400`): a **closed, exported registry** binds each live constant (review caps, schema versions, the ledger's own class/scope vocabulary, and the autonomy-doctor EXIT/status/trusted-dir contract) to the exact token its `references/modes/*.md` contract must carry, and asserts the CURRENT value renders into every bound file — a drifted doc, an unreadable file, or an absent token **fails closed**. The values are sourced from the live imports (never re-typed), so the lint can't itself go stale; adding a binding is adding a checked entry (closed-world, edit-safe). `--check` is the gate exit code a kit maintainer runs: the lint checks the kit's own package. Never writes, never commits, never runs a subscription CLI. |
264
264
  | `/agent-workflow-kit dispatch` | any time | **the delegation engine** — makes "how much does delegating a sub-task actually buy?" a measured number instead of a feeling. `check <file>` validates a sub-task brief's contract block and exits 0/1 naming the first violated field — **form only**: whether the task is genuinely bounded, its design decided and its acceptance adequate stays your judgment, and a well-formed absurdity passes here by construction. `advise --step-class <c>` answers the question that comes BEFORE that one — which vehicle should carry this kind of sub-task, whether it is even present on this machine, and what the ledger has already recorded for threads of that class (finished, failed, closed without a fold, and still open — counted separately) — and it decides nothing: it refuses no dispatch, gates no verb, and a choice that diverges from the advice is noted rather than blocked. It reads the filesystem only: nothing is launched to find out what is installed, an absent ledger prints "no recorded history", an unreadable one prints the store's own words, and either way the advice still prints. The same block appears as a footer under a form-valid `check` — never under a refusal, so it can never hide one. `register` pre-registers an acceptance wave (step classes, pairing key, minimum observations per class, the mean and first-pass thresholds) so the bar can never be chosen after the results it judges — immutable per wave. `observe` records ONE hand-written observation (`solo-construction`, the baseline whose ratio is 1 by construction — except over a scope measuring zero bytes, which has no ratio at all and is recorded ineligible by name — or `self-reported`) — delegated numbers are never hand-written, they are derived. The writer verbs are where that derivation happens: `open` puts a delegated thread on the record with every mint-time field copied from the brief's own header, refusing a deadline the wrapper's cap plus its kill grace would not fit inside, and recording whether the tree it started from was clean against the thread's base — HEAD by default, or the tree `--checkpoint <oid>` names, so the second task of a story is measured over the first one's uncommitted work instead of opening dirty (a dirty one makes the result honestly unmeasurable rather than quietly counted), while `--task <brief>` also records which task brief the thread carries out and the files that brief lists, refusing, since the last commit, a task thread whose files overlap by path prefix those of an open task thread or of a folded thread of another brief (`files-overlap`), and a mix of the two kinds — an untasked open beside an open task thread or, for a `code` open of backend `codex`, after a task fold, and a task open beside an open untasked thread (`mixed-open`), refusing at open a Files path the snapshot scope can never hold (`task-files-scope`), and measuring a task thread over its files alone, so `return` and `fold` refuse a changed path that no open or folded task thread on the same base claims (`out-of-files`); `await` waits for that one dispatch to answer and writes nothing — only the finished receipt satisfies it, a run still holding the nonce means keep waiting, and a wait that runs out says so with its own exit code, names whether the deadline or your own timeout ended it, and authorizes nothing: a wait that ended without an answer is a question for you, never permission to dispatch again; `return` absorbs the receipt the wrapper minted — only a finished one, checked against the contract it actually ran, its deadline and its own report, and refused outright when the tree hides changes from git or moves while the return is being computed — and derives the bytes from git rather than from anyone's claim; `fold` is the acceptance, and it refuses if the tree moved since the return — precisely, it re-confirms **equality of the visible canonical payload**, which is a change detector rather than a cryptographic identity of the tree: under the default head base that payload's untracked section is unframed and carries no file mode, so a content or symlink target that imitates the marker opening the next entry can alias two trees, and making an untracked file executable moves nothing (both named as residuals in the mode doc, with the fix queued); under a checkpoint base it is one indexed diff that carries modes. A change set carrying a binary, a non-regular path, a submodule, or a symlink whose target is not valid UTF-8 is **refused** at `return` and `fold` — CONSERVATIVELY, rather than promise what the default head payload may not be able to follow — and the same refusals hold for a checkpoint thread. `degrade` closes a thread that never earned a fold, on the record and with its reason. `aggregate` prints one wave: the registered thresholds, every observation as context, and per step class the finished threads — a folded success with git-provable bytes contributes its ratio, one whose bytes are unprovable is excluded from the mean but still counts in the first-pass rate, and a failed thread, a degrade-closed one, or one folded after failing acceptance each count as a real zero. Below the registered minimum nothing is computed (insufficient); at or above it is computed and labeled PILOT evidence. It REFUSES rather than guessing: no pre-registration, an unfinished thread in scope, a recorded refusal-to-delegate that never opened a thread, or an ambiguous wave each stop the computation by name. `handoff-return --slug <s>` closes the worktree loop after `land --prepare`: it re-attests that main still holds exactly the prepared tree under the same HEAD (both recorded in the handoff at prepare time), prints the satellite handoff's user-owned content byte for byte with its boundaries, byte lengths and the main-owned destinations each part folds into, prints the handoff digest and both OIDs as its proof, states the after-the-fold order (a fold landed after the gates leaves them stale), and records ONE self-reported worktree-stream observation only when the whole prepared change set is measurable — a deletion, a rename, a symlink, a submodule or a mode-only change ends with a named NOT RECORDED instead, never a partial number. Appends only to its own ledger inside the git dir (never committable); it also writes `handoff-return`'s `write-tree` tree object and, for a checkpoint measurement, the leaf's OWN temporary index file and the blobs its forced adds store — never a ref, never the real index; never commits, never runs a subscription CLI. |
package/SKILL.md CHANGED
@@ -3,7 +3,7 @@ name: agent-workflow-kit
3
3
  description: Deploy or upgrade a portable AI-agent memory-and-workflow system in any project. Use when the user wants to bootstrap `docs/ai/` + an entry-point `AGENTS.md` (+ `CLAUDE.md` alias) + cap/archive/index enforcement in a new or existing repo, set up the Memory Map and session protocols, install the docs-rotation pre-commit hook, or run `/agent-workflow-kit` / `/agent-workflow-kit upgrade`. Triggers on phrases like "set up the memory system", "deploy the AI workflow here", "bootstrap docs/ai", "upgrade the workflow". New to the epic, story and task tier? Run `/agent-workflow-kit tier`. A typed decision with a confidence from Jev? Run `/agent-workflow-kit jev`.
4
4
  disable-model-invocation: true
5
5
  metadata:
6
- version: '23.5.0'
6
+ version: '23.6.0'
7
7
  ---
8
8
 
9
9
  # agent-workflow-kit
package/capability.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schema": 1,
4
4
  "name": "agent-workflow-kit",
5
5
  "kind": "composition-root",
6
- "version": "23.5.0",
6
+ "version": "23.6.0",
7
7
  "provides": [],
8
8
  "roles": {},
9
9
  "detect": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sabaiway/agent-workflow-kit",
3
- "version": "23.5.0",
3
+ "version": "23.6.0",
4
4
  "description": "Portable, cross-agent memory & workflow for AI coding agents — Claude Code, Codex, Cursor, Devin Desktop. One command deploys an AGENTS.md entry point + docs/ai context with cap/archive/index enforcement into any repo.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -13,7 +13,7 @@ Run `node ${CLAUDE_SKILL_DIR}/tools/commit-guard.mjs --check [--cwd <dir>]` —
13
13
  5. fingerprint before ≠ after on the receipt (the tree moved UNDER the final run);
14
14
  6. a LATER `final-start` whose attempt never completed (interrupted run / failed receipt append — an attempt of unknown outcome never lets an earlier green stand);
15
15
  7. declaration content drift (the current `docs/ai/gates.json` {id, cmd} array no longer matches the receipt's recorded one);
16
- 8. evidence-hash drift (the store's canonical red-proof/degrade serializations moved under the receipt) or lcov drift (the consumed file's sha moved or vanished);
16
+ 8. evidence-hash drift (the store's canonical red-proof/degrade serializations moved under the receipt) or lcov drift (the consumed file's sha moved or vanished), or a declared coverage list `docs/ai/coverage-declared.json` the receipt did not bind — created, edited, deleted or unreadable after the run (the list may sit outside the fingerprint when git ignores it, so its hash rides `evidenceHashes.coverageDeclared`; a receipt of an earlier kit stands only while no list stands);
17
17
  9. unsatisfied review obligations — the SAME normative decision `review-state --check` computes (configured recipe backends, ship-class-only on the latest normal receipt, veto, the explicit degrade escape), recomputed over a SANITIZED env: the guard resolves FIXED git-dir paths for its own reads and ignores `AW_REVIEW_RECEIPTS`/`AW_CORE_EVIDENCE` (producer test seams are never guard inputs — a forged out-of-repo store never satisfies).
18
18
 
19
19
  **The empty-commit lane is a PASS that attests NOTHING — and it consults no receipt.** A content-free fingerprint over a CLEAN index means the index contributes no tree-content delta, so the commit changes no tree content: `git commit --allow-empty`, a message- or signature-only `--amend`, an empty merge. (What such a commit DOES change — its message, its parents, its signature — was never in the guard's domain.) The guard passes and says exactly that, because its whole claim is about the bytes a commit carries and here there are none. The receipt arms are SKIPPED rather than satisfied: the content-free fingerprint is the one value every clean moment shares, so a receipt found there cannot be correlated to THIS moment or base — letting it decide would make the outcome depend on which stray moment the store recorded last, the same reason `flow-check`'s `#65` rung steps over a content-free RED. The flow arm still runs (the commit still moves HEAD, and the chain bookkeeping is about that), with its own fingerprint-keyed correlations dropped through the explicit `treeCarriesBytes: false` the guard declares — the checker never derives that fact, because a routine clean-tree check still wants those rungs.
@@ -7,7 +7,7 @@ The **final-run checker** (strip-the-kit D3(c)+(d)) — two deterministic arms o
7
7
  Run `node ${CLAUDE_SKILL_DIR}/tools/coverage-check.mjs --check [--cwd <dir>]`:
8
8
 
9
9
  0. **Attestation precondition (the provenance arm).** An lcov on disk carries no evidence of the tree it came from, so reading one and issuing a verdict certifies whatever happens to be there — the false GREEN direction is the dangerous one, because a line appended AFTER the suite ran has no `DA` entry and therefore reads non-executable ("nothing to cover"). Provenance is a CONSEQUENCE in exactly one context: a `run-gates --final` run deletes the artifact before any gate spawns. That runner mints a random nonce and writes `final-start.attempt` as a ONE-WAY COMMITMENT over `{nonce, tree fingerprint, base}`; the raw nonce rides the environment to this child, which recomputes the commitment and requires the record to carry it. Neither half suffices alone — a bare nonce is unverifiable, a persisted attempt id is reconstructible from public repo state — and the commitment is also the only place the BASE is bound, since no record stores it. The raw nonce is stripped from the red-proof probe environment so no descendant retains a live capability. `attested=` states whether a coverage VERDICT was ISSUED — pass **or** fail — never whether coverage passed: a valid handshake over an lcov that lists uncovered lines still reads `attested=yes` and still exits 1. Outcomes: **attested** → the coverage verdict is issued; **no handshake** → `attested=no` + `NO VERDICT` (exit 0, findings still printed, uncovered lines still exit 1 — the findings contract is unchanged); **a valid handshake over a run that read NO lcov BYTES** (the file is absent, or the path was refused as a non-regular file) → `attested=no` + `NO VERDICT`: the run owned the artifact's lifetime and read nothing, so it certifies NOTHING — reading `yes` there would be the false green this arm exists to close, one layer up. The predicate is the consumed bytes (`lcov-sha256` is a digest, not `none`), never the skip flag, so a refused path can never attest either. The two halves are independent: WITHHOLDING the verdict never changes an exit code — an absent file stays exit 0 (the loud `skipped-no-lcov`), and the refused non-regular path keeps its OWN fail-closed exit 1; **a handshake describing another tree or matching no recorded attempt** → `REFUSED` (exit 1), never a verdict in either direction. One fully anchored `coverage-check: attested=<yes|no>` machine line rides every run, on the same exactly-once contract as the sha line — and a withheld verdict TRAVELS: `run-gates` carries it as `coverage=not-run` on the summary line and names it on the checker's table row, and `core-evidence summary` never renders an unqualified GREEN over a final record that consumed no lcov. Stated residuals, both named rather than implied: (a) an operator who runs both processes can forge the store or the code — the kit's standing self-discipline posture, not a security boundary; (b) **"the run owns the artifact" is exclusive by CONVENTION over the fixed path, not enforced** — a writer outside the run (a second `run-gates`, a hand-run `--only unit-tests`, an orphaned test process) can place foreign evidence between the deletion and the checker's read, and every check then agrees. Closing (b) needs an attempt-unique artifact path, which the runner can name but the declared producer cmd must reference — queued as LCOV-EXCLUSIVE-OWNERSHIP. What this arm removes is the false green that needs no second process and nobody trying: evidence that predates the edit.
10
- 1. **Coverage arm (D3(d)):** every CHANGED executable Node line (`.mjs`/`.cjs`/`.js`, tracked working-vs-HEAD changes + untracked-not-ignored files) must be covered — uncovered lines are LISTED `file:line` and fail; a changed file ABSENT from the lcov map is a file-level red (never "non-executable" by silence); changed out-of-domain files (e.g. `.sh`) and unsupported-source files (e.g. `.ts`) are LISTED — the claim is narrowed honestly, not widened. NO lcov file at the path (ENOENT) = a LOUD `skipped-no-lcov` (exit 0, stated — produce the file via the unit-tests gate's lcov reporters); any other status failure exits 1 naming the path and the code where it has one; a symlink at the path is a refusal (lstat, no-follow).
10
+ 1. **Coverage arm (D3(d)):** every CHANGED executable Node line (`.mjs`/`.cjs`/`.js`, tracked working-vs-HEAD changes + untracked-not-ignored files) must be covered — uncovered lines are LISTED `file:line` and fail; a changed file ABSENT from the lcov map is a file-level red (never "non-executable" by silence); changed out-of-domain files (e.g. `.sh`) and unsupported-source files (e.g. `.ts`) are LISTED — the claim is narrowed honestly, not widened. NO lcov file at the path (ENOENT) = a LOUD `skipped-no-lcov` (exit 0, stated — produce the file via the unit-tests gate's lcov reporters); any other status failure exits 1 naming the path and the code where it has one; a symlink at the path is a refusal (lstat, no-follow). **The declared list:** a project may name in `docs/ai/coverage-declared.json` — a strict config written by hand, `{ "schema": 1, "entries": [{ "path": "<exact repo path>", "reason": "<one line>" }] }` — changed files nothing runs at their repository path (a fixture a test copies out and runs elsewhere). A listed changed file with no executed line in the lcov this run read is not judged and is printed with its reason; one with an executed line is judged as any other file; every line about the list prints on every run. An unreadable or malformed list fails (exit 1) and applies nothing. Under a final run the list must be the one the run started with, or the checker REFUSES.
11
11
  2. **Red-proof arm (D3(c)):** every authoritative current-base `red-proof` declaration must verify — the bound test file exists (deleted fails), its content sha256 matches the declaration (custody), the test resolves (zero-match fails) and runs green N/N NOW, and the declaration's pre-fix fingerprint differs from the current tree (equal = reuse/forgery, refused). A malformed evidence store fails CLOSED.
12
12
 
13
13
  Wire it as the LAST declared gate in `docs/ai/gates.json` — `run-gates --final` REFUSES a declaration where the canonical coverage-check gate is not last (nothing may run after the checker consumed the lcov) or where its cmd is not ONE plain invocation of the kit's OWN tool (a masked form or a lookalike path never counts).
@@ -8,10 +8,10 @@ The **generic project gate runner** — it batches the project's OWN declared ve
8
8
 
9
9
  Run `node ${CLAUDE_SKILL_DIR}/tools/run-gates.mjs [--cwd <project>] [--only <id>]… [--final]`:
10
10
 
11
- 1. **Reads `docs/ai/gates.json`** (strict JSON, hand-editable; seeded from `references/templates/gates.json`). Each gate is `{ id, title, cmd }` plus the optional boolean **`lcovProducer`** (the producer paragraph below) — `id` a unique kebab handle, `cmd` **ONE bash command line** (brace/glob expansion works; a host without bash gets a loud preflight error, exit 6 — never a silent reinterpretation under another shell). The declaration names **WHAT to check, never who executes it** — the schema has no lane/model/routing fields and rejects unknown keys loudly.
12
- 2. **Runs each gate from the project root** and prints a per-gate **PASS/FAIL table** plus **one machine-readable summary line** as the last line (`[run-gates] status=… gates=… passed=… failed=… failed_ids=… coverage=…`). A failing gate's own output is preserved **verbatim** (triage without re-running); a green gate's output is not echoed; gates after a failure still run. **Exit 0 iff all selected gates are green.**
11
+ 1. **Reads `docs/ai/gates.json`** (strict JSON, hand-editable; seeded from `references/templates/gates.json`). Each gate is `{ id, title, cmd }` plus the optional boolean **`lcovProducer`** (the producer paragraph below) — `id` a unique kebab handle, `cmd` **ONE bash command line** (brace/glob expansion works; a host without bash gets a loud preflight error, exit 6, never another shell). The declaration names **WHAT to check, never who executes it** — the schema has no lane/model/routing fields and rejects unknown keys loudly.
12
+ 2. **Runs each gate from the project root** and prints a per-gate **PASS/FAIL table** plus **one machine-readable summary line** as the last line (`[run-gates] status=… gates=… passed=… failed=… failed_ids=… coverage=…`). A failing gate's own output is preserved **verbatim**; a green gate echoes only its checker's every-run lines (size warnings, declared-list lines); gates after a failure still run. **Exit 0 iff all selected gates are green.**
13
13
  3. **Honest outcomes, each distinct — never a silent green:** a **missing** declaration (exit 3 — the report names the recovery: create `docs/ai/gates.json` from the template; `upgrade` re-seeds a missing one), an **empty** `gates` list (exit 4), a **malformed/invalid** declaration (exit 5, loud `path: reason`). Repeatable **`--only <id>`** re-runs a subset; an unknown id is a loud usage error (exit 2). **`--pre-review`** runs the DERIVED mechanical subset (#66): the full matrix minus every gate whose cmd is a canonical kit checker invocation — derivation **matches canonical checker paths in the cmd strings** (realpath-resolved `--check` forms of review-state / commit-guard / coverage-check / flow-check, never a project-authored id), so a project abstracting a checker behind its own script declares it in `flow.pregateExclude` (an unknown id refuses loudly, exit 5). A failing subset gate gets the review-dependent diagnosis, naming the mechanical reset (a declared exclude changes the `subsetDigest`). **Under an ARMED flow (exactly one open adopted chain owned by this worktree) every subset run is RECORDED** as a `subset-attempt` via the flow store's locked append factory — the context keys `{planId, cycle, stepId, foldBatch, subsetDigest}`; index + hard-stop state are computed under the lock against the pre-run identity. **Hard stop (Decision 7/8):** the SECOND red records and exits red; past two reds every attempt needs `--diagnosis "<non-empty, byte-distinct from the prior>"` (recorded, self-servable); the THIRD red EXHAUSTS the context — further solo runs refuse, and only a recorded fresh-eyes consult verdict (a grounded bridge consult-attestation at this round context) reopens ONE further attempt. Armed-but-unrecordable (zero/several open chains, broken store) refuses loudly; a spawn failure records NO attempt; unarmed repos stay byte-unchanged. Mutually exclusive with `--only`/`--final` (exit 2); plain and `--final` runs never load the config.
14
- 4. **`--final`** — the D3(a) final verification run: it REFUSES `--only` (a subset never attests) and a declaration lacking the canonical core checks (ONE plain invocation each of the kit's OWN `review-state.mjs --check` and `coverage-check.mjs --check`, the checker declared LAST — a masked form, a compound, or a lookalike path never counts); deletes the stale git-dir lcov before the suite; exports `AW_GIT_DIR` + `AW_LCOV_FILE` to every gate cmd; records EVERY attempt (start + completed green/red) in the core-evidence store via its sole writer; and binds the receipt to { fingerprint before/after · the full declaration · per-gate results · the canonical red-proof + degrade evidence hashes · the sha of the lcov the checker actually read (exactly ONE `lcov-sha256` machine line, end-re-hashed) · **`evidenceHashes.flow`** when a flow store exists (D10: the sha of the OWNER-SCOPED flow projection — foreign worktrees never move it, except same-fingerprint planId-less globals, which share this tree's decision context; absent store → absent field; a broken store refuses up front) }. An artifact moving UNDER the run — the flow projection included — is a named `integrityFailure`; the receipt lands red. Stated residual: the movement arm is best-effort — an append racing the receipt write is refused at commit by the guard. A receipt that cannot be written is its own distinct outcome (exit 8): green gates never read as success without it. `${CLAUDE_SKILL_DIR}/references/modes/commit-guard.md` consumes the receipt at commit time (the guard re-hashes the live projection against it — a post-final append, or the store vanishing, refuses the commit).
14
+ 4. **`--final`** — the D3(a) final verification run: it REFUSES `--only` (a subset never attests), a git location other than one work tree, and a declaration lacking the canonical core checks (ONE plain invocation each of the kit's OWN `review-state.mjs --check` and `coverage-check.mjs --check`, the checker declared LAST — a masked form, a compound, or a lookalike path never counts); deletes the stale git-dir lcov before the suite; exports `AW_GIT_DIR` + `AW_LCOV_FILE` to every gate cmd; records EVERY attempt (start + completed green/red) in the core-evidence store via its sole writer; and binds the receipt to { fingerprint before/after · the full declaration · per-gate results · the canonical red-proof + degrade evidence hashes · the sha of the lcov the checker actually read (exactly ONE `lcov-sha256` machine line, end-re-hashed) · **`evidenceHashes.flow`** when a flow store exists (D10: the sha of the OWNER-SCOPED flow projection — foreign worktrees never move it, except same-fingerprint planId-less globals, which share this tree's decision context; absent store → absent field; a broken store refuses up front) · **`evidenceHashes.coverageDeclared`** when `docs/ai/coverage-declared.json` stands (an unreadable list refuses up front, exit 8) }. An artifact moving UNDER the run — the flow projection and that list included — is a named `integrityFailure`; the receipt lands red. Stated residual: an append racing the receipt write is refused at commit by the guard. A receipt that cannot be written is its own distinct outcome (exit 8): green gates never read as success without it. `${CLAUDE_SKILL_DIR}/references/modes/commit-guard.md` consumes the receipt at commit time (a post-final flow append, or the store vanishing, refuses the commit).
15
15
 
16
16
  The declaration is **seeded at bootstrap** (the template loop, `${CLAUDE_SKILL_DIR}/references/modes/bootstrap.md` step 6) and **ensured-if-missing on upgrade** from THIS kit's own template twin (`${CLAUDE_SKILL_DIR}/references/modes/upgrade.md` step 3) — independent of the installed memory substrate's age; an existing file is always **preserved byte-for-byte**. It is deliberately **not** a delegation-required memory asset: gates are optional, and absence is an honest runner outcome, not a deployment failure.
17
17
 
@@ -285,7 +285,7 @@ const CATALOG = [
285
285
  invocation: invocationOf('coverage-check'),
286
286
  group: 'Orchestrate',
287
287
  kind: PROJECT_EXEC,
288
- oneLine: 'The final-run checker: every CHANGED executable Node line must be covered by the lcov the declared unit-tests gate produced (uncovered lines listed file:line), and every current-base red-proof declaration must verify (bound test green N/N, content custody intact); --check turns it into a gate exit code.',
288
+ oneLine: 'The final-run checker: every CHANGED executable Node line must be covered by the lcov the declared unit-tests gate produced (uncovered lines listed file:line), and every current-base red-proof declaration must verify (bound test green N/N, content custody intact); a changed file listed in docs/ai/coverage-declared.json that nothing ran is not judged and is printed with its reason; --check turns it into a gate exit code.',
289
289
  },
290
290
  {
291
291
  key: 'commit-guard',
@@ -26,10 +26,12 @@
26
26
  // red record · fingerprintBefore ≠ fingerprintAfter · a LATER final-start with no completion
27
27
  // (an attempt of unknown outcome) · a DECLARATION whose current {id, cmd} content differs
28
28
  // from the recorded one · evidence hashes that no longer match the store's canonical
29
- // red-proof/degrade serializations · an lcov file whose sha moved. The guard's own reads
29
+ // red-proof/degrade serializations · an lcov file whose sha moved · a declared coverage list
30
+ // the receipt did not bind. The guard's own reads
30
31
  // resolve FIXED git-dir paths (env overrides are producer test seams, never guard inputs);
31
- // 3. consults the flow decision (Plan 3 Phase 2, two-tier): with NO flow store file the guard is
32
- // byte-identical to the pre-flow guard; a PRESENT store must read clean and its refusals
32
+ // 3. consults the flow decision (Plan 3 Phase 2, two-tier): with NO flow store file and a receipt
33
+ // carrying no evidenceHashes.flow, the flow arm adds nothing to the guard's decision or its
34
+ // PASS line; a PRESENT store must read clean and its refusals
33
35
  // (open own chain, base motion, coverage, ordering) refuse the commit with the flow-check
34
36
  // reason verbatim — a foreign worktree's chain stays advisory; the armed state extends the
35
37
  // PASS line;
@@ -50,6 +52,7 @@ import {
50
52
  computeWorkingState, CONTENT_FREE_FINGERPRINT,
51
53
  } from './core-evidence.mjs';
52
54
  import { resolveLcovPath } from './coverage-check.mjs';
55
+ import { checkDeclaredBinding, COVERAGE_DECLARED_REL } from './coverage-declared/index.mjs';
53
56
  import { GATES_REL, loadDeclaration } from './run-gates.mjs';
54
57
  import { computeFlowDecision } from './flow-check.mjs';
55
58
  import { resolveGitLocation } from './git-env.mjs';
@@ -304,6 +307,8 @@ export const runGuard = ({ cwd = process.cwd(), env = process.env } = {}) => {
304
307
  return { code: 1, lines: ['commit-guard: REFUSED — the lcov file the receipt consumed moved or vanished; re-run run-gates.mjs --final'] };
305
308
  }
306
309
  }
310
+ const declaredBinding = checkDeclaredBinding({ top: rootTop, field: current.evidenceHashes.coverageDeclared });
311
+ if (!declaredBinding.ok) return { code: 1, lines: [declaredBinding.line] };
307
312
  // The flow arm (#43/P3, two-tier over FIXED git-derived paths): no store file ⇒ byte-exact
308
313
  // prior behavior; a present store's refusals (malformed reads included) refuse with the
309
314
  // flow-check reason verbatim. The commit-guard consumer mode arms the D10 flow→final
@@ -329,7 +334,7 @@ export const runGuard = ({ cwd = process.cwd(), env = process.env } = {}) => {
329
334
  const flowSuffix = flow.present && flow.armed
330
335
  ? ` — flow: armed${review.flowLabels?.length ? ` (${review.flowLabels.join('; ')})` : ''}`
331
336
  : '';
332
- return { code: 0, lines: [`commit-guard: PASS — a green final receipt binds this exact tree (${fingerprint.slice(0, 12)}…), the declaration and evidence hashes match, and the review obligations are satisfied${flowSuffix}`, ...flowAdvisoryLines(flow)] };
337
+ return { code: 0, lines: [`commit-guard: PASS — a green final receipt binds this exact tree (${fingerprint.slice(0, 12)}…), the declaration and evidence hashes match, and the review obligations are satisfied${declaredBinding.suffix}${flowSuffix}`, ...flowAdvisoryLines(flow)] };
333
338
  };
334
339
 
335
340
  const HELP = `commit-guard — the read-only pre-commit guard (agent-workflow family, D10).
@@ -351,6 +356,7 @@ bytes: \`--allow-empty\`, a message-only \`--amend\`, an empty merge).
351
356
  Otherwise it binds
352
357
  the LATEST completed run-gates --final receipt — refusing on { no receipt for this tree · a red
353
358
  latest attempt · before≠after · declaration content drift · evidence-hash drift · lcov drift ·
359
+ a declared coverage list (${COVERAGE_DECLARED_REL}) the receipt did not bind ·
354
360
  a flow-store refusal (a PRESENT store's open own chain / base motion / coverage — verbatim; no
355
361
  store file = byte-exact pre-flow behavior) · unsatisfied review obligations (the review-state
356
362
  decision, over a sanitized env — receipts/evidence/flow-store/delegation-store seams stripped) }. Wire it into
@@ -40,6 +40,7 @@ const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArr
40
40
  const isNonEmptyString = (v) => typeof v === 'string' && v.length > 0;
41
41
  const HEX64_RE = /^[0-9a-f]{64}$/;
42
42
  const HEX40_RE = /^[0-9a-f]{40}$/;
43
+ const COVERAGE_DECLARED_HASH_REASON = 'final: evidenceHashes.coverageDeclared, when present, must be a 64-hex sha256 of the declared coverage list';
43
44
 
44
45
  export const validateEvidenceRecord = (record) => {
45
46
  if (!isPlainObject(record)) return { ok: false, reason: 'record is not an object' };
@@ -105,6 +106,9 @@ export const validateEvidenceRecord = (record) => {
105
106
  if ('flow' in record.evidenceHashes && (typeof record.evidenceHashes.flow !== 'string' || !HEX64_RE.test(record.evidenceHashes.flow))) {
106
107
  return { ok: false, reason: 'final: evidenceHashes.flow, when present, must be a 64-hex sha256 of the owner-scoped flow projection' };
107
108
  }
109
+ if ('coverageDeclared' in record.evidenceHashes && (typeof record.evidenceHashes.coverageDeclared !== 'string' || !HEX64_RE.test(record.evidenceHashes.coverageDeclared))) {
110
+ return { ok: false, reason: COVERAGE_DECLARED_HASH_REASON };
111
+ }
108
112
  if (record.lcovSha256 !== null && (typeof record.lcovSha256 !== 'string' || !HEX64_RE.test(record.lcovSha256))) {
109
113
  return { ok: false, reason: 'final: lcovSha256 must be a 64-hex sha256 of the consumed lcov file, or null when none was produced' };
110
114
  }
@@ -28,6 +28,7 @@ import { GIT_MAX_BUFFER } from './git-env.mjs';
28
28
  import { computeChangedSurface } from './changed-surface.mjs';
29
29
  import { isDirectRun } from './direct-run.mjs';
30
30
  import { lcovCoveredMap, uncoveredChangedFromLcov } from './lcov.mjs';
31
+ import { COVERAGE_DECLARED_REL, resolveDeclaredListPath, readDeclaredList, judgeDeclaredList, compareDeclaredAttest, declaredPassLine } from './coverage-declared/index.mjs';
31
32
  import {
32
33
  computeTreeFingerprint,
33
34
  resolveBase,
@@ -64,10 +65,9 @@ export const resolveLcovPath = (cwd, env = process.env) => {
64
65
 
65
66
  // ── the coverage arm (D3(d)) ──────────────────────────────────────────────────────────────────────
66
67
 
67
- // checkCoverage({ rootTop, lcovPath }) → { failures: ["file:line"...], notes: [...], skipped,
68
- // lcovSha256 } — the sha is of the EXACT bytes this check consumed (read once), so the final-run
69
- // receipt can bind what was CHECKED, not what happens to sit on disk later (M2, round 1).
70
- const checkCoverage = ({ rootTop, lcovPath }) => {
68
+ // The lcov sha is of the EXACT bytes this check consumed (read once), so the final-run receipt can
69
+ // bind what was CHECKED, not what happens to sit on disk later (M2, round 1).
70
+ const checkCoverage = ({ rootTop, lcovPath, judgeDeclared }) => {
71
71
  const notes = [];
72
72
  const failures = [];
73
73
  let st = null;
@@ -75,20 +75,22 @@ const checkCoverage = ({ rootTop, lcovPath }) => {
75
75
  st = lstatSync(lcovPath);
76
76
  } catch (error) {
77
77
  if (error?.code === 'ENOENT') {
78
- return { failures, notes: [`skipped-no-lcov: no lcov file at ${lcovPath} — NO coverage check ran (produce it via the declared unit-tests gate cmd's lcov reporters)`], skipped: true, lcovSha256: null };
78
+ return { failures, notes: [`skipped-no-lcov: no lcov file at ${lcovPath} — NO coverage check ran (produce it via the declared unit-tests gate cmd's lcov reporters)`], skipped: true, lcovSha256: null, declared: judgeDeclared(null) };
79
79
  }
80
80
  failures.push(`${lcovPath}: status could not be read (${error?.code ?? 'fs error'})`);
81
- return { failures, notes, skipped: false, lcovSha256: null };
81
+ return { failures, notes, skipped: false, lcovSha256: null, declared: judgeDeclared(null) };
82
82
  }
83
83
  if (!st.isFile()) {
84
84
  failures.push(`${lcovPath}: not a regular file (a symlink/device is never read — fail closed)`);
85
- return { failures, notes, skipped: false, lcovSha256: null };
85
+ return { failures, notes, skipped: false, lcovSha256: null, declared: judgeDeclared(null) };
86
86
  }
87
87
  const surface = computeChangedSurface(rootTop);
88
88
  const lcovBytes = readFileSync(lcovPath);
89
89
  const lcovSha256 = createHash('sha256').update(lcovBytes).digest('hex');
90
90
  const covered = lcovCoveredMap(lcovBytes.toString('utf8'), rootTop);
91
+ const declared = judgeDeclared(new Map([...surface.assessable.keys()].map((rel) => [rel, covered.get(keyFor(rootTop, rel))])));
91
92
  for (const [rel, lines] of surface.assessable) {
93
+ if (declared.notJudged.includes(rel)) continue;
92
94
  const key = keyFor(rootTop, rel);
93
95
  const uncovered = uncoveredChangedFromLcov(covered, key, lines);
94
96
  if (uncovered === null) {
@@ -103,7 +105,7 @@ const checkCoverage = ({ rootTop, lcovPath }) => {
103
105
  if (surface.unsupported.length > 0) {
104
106
  notes.push(`unsupported-source changed files (outside the narrowed Node domain): ${surface.unsupported.join(', ')}`);
105
107
  }
106
- return { failures, notes, skipped: false, lcovSha256 };
108
+ return { failures, notes, skipped: false, lcovSha256, declared };
107
109
  };
108
110
 
109
111
  // lcovCoveredMap canonicalizes SF paths with realpath — the lookup key must mirror it. On an
@@ -140,7 +142,8 @@ export const keyFor = (rootTop, rel) => {
140
142
  export const ATTEST_NONCE_ENV = 'AW_FINAL_ATTEST_NONCE';
141
143
  export const ATTEST_FINGERPRINT_ENV = 'AW_FINAL_ATTEST_FINGERPRINT';
142
144
  export const ATTEST_BASE_ENV = 'AW_FINAL_ATTEST_BASE';
143
- const ATTEST_ENV_VARS = Object.freeze([ATTEST_NONCE_ENV, ATTEST_FINGERPRINT_ENV, ATTEST_BASE_ENV]);
145
+ export const ATTEST_DECLARED_ENV = 'AW_FINAL_ATTEST_DECLARED';
146
+ export const ATTEST_ENV_VARS = Object.freeze([ATTEST_NONCE_ENV, ATTEST_FINGERPRINT_ENV, ATTEST_BASE_ENV, ATTEST_DECLARED_ENV]);
144
147
 
145
148
  // The commitment bytes: newline-joined, which is unambiguous because every field is hex or empty
146
149
  // (the nonce and fingerprint by construction, the base a git object id or '' on an unborn branch).
@@ -160,7 +163,7 @@ export const withoutAttestEnv = (env) => {
160
163
  // the ordinary non-attesting case, which is exit 0 and merely withholds the verdict.
161
164
  // Exported as a test seam (the keyFor idiom): the undecidable-identity arm below cannot be reached
162
165
  // through the CLI, where a resolvable work tree is a precondition of getting this far.
163
- export const attestationState = ({ env, records, fingerprint, base }) => {
166
+ export const attestationState = ({ env, records, fingerprint, base, declared }) => {
164
167
  const nonce = env[ATTEST_NONCE_ENV];
165
168
  if (typeof nonce !== 'string' || nonce === '') {
166
169
  return { attesting: false, reason: 'no final-run attestation context — a verdict is issued only inside the run that owns the lcov (run-gates.mjs --final); findings below are informational' };
@@ -173,6 +176,10 @@ export const attestationState = ({ env, records, fingerprint, base }) => {
173
176
  if (passedFingerprint !== fingerprint || passedBase !== (base ?? '')) {
174
177
  return { refusal: `the tree MOVED under the final run (the attestation context describes ${passedFingerprint.slice(0, 12)}…@${passedBase.slice(0, 12) || 'unborn'}, this tree is ${fingerprint.slice(0, 12)}…@${(base ?? '').slice(0, 12) || 'unborn'}) — a gate changed the working tree after the suite produced the lcov; re-run run-gates.mjs --final` };
175
178
  }
179
+ const comparison = compareDeclaredAttest(env[ATTEST_DECLARED_ENV], declared);
180
+ if (!comparison.accepted) {
181
+ return { refusal: `the declared coverage list is not the one the final run started with (${comparison.handed} handed, ${comparison.read} read); re-run run-gates.mjs --final` };
182
+ }
176
183
  const want = commitmentFor(nonce, fingerprint, base ?? '');
177
184
  if (!records.some((r) => r.kind === 'final-start' && r.attempt === want)) {
178
185
  return { refusal: 'the attestation context matches no recorded final-run attempt — the evidence store lost or never received the start record; re-run run-gates.mjs --final' };
@@ -240,6 +247,7 @@ const verifyRedProofs = ({ rootTop, cwd, env }) => {
240
247
  export const runCheck = ({ cwd = process.cwd(), env = process.env } = {}) => {
241
248
  const rootTop = gitLine(['rev-parse', '--show-toplevel'], cwd);
242
249
  if (rootTop == null) return { code: 0, lines: ['coverage-check: not a git work tree — nothing to check'] };
250
+ const read = readDeclaredList(resolveDeclaredListPath(rootTop));
243
251
  const lcovPath = resolveLcovPath(cwd, env);
244
252
  const lines = [];
245
253
  let failed = false;
@@ -248,20 +256,23 @@ export const runCheck = ({ cwd = process.cwd(), env = process.env } = {}) => {
248
256
  const identityBefore = { fingerprint: computeTreeFingerprint(cwd), base: resolveBase(cwd) };
249
257
  const storePath = resolveEvidencePath(cwd, env);
250
258
  const storeRecords = storePath ? readEvidence(storePath).records : [];
251
- const attestBefore = attestationState({ env, records: storeRecords, ...identityBefore });
252
- const cov = checkCoverage({ rootTop, lcovPath });
259
+ const attestBefore = attestationState({ env, records: storeRecords, ...identityBefore, declared: read });
260
+ const cov = checkCoverage({ rootTop, lcovPath, judgeDeclared: (changed) => judgeDeclaredList({ top: rootTop, read, changed }) });
261
+ const declared = cov.declared;
253
262
  // The machine line the final-run receipt binds (M2): the sha of the exact bytes THIS check
254
263
  // consumed — `none` states loudly that no lcov was read.
255
264
  lines.push(`coverage-check: lcov-sha256=${cov.lcovSha256 ?? 'none'}`);
256
- if (cov.skipped) {
257
- lines.push(`coverage-check: ${cov.notes[0]}`);
258
- } else {
259
- for (const note of cov.notes) lines.push(`coverage-check: ${note}`);
260
- if (cov.failures.length > 0) {
261
- failed = true;
262
- lines.push('coverage-check: FAIL — uncovered/unattributed changed Node lines:');
263
- for (const f of cov.failures) lines.push(` ${f}`);
264
- }
265
+ for (const note of cov.notes) lines.push(`coverage-check: ${note}`);
266
+ lines.push(...declared.lines);
267
+ if (declared.configFailure) {
268
+ failed = true;
269
+ lines.push(declared.configFailure);
270
+ }
271
+ const failures = [...cov.failures, ...declared.failures];
272
+ if (failures.length > 0) {
273
+ failed = true;
274
+ lines.push('coverage-check: FAIL — uncovered/unattributed changed Node lines:');
275
+ for (const f of failures) lines.push(` ${f}`);
265
276
  }
266
277
  // The probes must never inherit a live attestation capability (a detached descendant could keep it).
267
278
  const red = verifyRedProofs({ rootTop, cwd, env: withoutAttestEnv(env) });
@@ -280,7 +291,7 @@ export const runCheck = ({ cwd = process.cwd(), env = process.env } = {}) => {
280
291
  // Re-read the identity AFTER the coverage arm and re-decide: the attestation must describe the
281
292
  // tree the verdict was actually computed over, not the one it started over.
282
293
  const identityAfter = { fingerprint: computeTreeFingerprint(cwd), base: resolveBase(cwd) };
283
- const attestAfter = attestationState({ env, records: storeRecords, ...identityAfter });
294
+ const attestAfter = attestationState({ env, records: storeRecords, ...identityAfter, declared: read });
284
295
  const attestation = attestBefore.refusal ? attestBefore : attestAfter;
285
296
  const contextValid = attestation.attesting === true && attestBefore.attesting === true;
286
297
  // `attested=` states whether a coverage VERDICT was ISSUED — pass OR fail — never that coverage
@@ -301,7 +312,7 @@ export const runCheck = ({ cwd = process.cwd(), env = process.env } = {}) => {
301
312
  // The attestation gates ONLY the coverage claim. Every pre-existing fail-closed refusal above
302
313
  // (symlinked lcov, malformed evidence store, unmet red-proof obligation) keeps its own exit 1.
303
314
  if (attesting && !failed && cov.failures.length === 0) {
304
- lines.push('coverage-check: PASS — every changed Node line is covered');
315
+ lines.push(declaredPassLine(declared.notJudged.length));
305
316
  }
306
317
  return { code: failed ? 1 : 0, lines };
307
318
  };
@@ -322,6 +333,10 @@ every current-base red-proof record: bound test present, content hash unchanged,
322
333
  An absent lcov file (ENOENT) is a LOUD skipped-no-lcov (exit 0 — NO coverage check ran, stated).
323
334
  Any other lcov status failure, a symlinked lcov path, an uncovered line, a broken red-proof
324
335
  obligation, or a malformed evidence store fails (exit 1).
336
+ A changed file listed in ${COVERAGE_DECLARED_REL} (one { path, reason } entry per file nothing
337
+ runs at its repository path) with no executed line in the lcov read is not judged; it and every
338
+ other list line print on every run. An unreadable or malformed list fails (exit 1); with a context
339
+ the list must be the one the final run started with (AW_FINAL_ATTEST_DECLARED), else REFUSED.
325
340
 
326
341
  A coverage VERDICT is issued ONLY inside the run that owns the artifact's lifetime: run-gates
327
342
  --final deletes the lcov before any gate spawns and hands this checker an attestation context
@@ -335,7 +350,7 @@ coverage VERDICT was ISSUED — pass OR fail — never that coverage passed.
335
350
  changes an exit code: an absent lcov stays exit 0, a refused non-regular path
336
351
  keeps its own fail-closed exit 1, and uncovered lines still exit 1. Findings are
337
352
  still printed; run-gates carries the withheld verdict as coverage=not-run.
338
- REFUSED (exit 1) → the context describes another tree, or matches no recorded attempt.
353
+ REFUSED (exit 1) → the context describes another tree or another declared list, or matches no recorded attempt.
339
354
  Residual, stated: ownership of the fixed path is CONVENTION, not enforcement — a concurrent writer
340
355
  to it can still place foreign evidence (queued as LCOV-EXCLUSIVE-OWNERSHIP).
341
356
 
@@ -372,8 +387,7 @@ if (isDirectRun(import.meta.url)) {
372
387
  // process.env, so leaving it in place would hand a live attestation context to each of them —
373
388
  // and a detached descendant could then certify a foreign lcov long after this run ended.
374
389
  const attest = Object.fromEntries(
375
- [ATTEST_NONCE_ENV, ATTEST_FINGERPRINT_ENV, ATTEST_BASE_ENV]
376
- .filter((k) => process.env[k] !== undefined)
390
+ ATTEST_ENV_VARS.filter((k) => process.env[k] !== undefined)
377
391
  .map((k) => [k, process.env[k]]),
378
392
  );
379
393
  for (const k of Object.keys(attest)) delete process.env[k];
@@ -0,0 +1,186 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { lstatSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { classifyChangedPath } from '../changed-surface.mjs';
5
+ import { isLineUnsafe } from '../source-size-refusal.mjs';
6
+ import { readFileBytesNoFollow } from '../fs-read-nofollow.mjs';
7
+
8
+ export const COVERAGE_DECLARED_REL = 'docs/ai/coverage-declared.json';
9
+ export const DECLARED_REASON_MAX_BYTES = 300;
10
+
11
+ const SHAPE = '{ "schema": 1, "_README"?: string, "entries": [{ "path": string, "reason": string }, ...] }';
12
+ const SCHEMA = 1;
13
+ const TOP_KEYS = new Set(['schema', 'entries', '_README']);
14
+ const ENTRY_KEYS = new Set(['path', 'reason']);
15
+ const ABSENT = 'absent';
16
+ const REGULAR = 'regular';
17
+ const UNREADABLE = 'unreadable';
18
+ const OK = 'ok';
19
+ const FOREIGN = 'foreign';
20
+ const MISSING = 'ENOENT';
21
+ const NONE = 'none';
22
+ const STRING = 'string';
23
+ const OBJECT = 'object';
24
+ const UTF8 = 'utf-8';
25
+ const HASH_ALGORITHM = 'sha256';
26
+ const HEX = 'hex';
27
+ const HASH_PATTERN = /^[0-9a-f]{64}$/;
28
+ const HASH_LENGTH = 64;
29
+ const HASH_DISPLAY_LENGTH = 12;
30
+ const HEX_RADIX = 16;
31
+ const ESCAPE_WIDTH = 4;
32
+ const ESCAPE_PADDING = '0';
33
+ const SEPARATOR = '/';
34
+ const BACKSLASH = '\\';
35
+ const INVALID_SEGMENTS = new Set(['', '.', '..']);
36
+ const ASSESSABLE = 'assessable';
37
+ const DISPLAY = {
38
+ noValue: 'no value', malformed: 'a malformed value', unreadable: 'an unreadable list',
39
+ noList: 'no list', absent: 'absent', notReadable: 'not readable', another: 'another list',
40
+ unprintableKey: 'an unprintable key',
41
+ };
42
+ const DEFECT = {
43
+ json: 'not JSON', object: 'not a JSON object', schema: 'schema must be the number 1',
44
+ entries: 'entries must be an array', readme: '_README must be a string',
45
+ entryObject: 'must be an object', missingKey: 'is missing key', extraKey: 'has unknown key',
46
+ pathString: 'must be a string', pathEmpty: 'must not be empty',
47
+ pathAbsolute: 'must be repository-relative', pathBackslash: 'must not contain a backslash',
48
+ pathSegment: 'must not contain an empty, . or .. segment', pathUnsafe: 'contains unsafe characters',
49
+ pathDuplicate: 'duplicates an earlier entry', pathClass: 'is not assessable',
50
+ reasonString: 'must be a string', reasonBlank: 'must not be blank',
51
+ reasonUnsafe: 'contains unsafe characters',
52
+ };
53
+
54
+ export const resolveDeclaredListPath = (top) => join(top, COVERAGE_DECLARED_REL);
55
+
56
+ const renderSafeText = (value) => Array.from(String(value), (character) => isLineUnsafe(character)
57
+ ? `\\u${character.codePointAt(0).toString(HEX_RADIX).padStart(ESCAPE_WIDTH, ESCAPE_PADDING)}`
58
+ : character).join('');
59
+
60
+ export const readDeclaredList = (path, io = {}) => {
61
+ try {
62
+ (io.lstat ?? lstatSync)(path);
63
+ } catch (error) {
64
+ if (error?.code === MISSING) return { state: ABSENT };
65
+ }
66
+ const read = readFileBytesNoFollow(path, io);
67
+ if (read.outcome === ABSENT) return { state: ABSENT };
68
+ if (read.outcome === OK) {
69
+ return { state: REGULAR, bytes: read.bytes,
70
+ hash: createHash(HASH_ALGORITHM).update(read.bytes).digest(HEX) };
71
+ }
72
+ const defect = read.outcome === FOREIGN
73
+ ? `not a regular file (${renderSafeText(read.className)})` : renderSafeText(read.code);
74
+ return { state: UNREADABLE, defect };
75
+ };
76
+
77
+ const makeShapeDefect = (detail) => ({ ok: false, defect: `${detail}; the list must be ${SHAPE}` });
78
+ const renderKey = (key) => {
79
+ const rendered = JSON.stringify(key);
80
+ return isLineUnsafe(rendered) ? DISPLAY.unprintableKey : rendered;
81
+ };
82
+ const isPlainObject = (value) => value !== null && typeof value === OBJECT && !Array.isArray(value);
83
+
84
+ const checkListShape = (value) => {
85
+ if (!isPlainObject(value)) return makeShapeDefect(DEFECT.object);
86
+ const unknownKey = Object.keys(value).find((key) => !TOP_KEYS.has(key));
87
+ if (unknownKey !== undefined) return makeShapeDefect(`${DEFECT.extraKey} ${renderKey(unknownKey)}`);
88
+ if (value.schema !== SCHEMA) return makeShapeDefect(DEFECT.schema);
89
+ if (!Array.isArray(value.entries)) return makeShapeDefect(DEFECT.entries);
90
+ if (Object.hasOwn(value, '_README') && typeof value._README !== STRING) return makeShapeDefect(DEFECT.readme);
91
+ for (const [index, entry] of value.entries.entries()) {
92
+ const label = `entries[${index}]`;
93
+ if (!isPlainObject(entry)) return makeShapeDefect(`${label} ${DEFECT.entryObject}`);
94
+ const missingKey = [...ENTRY_KEYS].find((key) => !Object.hasOwn(entry, key));
95
+ if (missingKey !== undefined) return makeShapeDefect(`${label} ${DEFECT.missingKey} ${renderKey(missingKey)}`);
96
+ const extraKey = Object.keys(entry).find((key) => !ENTRY_KEYS.has(key));
97
+ if (extraKey !== undefined) return makeShapeDefect(`${label} ${DEFECT.extraKey} ${renderKey(extraKey)}`);
98
+ }
99
+ return null;
100
+ };
101
+
102
+ const checkPath = (path, seen) => {
103
+ if (typeof path !== STRING) return DEFECT.pathString;
104
+ if (path === '') return DEFECT.pathEmpty;
105
+ if (path.startsWith(SEPARATOR)) return DEFECT.pathAbsolute;
106
+ if (path.includes(BACKSLASH)) return DEFECT.pathBackslash;
107
+ if (path.split(SEPARATOR).some((segment) => INVALID_SEGMENTS.has(segment))) return DEFECT.pathSegment;
108
+ if (isLineUnsafe(path)) return DEFECT.pathUnsafe;
109
+ if (seen.has(path)) return DEFECT.pathDuplicate;
110
+ if (classifyChangedPath(path) !== ASSESSABLE) return DEFECT.pathClass;
111
+ seen.add(path);
112
+ return null;
113
+ };
114
+
115
+ const checkReason = (reason) => {
116
+ if (typeof reason !== STRING) return DEFECT.reasonString;
117
+ if (reason.trim() === '') return DEFECT.reasonBlank;
118
+ if (Buffer.byteLength(reason, UTF8) > DECLARED_REASON_MAX_BYTES) {
119
+ return `exceeds ${DECLARED_REASON_MAX_BYTES} UTF-8 bytes`;
120
+ }
121
+ if (isLineUnsafe(reason)) return DEFECT.reasonUnsafe;
122
+ return null;
123
+ };
124
+
125
+ export const parseDeclaredList = (bytes) => {
126
+ const parsed = (() => {
127
+ try {
128
+ return { value: JSON.parse(new TextDecoder(UTF8, { fatal: true, ignoreBOM: true }).decode(bytes)) };
129
+ } catch {
130
+ return { failure: makeShapeDefect(DEFECT.json) };
131
+ }
132
+ })();
133
+ if (parsed.failure) return parsed.failure;
134
+ const shapeDefect = checkListShape(parsed.value);
135
+ if (shapeDefect) return shapeDefect;
136
+ const entries = parsed.value.entries;
137
+ const seen = new Set();
138
+ for (const [index, entry] of entries.entries()) {
139
+ const defect = checkPath(entry.path, seen);
140
+ if (defect) return { ok: false, defect: `entries[${index}].path ${defect}` };
141
+ }
142
+ for (const [index, entry] of entries.entries()) {
143
+ const defect = checkReason(entry.reason);
144
+ if (defect) return { ok: false, defect: `entries[${index}].reason ${defect}` };
145
+ }
146
+ return { ok: true, entries: entries.map(({ path, reason }) => ({ path, reason })) };
147
+ };
148
+
149
+ export const declaredAttestValue = (read) => {
150
+ if (read.state === ABSENT) return NONE;
151
+ return read.state === REGULAR ? read.hash : null;
152
+ };
153
+
154
+ const isHash = (value) => typeof value === STRING && value.length === HASH_LENGTH && HASH_PATTERN.test(value);
155
+ const renderHanded = (handed) => {
156
+ if (handed === NONE) return NONE;
157
+ if (isHash(handed)) return handed.slice(0, HASH_DISPLAY_LENGTH);
158
+ return handed === undefined || handed === null ? DISPLAY.noValue : DISPLAY.malformed;
159
+ };
160
+
161
+ export const compareDeclaredAttest = (handed, read) => {
162
+ const accepted = (handed === NONE && read.state === ABSENT)
163
+ || (isHash(handed) && read.state === REGULAR && handed === read.hash);
164
+ if (accepted) return { accepted: true };
165
+ const displayedRead = read.state === ABSENT ? NONE
166
+ : read.state === REGULAR ? read.hash.slice(0, HASH_DISPLAY_LENGTH) : DISPLAY.unreadable;
167
+ return { accepted: false, handed: renderHanded(handed), read: displayedRead };
168
+ };
169
+
170
+ export const checkDeclaredBinding = ({ top, field, io = {} }) => {
171
+ const read = readDeclaredList(resolveDeclaredListPath(top), io);
172
+ const hasField = field !== undefined;
173
+ const comparison = compareDeclaredAttest(hasField ? field : NONE, read);
174
+ const parsed = hasField && comparison.accepted ? parseDeclaredList(read.bytes) : null;
175
+ if (comparison.accepted && (!hasField || parsed.ok)) {
176
+ const suffix = hasField
177
+ ? ` — declared coverage list ${COVERAGE_DECLARED_REL} bound, ${parsed.entries.length} entr(ies)` : '';
178
+ return { ok: true, suffix };
179
+ }
180
+ const bound = !hasField ? DISPLAY.noList
181
+ : isHash(field) ? field.slice(0, HASH_DISPLAY_LENGTH) : DISPLAY.malformed;
182
+ const current = read.state === ABSENT ? DISPLAY.absent
183
+ : read.state === UNREADABLE || (parsed && !parsed.ok) ? DISPLAY.notReadable : DISPLAY.another;
184
+ return { ok: false,
185
+ line: `commit-guard: REFUSED — the declared coverage list is not the one the final run bound (the receipt binds ${bound}, ${COVERAGE_DECLARED_REL} is ${current}); re-run run-gates.mjs --final` };
186
+ };
@@ -0,0 +1,2 @@
1
+ export { COVERAGE_DECLARED_REL, DECLARED_REASON_MAX_BYTES, resolveDeclaredListPath, readDeclaredList, parseDeclaredList, declaredAttestValue, compareDeclaredAttest, checkDeclaredBinding } from './config.mjs';
2
+ export { DECLARED_LINE_PREFIX, DECLARED_MOVED_FAILURE, judgeDeclaredList, declaredPassLine, declaredStartRefusal } from './judge.mjs';
@@ -0,0 +1,88 @@
1
+ import { join } from 'node:path';
2
+ import { COVERAGE_DECLARED_REL, parseDeclaredList } from './config.mjs';
3
+ import { probeRegularFileNoFollow } from '../fs-read-nofollow.mjs';
4
+ import { listGitNamedPaths } from '../tracked-tree-census.mjs';
5
+
6
+ export const DECLARED_LINE_PREFIX = 'coverage-check: declared list — ';
7
+ export const DECLARED_MOVED_FAILURE = 'the declared coverage list moved under the final run';
8
+
9
+ const ABSENT = 'absent';
10
+ const UNREADABLE = 'unreadable';
11
+ const FOREIGN = 'foreign';
12
+ const ERROR = 'error';
13
+ const UTF8 = 'utf8';
14
+ const ZERO = 0;
15
+ const ASCII_FIRST = 32;
16
+ const ASCII_LAST = 126;
17
+ const HEX_RADIX = 16;
18
+ const ESCAPE_WIDTH = 4;
19
+ const ESCAPE_PADDING = '0';
20
+ const EMPTY_TEXT = '';
21
+ const CONFIG_FAILURE_PREFIX = `coverage-check: FAIL — ${COVERAGE_DECLARED_REL}: `;
22
+ const PASS_LINE = 'coverage-check: PASS — every changed Node line is covered';
23
+
24
+ const makeResult = (configFailure = null) => ({ configFailure, notJudged: [], lines: [], failures: [] });
25
+ const makeConfigFailure = (defect) => makeResult(`${CONFIG_FAILURE_PREFIX}${defect}`);
26
+ const renderAsciiLine = (value) => Array.from(String(value), (character) => {
27
+ const codePoint = character.codePointAt(ZERO);
28
+ return codePoint >= ASCII_FIRST && codePoint <= ASCII_LAST
29
+ ? character : `\\u{${codePoint.toString(HEX_RADIX).padStart(ESCAPE_WIDTH, ESCAPE_PADDING)}}`;
30
+ }).join(EMPTY_TEXT);
31
+
32
+ export const judgeDeclaredList = ({ top, read, changed, spawn }) => {
33
+ if (read.state === ABSENT) return makeResult();
34
+ if (read.state === UNREADABLE) return makeConfigFailure(read.defect);
35
+ const parsed = parseDeclaredList(read.bytes);
36
+ if (!parsed.ok) return makeConfigFailure(parsed.defect);
37
+ const entries = parsed.entries;
38
+ if (entries.length === ZERO) return makeResult();
39
+ const listed = (() => {
40
+ try {
41
+ return { paths: listGitNamedPaths(top, { untracked: true, spawn }) };
42
+ } catch (error) {
43
+ return { failure: makeConfigFailure(renderAsciiLine(error.message)) };
44
+ }
45
+ })();
46
+ if (listed.failure) return listed.failure;
47
+ const result = makeResult();
48
+ const unchanged = [];
49
+ for (const entry of entries) {
50
+ const entryBytes = Buffer.from(entry.path, UTF8);
51
+ const named = listed.paths.some((name) => name.equals(entryBytes));
52
+ const probe = named ? probeRegularFileNoFollow(join(top, entry.path)) : { outcome: ABSENT };
53
+ if (probe.outcome === ABSENT) {
54
+ result.lines.push(`${DECLARED_LINE_PREFIX}names no file of this tree: ${entry.path}`);
55
+ continue;
56
+ }
57
+ if (probe.outcome === FOREIGN || probe.outcome === ERROR) {
58
+ result.failures.push(`${entry.path}: listed in ${COVERAGE_DECLARED_REL} but not a regular file`);
59
+ continue;
60
+ }
61
+ if (changed === null) continue;
62
+ if (!changed.has(entry.path)) {
63
+ unchanged.push(entry.path);
64
+ continue;
65
+ }
66
+ const lineMap = changed.get(entry.path);
67
+ const executed = lineMap !== undefined && [...lineMap.values()].some((hits) => hits > ZERO);
68
+ if (executed) {
69
+ result.lines.push(`${DECLARED_LINE_PREFIX}did not apply, the coverage data shows an executed line: ${entry.path}`);
70
+ } else {
71
+ result.notJudged.push(entry.path);
72
+ result.lines.push(`${DECLARED_LINE_PREFIX}not judged, no executed line in the coverage data: ${entry.path} — ${entry.reason}`);
73
+ }
74
+ }
75
+ if (changed === null) {
76
+ result.lines.push(`${DECLARED_LINE_PREFIX}no coverage data was read, so no entry applied (${entries.length} listed)`);
77
+ } else if (unchanged.length > ZERO) {
78
+ result.lines.push(`${DECLARED_LINE_PREFIX}${unchanged.length} listed file(s) unchanged, not looked up`);
79
+ }
80
+ return result;
81
+ };
82
+
83
+ export const declaredPassLine = (count) => count > ZERO
84
+ ? `coverage-check: PASS — ${count} listed file(s) not judged; every other changed Node line is covered`
85
+ : PASS_LINE;
86
+
87
+ export const declaredStartRefusal = (read) =>
88
+ `[run-gates] --final: ${COVERAGE_DECLARED_REL} is not readable (${read.defect}) — the declared coverage list cannot be bound; nothing was recorded`;
@@ -64,6 +64,7 @@ import { COVERAGE } from './coverage-state.mjs';
64
64
  // The canonical producer body: gates.md prints the whole command byte for byte, so the doc is a
65
65
  // hand copy of a moving constant unless it is bound here.
66
66
  import { COVERAGE_PRODUCER_BODY } from './coverage-producer.mjs';
67
+ import { COVERAGE_DECLARED_REL } from './coverage-declared/index.mjs';
67
68
  // The ensure outcomes upgrade.md relays: the doc enumerates them for the agent, so an outcome the
68
69
  // tool renames or drops must fail here rather than leave the doc teaching a vocabulary nobody emits.
69
70
  // Imported from the VOCABULARY leaf, never from the ops: a read-only lint must not pull the ensure
@@ -86,6 +87,8 @@ const PROCEDURES_DOC = 'references/modes/procedures.md';
86
87
  const SET_FLOW_DOC = 'references/modes/set-flow.md';
87
88
  const RECEIPT_DEADLINE_DOC = 'references/modes/receipt-deadline.md';
88
89
  const GATES_DOC = 'references/modes/gates.md';
90
+ const COVERAGE_CHECK_DOC = 'references/modes/coverage-check.md';
91
+ const COMMIT_GUARD_DOC = 'references/modes/commit-guard.md';
89
92
  const MCP_DOC = 'references/modes/mcp.md';
90
93
  const UNINSTALL_DOC = 'references/modes/uninstall.md';
91
94
  const STATUS_DOC = 'references/modes/status.md';
@@ -230,6 +233,9 @@ export const BINDINGS = Object.freeze([
230
233
  // sees the doc. Bound here, a future move fails a declared gate instead of leaving the contract
231
234
  // doc quietly describing a command the kit no longer emits.
232
235
  valueBinding('coverage-producer-body', COVERAGE_PRODUCER_BODY, COVERAGE_PRODUCER_BODY, [GATES_DOC]),
236
+ valueBinding('coverage-declared-rel', COVERAGE_DECLARED_REL, `\`${COVERAGE_DECLARED_REL}\``, [
237
+ COVERAGE_CHECK_DOC, GATES_DOC, COMMIT_GUARD_DOC,
238
+ ]),
233
239
  // The MCP registration's four public strings (mode: mcp). TWO docs quote each of them: the mode
234
240
  // contract, which tells a reader what will be declared, and the uninstall KEEP list, which tells
235
241
  // them what to edit to undo it — so a renamed key or tool would otherwise leave one of the two
@@ -313,7 +319,8 @@ FORM-only + aggregate-refusal contract and the routing advisor's two honesty sen
313
319
  advice never gates, and the harness-subagent lane carries no availability verdict (dispatch.md), the
314
320
  runner's closed coverage= summary
315
321
  vocabulary (gates.md), the canonical coverage-producer-body command the same doc prints in full
316
- (gates.md), and the MCP registration's five public strings — mcp-json-rel, mcp-enabled-key,
322
+ (gates.md), the declared coverage list's path coverage-declared-rel (coverage-check.md, gates.md,
323
+ commit-guard.md), and the MCP registration's five public strings — mcp-json-rel, mcp-enabled-key,
317
324
  mcp-server-name and the two mcp-allow-rule entries, each quoted by BOTH the mcp mode contract and the
318
325
  uninstall KEEP list that undoes it (mcp.md, uninstall.md) — to
319
326
  the exact token its references/modes/*.md contract must carry, and
@@ -56,7 +56,7 @@ import {
56
56
  commitmentFor,
57
57
  ATTEST_NONCE_ENV,
58
58
  ATTEST_FINGERPRINT_ENV,
59
- ATTEST_BASE_ENV,
59
+ ATTEST_BASE_ENV, ATTEST_DECLARED_ENV, ATTEST_ENV_VARS,
60
60
  } from './coverage-check.mjs';
61
61
  // The declaration load/validation + the canonical checker predicate family live in the
62
62
  // gates-declaration.mjs LEAF (FLOW-READ-GRAPH-PURITY / the R10 rider: the locked subset-attempt
@@ -73,6 +73,10 @@ import {
73
73
  // only direction that has no cycle. Re-exported here: this module is the vocabulary's public face.
74
74
  import { COVERAGE } from './coverage-state.mjs';
75
75
  import { CHECKER_CLAIM, SOURCE_SIZE_WARNING_PREFIX, classifySourceSizeGate } from './source-size-core.mjs';
76
+ import { checkerClaimTool, classifyCheckerClaim } from './checker-claim.mjs';
77
+ import { resolveGitLocation } from './git-env.mjs';
78
+ import { escapeForDisplay } from './repo-lex.mjs';
79
+ import { COVERAGE_DECLARED_REL, DECLARED_LINE_PREFIX, DECLARED_MOVED_FAILURE, resolveDeclaredListPath, readDeclaredList, declaredStartRefusal, declaredAttestValue, compareDeclaredAttest } from './coverage-declared/index.mjs';
76
80
 
77
81
  export { GATES_REL, loadDeclaration, validateDeclaration, canonicalCheckerGates, isFinalCapableDeclaration, isReviewDependentGate };
78
82
  export { COVERAGE };
@@ -98,6 +102,7 @@ export const fail = (exitCode, message) => Object.assign(new Error(message), { e
98
102
  const NO_FAILED_IDS = '-';
99
103
  const SPAWN_FAILED_CODE = -1;
100
104
  const MAX_GATE_OUTPUT_BYTES = 64 * 1024 * 1024;
105
+ const NO_ECHO_SKIP_INDEX = -1;
101
106
 
102
107
  const USAGE = [
103
108
  'usage: run-gates.mjs [--cwd <dir>] [--only <id>]... [--final] [--pre-review [--diagnosis <text>]] [--help]',
@@ -127,6 +132,9 @@ const USAGE = [
127
132
  'degrade evidence hashes, the lcov sha, the run\'s own coverage token, and — when a flow store',
128
133
  'exists — evidenceHashes.flow, the owner-scoped flow projection hash (D10; projection movement',
129
134
  'under the run is a red integrityFailure) }. --final refuses --only (a subset never attests).',
135
+ `--final needs one git work tree, and binds the declared coverage list ${COVERAGE_DECLARED_REL}: an`,
136
+ 'unreadable list refuses (exit 8), a list that moves under the run is a red integrityFailure, its hash',
137
+ 'rides evidenceHashes.coverageDeclared. A green coverage-check gate echoes the list lines on every run.',
130
138
  '',
131
139
  `Runs the gates declared in <cwd>/${GATES_REL} (one bash command line each, project root as cwd).`,
132
140
  'Prints a per-gate PASS/FAIL table + one machine-readable summary line; exit 0 iff all green.',
@@ -188,7 +196,7 @@ export const RESERVED_PRODUCER_ENV = Object.freeze(['AW_GIT_DIR', 'AW_LCOV_FILE'
188
196
  // other child (and any descendant it spawns) must see it absent, host-set copies included, or that
189
197
  // descendant could certify a foreign lcov later. Conflating the two lists made a gate that merely
190
198
  // MENTIONS the name refuse the whole run.
191
- export const RESERVED_CAPABILITY_ENV = Object.freeze([ATTEST_NONCE_ENV, ATTEST_FINGERPRINT_ENV, ATTEST_BASE_ENV]);
199
+ export const RESERVED_CAPABILITY_ENV = ATTEST_ENV_VARS;
192
200
 
193
201
  export const spawnGateViaBash = (cmd, cwd, extraEnv = {}) => {
194
202
  const env = { ...process.env };
@@ -228,19 +236,21 @@ export const BASH_PROBE_CMD = 'true';
228
236
  const formatSeconds = (ms) => `${(ms / 1000).toFixed(1)}s`;
229
237
  const trimTrailingNewline = (text) => text.replace(/\n$/, '');
230
238
 
231
- // A green source-size check's warnings print on every run, so the matrix echoes them — and nothing
232
- // else of its output — under a gate running this checker or a regular-file copy of it elsewhere.
233
- const SOURCE_SIZE_CLAIMS = new Set([CHECKER_CLAIM.CANONICAL, CHECKER_CLAIM.ELSEWHERE]);
234
- const sourceSizeWarnings = (gate, cwd, stdout) => (SOURCE_SIZE_CLAIMS.has(classifySourceSizeGate(gate.cmd, cwd))
235
- ? String(stdout).split(/\r?\n/).filter((line) => line.startsWith(SOURCE_SIZE_WARNING_PREFIX))
236
- : []);
239
+ // A green size or coverage check marks every-run lines with its prefix; the matrix echoes only
240
+ // those lines under a gate running the canonical checker or a regular-file copy of it elsewhere.
241
+ const COVERAGE_CHECK_TOOL = checkerClaimTool('coverage-check.mjs', FINAL_CORE_CHECKS[1].canonical);
242
+ const GREEN_GATE_LINE_PREFIXES = Object.freeze([
243
+ [(cmd, cwd) => [CHECKER_CLAIM.CANONICAL, CHECKER_CLAIM.ELSEWHERE].includes(classifySourceSizeGate(cmd, cwd)), SOURCE_SIZE_WARNING_PREFIX],
244
+ [(cmd, cwd) => matchesCanonicalCheck(FINAL_CORE_CHECKS[1], cmd, cwd) || classifyCheckerClaim(COVERAGE_CHECK_TOOL, cmd, cwd) === CHECKER_CLAIM.ELSEWHERE, DECLARED_LINE_PREFIX],
245
+ ]);
246
+ const selectGreenGateLines = (gate, cwd, stdout) => GREEN_GATE_LINE_PREFIXES.flatMap(([matches, prefix]) => matches(gate.cmd, cwd) ? String(stdout).split(/\r?\n/).filter((line) => line.startsWith(prefix)) : []);
237
247
 
238
248
  // Run the selected gates sequentially (declaration order). A green gate logs one PASS line (and a
239
249
  // source-size check its warnings); a failing gate logs FAIL + its captured stdout/stderr VERBATIM
240
250
  // (triage without re-running).
241
- export const runGates = (gates, { cwd, spawn = spawnGateViaBash, now = Date.now, log = console.log }) => {
251
+ export const runGates = (gates, { cwd, spawn = spawnGateViaBash, now = Date.now, log = console.log, echoSkipAt = NO_ECHO_SKIP_INDEX }) => {
242
252
  const results = [];
243
- for (const gate of gates) {
253
+ for (const [gateIndex, gate] of gates.entries()) {
244
254
  log(`── ${gate.id} — ${gate.title}`);
245
255
  const startedAt = now();
246
256
  const res = spawn(gate.cmd, cwd);
@@ -251,7 +261,7 @@ export const runGates = (gates, { cwd, spawn = spawnGateViaBash, now = Date.now,
251
261
  results.push({ id: gate.id, title: gate.title, ok, code, elapsedMs, stdout: res.stdout ? String(res.stdout) : '' });
252
262
  if (ok) {
253
263
  log(` PASS (${formatSeconds(elapsedMs)})`);
254
- for (const line of sourceSizeWarnings(gate, cwd, res.stdout ?? '')) log(line);
264
+ if (gateIndex !== echoSkipAt) for (const line of selectGreenGateLines(gate, cwd, res.stdout ?? '')) log(line);
255
265
  } else {
256
266
  log(` FAIL exit=${code} (${formatSeconds(elapsedMs)})`);
257
267
  if (res.stdout) log(trimTrailingNewline(res.stdout));
@@ -584,6 +594,7 @@ export const runCli = (argv, deps = {}) => {
584
594
  const dirRes = spawnSync('git', ['rev-parse', '--absolute-git-dir'], { cwd: projectDir, windowsHide: true });
585
595
  const gitDir = dirRes.error || dirRes.status !== 0 ? null : dirRes.stdout.toString('utf8').replace(/\r?\n$/, '');
586
596
  let gateSpawn = gitDir === null ? spawn : (cmd, cwd2) => spawn(cmd, cwd2, { AW_GIT_DIR: gitDir });
597
+ const finalLocation = opts.final ? resolveGitLocation(projectDir, { env }) : null;
587
598
  // ── --final preflight (D3(a)): the declaration must carry the canonical core checks; the TRUE
588
599
  // git dir resolves AW_GIT_DIR; the stale lcov dies BEFORE the suite so it is never consumed.
589
600
  if (opts.final) {
@@ -602,7 +613,7 @@ export const runCli = (argv, deps = {}) => {
602
613
  if (!matchesCanonicalCheck(FINAL_CORE_CHECKS[1], lastGate.cmd, projectDir)) {
603
614
  throw fail(EXIT.malformed, `--final refuses the declaration — the CANONICAL coverage-check gate must be the LAST declared gate (nothing may run after the checker consumed the lcov; "${lastGate.id}" is declared last)`);
604
615
  }
605
- if (gitDir === null) throw fail(EXIT.fail, '--final needs a git work tree (cannot resolve the git dir)');
616
+ if (finalLocation.state !== 'work-tree') throw fail(EXIT.fail, `--final needs a git work tree (${finalLocation.state}: ${escapeForDisplay(finalLocation.cause)})`);
606
617
  try {
607
618
  unlinkSync(join(gitDir, LCOV_BASENAME)); // a stale lcov is never consumed
608
619
  } catch (err) {
@@ -642,6 +653,12 @@ export const runCli = (argv, deps = {}) => {
642
653
  // --final needs the pre-run fingerprint (the receipt binds before == after == current).
643
654
  const finalFingerprintBefore = opts.final ? fingerprint(projectDir) : null;
644
655
  const finalBase = opts.final ? resolveBase(projectDir) ?? '' : null;
656
+ const declaredStart = opts.final ? readDeclaredList(resolveDeclaredListPath(finalLocation.top)) : null;
657
+ if (declaredStart?.state === 'unreadable') {
658
+ logError(declaredStartRefusal(declaredStart));
659
+ log(composeSummaryLine({ status: 'fail' }));
660
+ return EXIT.finalFailed;
661
+ }
645
662
  // The attestation handshake (see coverage-check.mjs): a fresh random nonce rides the child
646
663
  // environment, and the attempt id this run records is the one-way COMMITMENT over it plus the
647
664
  // identity. Persisting only the commitment is what makes the context unreproducible from the
@@ -661,6 +678,7 @@ export const runCli = (argv, deps = {}) => {
661
678
  [ATTEST_NONCE_ENV]: finalNonce,
662
679
  [ATTEST_FINGERPRINT_ENV]: finalFingerprintBefore ?? '',
663
680
  [ATTEST_BASE_ENV]: finalBase,
681
+ [ATTEST_DECLARED_ENV]: declaredAttestValue(declaredStart),
664
682
  });
665
683
  };
666
684
  }
@@ -742,7 +760,7 @@ export const runCli = (argv, deps = {}) => {
742
760
  // The checker's position is pinned BEFORE the matrix spawns; the tree it leaves behind never
743
761
  // gets to re-decide which gate this run selected.
744
762
  const checkerAt = resolveCheckerIndex(selected, projectDir);
745
- const results = runGates(selected, { cwd: projectDir, spawn: gateSpawn, log, now });
763
+ const results = runGates(selected, { cwd: projectDir, spawn: gateSpawn, log, now, echoSkipAt: opts.final ? checkerAt : NO_ECHO_SKIP_INDEX });
746
764
  // Decided once, from the checker's own machine lines, and carried to BOTH surfaces of this run:
747
765
  // the checker's table row and the machine summary field (Decision 7/8).
748
766
  const coverage = coverageSignal(checkerAt, results);
@@ -854,6 +872,7 @@ export const runCli = (argv, deps = {}) => {
854
872
  integrityFailure = 'the flow store moved under the final run (the owner-scoped projection changed)';
855
873
  }
856
874
  }
875
+ if (integrityFailure === null && !compareDeclaredAttest(declaredAttestValue(declaredStart), readDeclaredList(resolveDeclaredListPath(finalLocation.top))).accepted) integrityFailure = DECLARED_MOVED_FAILURE;
857
876
  // Exactly ONE full machine line binds the receipt — an unanchored first-match would let
858
877
  // an injected/duplicated line shadow the real one and skip the end re-hash.
859
878
  const shaLines = anchoredMachineLines(checkerRow?.stdout, LCOV_SHA_LINE_RE);
@@ -908,6 +927,7 @@ export const runCli = (argv, deps = {}) => {
908
927
  degrade: sha256Hex(canonicalKindSerialization(endRead.records, 'degrade')),
909
928
  }),
910
929
  ...(finalFlow?.present ? { flow: finalFlow.hash } : {}),
930
+ ...(declaredStart.state === 'regular' ? { coverageDeclared: declaredStart.hash } : {}),
911
931
  },
912
932
  lcovSha256,
913
933
  // The run's OWN coverage token, recorded rather than re-derived: `lcovSha256` says what
@@ -43,8 +43,11 @@ const splitOnNul = (buffer) => {
43
43
  return parts;
44
44
  };
45
45
 
46
- const listTrackedPaths = (root, spawn) => {
47
- const result = spawn('git', ['ls-files', '-z'], { cwd: root, maxBuffer: GIT_MAX_BUFFER, windowsHide: true });
46
+ const TRACKED_PATH_ARGS = ['ls-files', '-z'];
47
+ const ALL_NAMED_PATH_ARGS = ['ls-files', '-z', '--cached', '--others', '--exclude-standard'];
48
+ export const listGitNamedPaths = (root, { untracked = false, spawn = spawnSync } = {}) => {
49
+ const args = untracked ? ALL_NAMED_PATH_ARGS : TRACKED_PATH_ARGS;
50
+ const result = spawn('git', args, { cwd: root, maxBuffer: GIT_MAX_BUFFER, windowsHide: true });
48
51
  if (result.error || result.status !== 0) {
49
52
  const reason = result.error ? (result.error.code ?? result.error.message) : `git exited ${result.status}`;
50
53
  throw Object.assign(new Error(`tracked-tree census unavailable: ${reason}`), { code: 'CENSUS_UNAVAILABLE' });
@@ -57,7 +60,7 @@ const listTrackedPaths = (root, spawn) => {
57
60
  const identity = part.toString('latin1'); // byte-exact key: one char per byte, never lossy
58
61
  if (seenBytes.has(identity)) continue;
59
62
  seenBytes.add(identity);
60
- paths.push(part.toString('utf8'));
63
+ paths.push(part);
61
64
  }
62
65
  return paths;
63
66
  };
@@ -76,7 +79,8 @@ const listTrackedPaths = (root, spawn) => {
76
79
  export const takeCensus = (root, { spawn = spawnSync } = {}) => {
77
80
  const counts = { assessable: 0, unsupported: 0, 'out-of-domain': 0, 'excluded-test': 0 };
78
81
  const unsupportedExtensions = new Set();
79
- for (const path of listTrackedPaths(root, spawn)) {
82
+ for (const name of listGitNamedPaths(root, { spawn })) {
83
+ const path = name.toString('utf8');
80
84
  const kind = classifyChangedPath(path);
81
85
  counts[kind] += 1;
82
86
  if (kind === 'unsupported') {