@sabaiway/agent-workflow-kit 5.3.0 → 5.4.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.
@@ -10,6 +10,7 @@ import { readFileSync, lstatSync, realpathSync } from 'node:fs';
10
10
  import { join, isAbsolute } from 'node:path';
11
11
  import { fileURLToPath } from 'node:url';
12
12
  import { fail, loadConfig, CONFIG_REL } from './orchestration-config.mjs';
13
+ import { matchesCoverageProducer } from './coverage-producer.mjs';
13
14
 
14
15
  // The per-project declaration (strict JSON, hand-editable). cwd-relative — errors show a path the
15
16
  // user can open (the orchestration-config CONFIG_REL idiom).
@@ -140,6 +141,54 @@ export const isFinalCapableDeclaration = (gates, projectDir) => {
140
141
  return matchesCanonicalCheck(FINAL_CORE_CHECKS[1], gates[gates.length - 1].cmd, projectDir);
141
142
  };
142
143
 
144
+ // coverageProducerPrecedes(gates, checkerIndex) → whether a producer runs BEFORE the checker at that
145
+ // index. ORDER is the whole question: a producer declared AFTER the checker writes the lcov too late,
146
+ // so the checker reads nothing — or, worse, stale bytes an earlier run left behind — and still
147
+ // passes. ONE home for the rule: the written-declaration defects below and the advisor's
148
+ // inert-declaration item both decide through it, so they cannot drift apart.
149
+ export const coverageProducerPrecedes = (gates, checkerIndex) =>
150
+ gates.slice(0, checkerIndex).some((gate) => matchesCoverageProducer(gate.cmd));
151
+
152
+ // coverageDeclarationDefects(gates, projectDir) → the WRITTEN-declaration coverage rule, as a list
153
+ // of named defects (empty = satisfied): at most ONE canonical coverage checker; if one is present
154
+ // it is LAST, and a producer precedes it. Consumers turn a defect into their own refusal — an
155
+ // offer-level check alone is not enough, because the declaration that gets WRITTEN is a merge of an
156
+ // existing file with a consented subset, and every one of these three shapes is reachable that way.
157
+ // Order is deliberate: a duplicate must be resolved before order or production can even be read.
158
+ export const coverageDeclarationDefects = (gates, projectDir) => {
159
+ const checkers = canonicalCheckerGates(gates, projectDir);
160
+ if (checkers.length > 1) {
161
+ return [{
162
+ kind: 'duplicate-checker',
163
+ message:
164
+ `${GATES_REL}: ${checkers.length} gates are the canonical coverage checker (${checkers.map((g) => g.id).join(', ')}) — ` +
165
+ '--final accepts exactly one; keep a single checker and remove the rest',
166
+ }];
167
+ }
168
+ if (checkers.length === 0) return []; // no checker declared — coverage is optional, nothing to enforce
169
+ const index = gates.indexOf(checkers[0]);
170
+ const after = gates.slice(index + 1);
171
+ if (after.length > 0) {
172
+ return [{
173
+ kind: 'checker-not-last',
174
+ message:
175
+ `${GATES_REL}: the canonical coverage checker (${checkers[0].id}) must be the LAST declared gate — ` +
176
+ `${after.map((g) => g.id).join(', ')} would run after it consumed the lcov. REORDER the declaration by hand ` +
177
+ '(the gate itself is fine — this is an ORDERING refusal, and the fill is append-only, so it cannot reorder for you)',
178
+ }];
179
+ }
180
+ if (!coverageProducerPrecedes(gates, index)) {
181
+ return [{
182
+ kind: 'no-producer',
183
+ message:
184
+ `${GATES_REL}: the canonical coverage checker (${checkers[0].id}) is declared but NO gate would produce the lcov it reads — ` +
185
+ 'the checker would pass while verifying nothing. Declare a suite gate carrying the coverage reporters ' +
186
+ '(references/modes/gates.md names the exact form), or drop the checker',
187
+ }];
188
+ }
189
+ return [];
190
+ };
191
+
143
192
  // The review-dependent predicate (#66/P14): a gate is review-dependent iff its cmd IS the plain
144
193
  // canonical `--check` invocation of one of the kit's OWN checkers, resolved by realpath — never a
145
194
  // project-authored id. A project abstracting the invocation behind its own script declares it in
@@ -30,6 +30,12 @@
30
30
  // • the safety claim is scoped to the OFFER DERIVATION, not a runtime sandbox: a gate still
31
31
  // executes project-controlled tooling (a node_modules/.bin PATH shim intercepts under every
32
32
  // form) — the documented residual, disclosed in the preview, bounded by the two consents;
33
+ // • a `node --test` suite body — the ONE allowlist member that produces lcov unaided — is
34
+ // emitted WITH the canonical coverage reporters, so the offered checker has a producer; every
35
+ // other body is emitted verbatim. The coverage-check candidate is WITHHELD (loud note) when
36
+ // neither the offer nor the existing declaration carries a producer, and --apply refuses to
37
+ // WRITE a declaration whose checker has no producer, is not last, or has a canonical twin:
38
+ // the checker READS an lcov, and with nothing writing it the gate passes certifying nothing;
33
39
  // • ids derive kebab-case from script names (build:prod → build-prod) and every offered entry
34
40
  // passes the runner's validateDeclaration (this module imports the validator — NEVER the
35
41
  // reverse: run-gates.mjs stays a runner that writes nothing);
@@ -54,6 +60,8 @@ import { join, resolve, dirname } from 'node:path';
54
60
  import { fileURLToPath, pathToFileURL } from 'node:url';
55
61
  import { discoverGateCandidates, EXPECTED_WORKFLOW_VERSION } from './velocity-profile.mjs';
56
62
  import { GATES_REL, validateDeclaration } from './run-gates.mjs';
63
+ import { coverageDeclarationDefects, isReviewDependentGate } from './gates-declaration.mjs';
64
+ import { COVERAGE_PRODUCER_BODY, matchesCoverageProducer } from './coverage-producer.mjs';
57
65
  import { loadConfig } from './orchestration-config.mjs';
58
66
  import { assertDocsAiDeployment, writeDocsAiFileAtomic, lstatNoFollow } from './atomic-write.mjs';
59
67
 
@@ -95,7 +103,10 @@ never watch/serve, never a write-mode variant) whose BODY is a member of the lit
95
103
  allowlist is offered, as the hook-free \`COREPACK_ENABLE_NETWORK=0 <pm> exec -- <body>\` form for
96
104
  the detected package manager. A gate-class script whose body is NOT in the allowlist is screened
97
105
  out with a note naming it (a command you trust can still be declared by hand); non-gate-class
98
- names are excluded silently, as always.
106
+ names are excluded silently, as always. A \`node --test\` body carries the canonical coverage
107
+ reporters; the coverage-check candidate is withheld when nothing would produce the lcov it reads,
108
+ and --apply refuses to write a checker with no producer, a checker that is not last, or a second
109
+ canonical checker.
99
110
  ${TRUST_CHAIN_DISCLOSURE}`;
100
111
 
101
112
  // ── candidate classification: the NAME screens (the LOCKED derivation invariants) ──────
@@ -195,6 +206,13 @@ export const execCmdFor = (pm, body) => {
195
206
  };
196
207
  };
197
208
 
209
+ // The coverage PRODUCER wiring (Decision 1 — closed-world here too). `node --test` is the only
210
+ // allowlist body that produces lcov with no extra dependency, so it is the only body the offer
211
+ // extends with the reporter flags; every other body is emitted verbatim and produces none (an
212
+ // optional-dependency coverage flag set would be speculation about the project's own tooling).
213
+ const COVERAGE_PRODUCING_BODY = 'node --test';
214
+ const emittedBodyOf = (body) => (body === COVERAGE_PRODUCING_BODY ? COVERAGE_PRODUCER_BODY : body);
215
+
198
216
  export const kebabIdOf = (name) =>
199
217
  String(name)
200
218
  .toLowerCase()
@@ -253,12 +271,14 @@ const deriveScripts = (cwd, deps = {}) => {
253
271
  screenedIds.push(id);
254
272
  continue;
255
273
  }
256
- const { cmd, note } = execCmdFor(pm, body);
274
+ const emitted = emittedBodyOf(body);
275
+ const { cmd, note } = execCmdFor(pm, emitted);
257
276
  if (cmd === null) {
258
277
  withheld.push({ id, note });
259
278
  continue;
260
279
  }
261
- entries.push({ id, title: `Project script ${c.scriptName}: ${body}`, cmd });
280
+ const coverage = emitted === body ? '' : ' (+ the lcov reporters the coverage checker reads)';
281
+ entries.push({ id, title: `Project script ${c.scriptName}: ${body}${coverage}`, cmd });
262
282
  }
263
283
  const notes = [];
264
284
  if (screenedIds.length) {
@@ -397,7 +417,10 @@ const assertOnlyIdsOffered = (offer, onlyIds = []) => {
397
417
  const offered = new Set(offer.entries.map((e) => e.id));
398
418
  const unknown = onlyIds.filter((id) => !offered.has(id));
399
419
  if (unknown.length) {
400
- throw usageFail(`--only names ids not in the offer: ${unknown.join(', ')} (offered: ${[...offered].join(', ') || 'none'})`);
420
+ // The offer's notes carry WHY a candidate is absent (a withheld checker, a screened body); an
421
+ // id-not-offered error without them reads as a typo the user did not make.
422
+ const why = offer.notes.length ? ` — why: ${offer.notes.join(' | ')}` : '';
423
+ throw usageFail(`--only names ids not in the offer: ${unknown.join(', ')} (offered: ${[...offered].join(', ') || 'none'})${why}`);
401
424
  }
402
425
  };
403
426
 
@@ -411,10 +434,47 @@ export const buildOffer = (cwd, deps = {}) => {
411
434
  const rs = reviewStateCandidate(cwd, deps);
412
435
  const fc = flowCheckCandidate(cwd, deps);
413
436
  const cc = coverageCheckCandidate(cwd, deps);
414
- const candidates = [rs.candidate, fc.candidate, cc.candidate].filter(Boolean);
437
+ // Decision 3 the checker is never offered DEAD. The producer may come from this offer or from
438
+ // a declaration the user already wrote by hand, so the rule reads the merged picture; a
439
+ // declaration this preview cannot read degrades to a stated note, never to a silent withhold.
440
+ const existing = declaredGatesBestEffort(cwd, deps);
441
+ const producerPresent =
442
+ scripts.entries.some((entry) => matchesCoverageProducer(entry.cmd)) ||
443
+ existing.gates.some((gate) => matchesCoverageProducer(gate.cmd));
444
+ const withholdCoverage = cc.candidate !== null && !producerPresent;
445
+ const coverageNote = withholdCoverage
446
+ ? `the coverage-check candidate was withheld: nothing would PRODUCE the lcov it reads — no offered or ` +
447
+ `declared gate carries the canonical coverage reporters, and a checker with no producer passes while ` +
448
+ `verifying nothing (declare a suite gate per references/modes/gates.md, then re-run)`
449
+ : cc.note;
450
+ // ALWAYS stated, not only when it changed the withhold: the preview would otherwise promise an
451
+ // applicable offer over a declaration --apply is certain to refuse.
452
+ const unreadableNote =
453
+ existing.unreadable === null
454
+ ? null
455
+ : `the existing ${GATES_REL} could not be read (${existing.unreadable}) — this preview treated it as EMPTY, and --apply will refuse until it is fixed`;
456
+ // An offer that lists nothing but the kit's own checkers reads like a clean offer; say the
457
+ // consequence out loud (no command bodies are echoed — an unvetted body must never become one
458
+ // keystroke from a declared, hook-auto-approvable gate). The offer-level fact is ALWAYS true; the
459
+ // matrix claim and the advice are only true in ONE of three declaration states, and asserting
460
+ // them in the other two would be the same false report this seam exists to remove:
461
+ // unreadable → the empty gates array means UNPARSED, not undeclared: say nothing more;
462
+ // readable, no gate → the claim and the advice both hold;
463
+ // readable, has gate → a green matrix proves plenty and the user already declared their own.
464
+ const declarationState =
465
+ existing.unreadable !== null ? 'unreadable' : existing.gates.some((gate) => !isReviewDependentGate(gate, cwd)) ? 'has-gate' : 'no-gate';
466
+ const noVerificationNote =
467
+ scripts.entries.length > 0
468
+ ? null
469
+ : `this offer adds no project-verification gate — nothing here runs your suite, linter or build${
470
+ declarationState === 'no-gate'
471
+ ? `, and none is declared either, so a green matrix would prove only that the kit's own checkers ran; declare your own in ${GATES_REL}`
472
+ : ''
473
+ }`;
474
+ const candidates = [rs.candidate, fc.candidate, withholdCoverage ? null : cc.candidate].filter(Boolean);
415
475
  return {
416
476
  entries: [...scripts.entries, ...candidates],
417
- notes: [...scripts.notes, rs.note, fc.note, cc.note].filter(Boolean),
477
+ notes: [...scripts.notes, noVerificationNote, unreadableNote, rs.note, fc.note, coverageNote].filter(Boolean),
418
478
  };
419
479
  };
420
480
 
@@ -479,6 +539,18 @@ const loadExistingDeclaration = (cwd, deps = {}) => {
479
539
  return { outcome: 'loaded', readme: typeof parsed._README === 'string' ? parsed._README : undefined, gates };
480
540
  };
481
541
 
542
+ // The declaration as the OFFER sees it: read-only and non-fatal. The preview must survive a
543
+ // declaration --apply would refuse (missing, malformed, symlinked) — it just reports what it could
544
+ // not read, so the withhold is never blamed on the wrong cause.
545
+ const declaredGatesBestEffort = (cwd, deps = {}) => {
546
+ try {
547
+ const existing = loadExistingDeclaration(cwd, deps);
548
+ return { gates: existing.outcome === 'loaded' ? existing.gates : [], unreadable: null };
549
+ } catch (err) {
550
+ return { gates: [], unreadable: err?.message ?? String(err) };
551
+ }
552
+ };
553
+
482
554
  const templateReadme = (deps = {}) => {
483
555
  const read = deps.readTemplate ?? readFileSync;
484
556
  try {
@@ -531,6 +603,11 @@ export const applyFill = ({ cwd, onlyIds = [] }, deps = {}) => {
531
603
  gates: [...existingGates, ...selected],
532
604
  };
533
605
  validateDeclaration(merged); // every written declaration passes the runner's validator, always
606
+ // Decision 4 — the coverage invariant is enforced on the declaration that GETS WRITTEN, not on
607
+ // the offer: --only filters, the merge appends, and each of those still reaches a dead pair, a
608
+ // producer landing after an already-last checker, or a second checker under another id.
609
+ const defects = coverageDeclarationDefects(merged.gates, cwd);
610
+ if (defects.length) throw stop(`${defects[0].message} — nothing was written`);
534
611
  const body = `${JSON.stringify(merged, null, 2)}\n`;
535
612
  const { writtenPath } = writeDocsAiFileAtomic(cwd, GATES_REL, body, deps, { stop, noun: 'a gate declaration' });
536
613
  return { outcome: 'written', writtenPath, appended: selected.map((e) => e.id), notes: offer.notes };
@@ -33,7 +33,7 @@
33
33
  import { readFileSync, readdirSync, lstatSync, existsSync } from 'node:fs';
34
34
  import { createHash } from 'node:crypto';
35
35
  import { homedir } from 'node:os';
36
- import { dirname, join, resolve, sep } from 'node:path';
36
+ import { dirname, join, resolve } from 'node:path';
37
37
  import { fileURLToPath, pathToFileURL } from 'node:url';
38
38
  import {
39
39
  preflightVelocityProfile,
@@ -55,6 +55,10 @@ import { surveyFamily, surveyGateHook, surveyAdrLayoutStrict } from './family-re
55
55
  import { probeSandboxMasks, needsMasksApply } from './sandbox-masks.mjs';
56
56
  import { shellQuoteArg } from './review-state.mjs';
57
57
  import { isFinalCapableDeclaration } from './run-gates.mjs';
58
+ import { loadDeclaration, canonicalCheckerGates, coverageProducerPrecedes, isReviewDependentGate, GATES_REL } from './gates-declaration.mjs';
59
+ // The declared-path resolution + segment containment this item's convergence lane shares with the
60
+ // autonomy render's allowWrite degrade — ONE leaf, so the two answers cannot drift.
61
+ import { resolveDeclaredDir, dirCovers, isResolvableDeclaredEntry } from './declared-paths.mjs';
58
62
  import { resolveGitHooksPath } from './commit-guard.mjs';
59
63
  import { loadConfig } from './orchestration-config.mjs';
60
64
  import { DEFAULT_BUNDLE_ROOT } from './bridge-settings-read.mjs';
@@ -100,6 +104,8 @@ export const SEVERITIES = Object.freeze({
100
104
  'sandbox-provision': SEVERITY_OPTIONAL,
101
105
  'review-recipe': SEVERITY_ATTENTION,
102
106
  'gates-declaration': SEVERITY_OPTIONAL,
107
+ 'gates-inert': SEVERITY_ATTENTION,
108
+ 'gates-inert.no-verification': SEVERITY_ATTENTION,
103
109
  'gate-hook': SEVERITY_OPTIONAL,
104
110
  'commit-guard': SEVERITY_OPTIONAL,
105
111
  'read-lane': SEVERITY_OPTIONAL,
@@ -158,6 +164,8 @@ export const WHATS = Object.freeze({
158
164
  'sandbox-provision.installable': 'the OS sandbox is unavailable: {reason} — installable via the doctor (consent tuple {tuple})',
159
165
  'review-recipe': '{degraded}',
160
166
  'gates-declaration': 'no declared gate matrix (docs/ai/gates.json absent or empty) — gates prompt one by one; the apply PREVIEWS its --apply line, writes nothing',
167
+ 'gates-inert': 'the declared coverage checker ({id}) has no producer before it — it certifies nothing this run, or reads a stale lcov',
168
+ 'gates-inert.no-verification': "all {n} declared gate(s) are the kit's own checkers — the matrix runs no project-verification command",
161
169
  'gate-hook': '{n} declared gate(s) prompt per run — the gate-approval hook is not wired',
162
170
  'commit-guard': 'the gate matrix is final-run-capable but no commit-guard arms the pre-commit hook — a commit needs no green receipt yet',
163
171
  'read-lane': 'the gate hook is wired but the read-only compound lane is off — pipes/chains of seeded reads still prompt one by one',
@@ -214,6 +222,7 @@ export const BENEFITS = Object.freeze({
214
222
  'sandbox-provision': `velocity — confined ad-hoc commands stop prompting; ${DUAL_SECURITY_BENEFIT}`,
215
223
  'review-recipe': 'recipe coverage — the review AND execution recipes you configured actually run instead of silently degrading',
216
224
  'gates-declaration': 'velocity — your project’s gates run as ONE declared batch with a PASS/FAIL table',
225
+ 'gates-inert': 'honest gates — the declared matrix verifies your project instead of reporting green over a check that ran nothing',
217
226
  'gate-hook': 'velocity — your own declared gate commands auto-approve byte-exactly (opt-in PreToolUse hook)',
218
227
  'commit-guard': 'integrity — commits require the ONE green --final receipt at the exact staged fingerprint (consented pre-commit arm)',
219
228
  'read-lane': 'velocity — pipes/chains of your seeded read-only commands auto-approve instead of prompting (opt-in, conservatively classified)',
@@ -250,6 +259,10 @@ export const OPT_IN_CAPABILITIES = Object.freeze([
250
259
  { id: 'autonomy-policy', mode: 'set-autonomy', advisorKey: 'autonomy-policy' },
251
260
  { id: 'sandbox-provision', mode: 'autonomy-doctor', advisorKey: 'sandbox-provision' },
252
261
  { id: 'gates-declaration', mode: 'gates', advisorKey: 'gates-declaration' },
262
+ // A DECLARED matrix that verifies nothing is its own capability: the gates-declaration offer
263
+ // converges the moment any gate exists, so it can never observe this state. The advisor key names
264
+ // the state it reports (an inert declaration), the capability names what the user gains.
265
+ { id: 'gates-verification', mode: 'gates', advisorKey: 'gates-inert' },
253
266
  { id: 'gate-hook', mode: 'hook', advisorKey: 'gate-hook' },
254
267
  { id: 'read-lane', mode: 'hook', advisorKey: 'read-lane' },
255
268
  { id: 'commit-guard', mode: 'commit-guard', advisorKey: 'commit-guard' },
@@ -412,6 +425,52 @@ const probeGates = ({ root, deps, add, skip }) => {
412
425
  }
413
426
  };
414
427
 
428
+ // The INERT-DECLARATION item: a gate matrix that is declared, runs green, and verifies nothing.
429
+ // Both causes are read off the DECLARATION through the same predicates the runner and the fill
430
+ // decide with — the checker side through canonicalCheckerGates, the producer side through the
431
+ // closed matchesCoverageProducer — so the advisor can never disagree with what --final accepts.
432
+ //
433
+ // Cause A (a canonical coverage checker with no producer anywhere in the declaration) is checked
434
+ // FIRST and reported alone: its remedy — declaring the producer — also resolves cause B, because a
435
+ // producer gate is not a kit checker. Its apply is HAND-APPLY: the producer must precede the
436
+ // checker, and the fill is append-only (it refuses by name rather than reordering), so the edit is
437
+ // the maintainer's.
438
+ //
439
+ // An ABSENT or EMPTY declaration belongs to the gates-declaration item; a malformed one throws out
440
+ // of the validated reader and becomes this probe's stated skip, never a guess.
441
+ export const probeGatesInert = ({ root, deps, add, skip }) => {
442
+ try {
443
+ const declaration = loadDeclaration(root, deps);
444
+ if (declaration.outcome === 'missing') return;
445
+ const gates = declaration.gates;
446
+ if (gates.length === 0) return;
447
+ const checkers = canonicalCheckerGates(gates, root);
448
+ if (checkers.length > 0) {
449
+ // ORDER decides, through the declaration's own shared predicate: a producer declared AFTER the
450
+ // checker leaves it just as inert as no producer at all (it reads nothing, or stale bytes), and
451
+ // only --final refuses that shape — a plain run reports every gate PASS.
452
+ if (coverageProducerPrecedes(gates, gates.indexOf(checkers[0]))) return; // the pair is live
453
+ const id = truncatedTo(oneLineOf(checkers[0].id), templateBudget(WHATS['gates-inert']));
454
+ add(
455
+ 'gates-inert',
456
+ fillTemplate(WHATS['gates-inert'], { id }),
457
+ `HAND-APPLY: declare or MOVE a suite gate carrying the coverage reporters BEFORE ${id} in ${GATES_REL} (references/modes/gates.md names the exact form), or drop ${id} — the fill is append-only and cannot reorder for you`,
458
+ );
459
+ return;
460
+ }
461
+ if (gates.every((gate) => isReviewDependentGate(gate, root))) {
462
+ add(
463
+ 'gates-inert',
464
+ fillTemplate(WHATS['gates-inert.no-verification'], { n: gates.length }),
465
+ `node ${q(toolPath('gates-init.mjs'))} --cwd ${q(root)}`,
466
+ 'gates-inert.no-verification',
467
+ );
468
+ }
469
+ } catch (err) {
470
+ skip('gates-inert', err);
471
+ }
472
+ };
473
+
415
474
  // The D10 consumer surface: once the declaration is FINAL-capable (the canonical core checks
416
475
  // present, the checker LAST — the run-gates helper is the one home of that rule), offer the
417
476
  // consented commit-guard install — for a MANAGED guardless pre-commit hook AND for an absent one
@@ -792,7 +851,7 @@ const readReadLaneToggle = (root, deps) => {
792
851
  // D3: the risk-marked keys — every key here has a per-item posture note in the mode doc, surfaced
793
852
  // at the consent moment; the static contract test asserts EXACT bidirectional coverage
794
853
  // (risk-marked keys == mode-doc note keys — a dropped note goes red, not silent).
795
- export const RISK_NOTED_KEYS = Object.freeze(['sandbox-lane', 'read-lane', 'worktrees-dir', 'adr-store-migration']);
854
+ export const RISK_NOTED_KEYS = Object.freeze(['sandbox-lane', 'read-lane', 'worktrees-dir', 'adr-store-migration', 'gates-inert']);
796
855
 
797
856
  const probeSandboxLane = ({ root, deps, add, skip }) => {
798
857
  try {
@@ -849,22 +908,6 @@ const probeSandboxLane = ({ root, deps, add, skip }) => {
849
908
  }
850
909
  };
851
910
 
852
- // A declared `sandbox.filesystem.allowWrite` entry, resolved the way a host that honors the key
853
- // resolves it: `~` and `~/…` against the resolved home, every other form against the project root.
854
- const resolveDeclaredDir = (entry, { home, root }) => {
855
- if (entry === '~') return resolve(home);
856
- if (entry.startsWith('~/')) return resolve(home, entry.slice(2));
857
- return resolve(root, entry);
858
- };
859
-
860
- // Ancestor-or-equal containment on PATH SEGMENTS, never a raw string prefix — a grant on
861
- // `<p>/farm` must never read as a grant on the sibling `<p>/farmhouse`. A grant on a DESCENDANT
862
- // never covers its parent: the parent dir is the one provision writes into.
863
- const dirCovers = (declaredDir, probeDir) => {
864
- const base = declaredDir.endsWith(sep) ? declaredDir.slice(0, -sep.length) : declaredDir;
865
- return probeDir === base || probeDir.startsWith(`${base}${sep}`);
866
- };
867
-
868
911
  // D7 lane 1 — the DECLARATION confirmation. A settings entry is not proof of writable CAPABILITY
869
912
  // (runtime truth stays with the provision preflight's real create+delete probe); it is proof the
870
913
  // maintainer applied this item's own advice, which is what the item may converge on. Both scopes
@@ -899,7 +942,7 @@ const declaredWritableDirs = (scope, rel) => {
899
942
  if (filesystem === null || typeof filesystem !== 'object' || Array.isArray(filesystem)) return [];
900
943
  const { allowWrite } = filesystem;
901
944
  if (allowWrite === undefined) return [];
902
- if (!Array.isArray(allowWrite) || !allowWrite.every((entry) => typeof entry === 'string' && entry.trim() !== '')) {
945
+ if (!Array.isArray(allowWrite) || !allowWrite.every(isResolvableDeclaredEntry)) {
903
946
  throw new Error(`${rel}: sandbox.filesystem.allowWrite must be an array of non-empty strings`);
904
947
  }
905
948
  return allowWrite;
@@ -1010,6 +1053,7 @@ const PROBES = Object.freeze([
1010
1053
  probeSandboxProvision,
1011
1054
  probeReviewRecipe,
1012
1055
  probeGates,
1056
+ probeGatesInert,
1013
1057
  probeCommitGuard,
1014
1058
  probeReadLane,
1015
1059
  probeStateBlockHook,
@@ -68,7 +68,13 @@ import {
68
68
  isReviewDependentGate, unknownPregateExcludeIds, derivePregateSubsetGates,
69
69
  } from './gates-declaration.mjs';
70
70
 
71
+ // The coverage vocabulary lives in a LEAF below this runner AND core-evidence (which validates the
72
+ // token this runner records) — run-gates already imports core-evidence, so a shared home is the
73
+ // only direction that has no cycle. Re-exported here: this module is the vocabulary's public face.
74
+ import { COVERAGE } from './coverage-state.mjs';
75
+
71
76
  export { GATES_REL, loadDeclaration, validateDeclaration, canonicalCheckerGates, isFinalCapableDeclaration, isReviewDependentGate };
77
+ export { COVERAGE };
72
78
 
73
79
  // The full exit-code table — one distinct code per honest outcome (never a silent green).
74
80
  // 7 is RETIRED (the deleted --record arm's outcome) — never reused for a new meaning.
@@ -117,12 +123,18 @@ const USAGE = [
117
123
  'deletes the stale git-dir lcov first, exports AW_GIT_DIR to every gate cmd, records EVERY',
118
124
  'attempt (start + completed green/red) in the core-evidence store, and binds the receipt to',
119
125
  '{ fingerprint before/after, the full declaration, per-gate results, the canonical red-proof +',
120
- 'degrade evidence hashes, the lcov sha, and — when a flow store exists — evidenceHashes.flow,',
121
- 'the owner-scoped flow projection hash (D10; projection movement under the run is a red',
122
- 'integrityFailure) }. --final refuses --only (a subset never attests).',
126
+ 'degrade evidence hashes, the lcov sha, the run\'s own coverage token, and — when a flow store',
127
+ 'exists — evidenceHashes.flow, the owner-scoped flow projection hash (D10; projection movement',
128
+ 'under the run is a red integrityFailure) }. --final refuses --only (a subset never attests).',
123
129
  '',
124
130
  `Runs the gates declared in <cwd>/${GATES_REL} (one bash command line each, project root as cwd).`,
125
131
  'Prints a per-gate PASS/FAIL table + one machine-readable summary line; exit 0 iff all green.',
132
+ `The summary line carries coverage=<${COVERAGE.certified}|${COVERAGE.notRun}|${COVERAGE.none}|${COVERAGE.unknown}> — whether a coverage`,
133
+ 'VERDICT rode this run: certified (one was issued, pass OR fail), not-run (the checker issued',
134
+ 'none — no lcov, or this run does not own it), none (no canonical checker ran here), unknown (the',
135
+ 'run ended before the gates produced a signal, or the signal is unreadable). The checker\'s own',
136
+ 'table row names a withheld verdict in the same words. DETAIL only: the exit code and the status=',
137
+ 'token are untouched by it.',
126
138
  '',
127
139
  'Producer env: AW_GIT_DIR (inside a git tree) and AW_LCOV_FILE (--final only) are computed and',
128
140
  'exported to every gate child, and STRIPPED from the inherited environment first — a host-set',
@@ -238,23 +250,82 @@ export const runGates = (gates, { cwd, spawn = spawnGateViaBash, now = Date.now,
238
250
  };
239
251
 
240
252
  // The per-gate PASS/FAIL table (printed after every gate ran — failures never stop the matrix).
241
- export const formatTable = (results) => {
253
+ // `notes` annotates rows by gate id: the coverage signal names a WITHHELD verdict on the checker's
254
+ // own row, so a PASS there can never read as a claim the checker did not make. A Map, not an
255
+ // object — a gate id is any kebab word, `constructor` included, and a plain object would answer
256
+ // that lookup from its prototype.
257
+ export const formatTable = (results, notes = new Map()) => {
242
258
  const idWidth = Math.max(...results.map((result) => result.id.length), 'gate'.length);
243
259
  const pad = (text) => text + ' '.repeat(idWidth - text.length);
244
260
  const lines = ['', `${pad('gate')} result`];
245
261
  for (const result of results) {
246
- lines.push(`${pad(result.id)} ${result.ok ? 'PASS' : `FAIL (exit ${result.code})`}`);
262
+ const note = notes.get(result.id);
263
+ lines.push(`${pad(result.id)} ${result.ok ? 'PASS' : `FAIL (exit ${result.code})`}${note ? ` ${note}` : ''}`);
247
264
  }
248
265
  return lines;
249
266
  };
250
267
 
268
+ // ── the coverage signal this run carries (Decision 8) ─────────────────────────────────
269
+ // The checker's two fully anchored machine lines. Exactly ONE of each rides a run: the --final
270
+ // receipt binds them (an injected or duplicated line must never shadow the real one), and the
271
+ // summary field below is derived from the SAME bytes, so the two can never disagree.
272
+ const LCOV_SHA_LINE_RE = /^coverage-check: lcov-sha256=([0-9a-f]{64}|none)$/;
273
+ const ATTESTED_LINE_RE = /^coverage-check: attested=(yes|no)$/;
274
+ const anchoredMachineLines = (stdout, re) => String(stdout ?? '').split(/\r?\n/).filter((line) => re.test(line));
275
+ const exactlyOneMachineValue = (stdout, re) => {
276
+ const lines = anchoredMachineLines(stdout, re);
277
+ return lines.length === 1 ? re.exec(lines[0])[1] : null;
278
+ };
279
+
280
+ // Which SELECTED gate is the canonical checker — resolved BEFORE anything spawns, because the
281
+ // answer is a property of the DECLARATION, not of the post-run filesystem. The predicate reads the
282
+ // tool path through realpath, so a gate that deletes or redirects it mid-run would otherwise turn
283
+ // the checker this run selected into "no checker at all" (`none`) — and a --final receipt refuses
284
+ // that state, which would lose the whole attempt's evidence rather than record it honestly.
285
+ export const resolveCheckerIndex = (selected, projectDir) =>
286
+ selected.findIndex((gate) => matchesCanonicalCheck(FINAL_CORE_CHECKS[1], gate.cmd, projectDir));
287
+
288
+ // coverageSignal(checkerAt, results) → { state, note, checkerRow } — what THIS run can honestly say
289
+ // about coverage, decided by the checker's own OUTPUT rather than by its exit status (it exits 0
290
+ // both when it certifies and when it withholds). BOTH anchored lines are read and CROSS-CHECKED:
291
+ // neither alone is trustworthy — a missing or duplicated line is unreadable, and an attestation
292
+ // over bytes that were never consumed is a contradiction. `note` is the checker row's table
293
+ // annotation, null when there is nothing to name.
294
+ export const coverageSignal = (checkerAt, results) => {
295
+ if (checkerAt === -1) return { state: COVERAGE.none, note: null, checkerRow: null };
296
+ const checkerRow = results[checkerAt] ?? null;
297
+ if (checkerRow === null || checkerRow.code === SPAWN_FAILED_CODE) {
298
+ return { state: COVERAGE.unknown, note: null, checkerRow };
299
+ }
300
+ const unreadable = (why) => ({ state: COVERAGE.unknown, note: `coverage=${COVERAGE.unknown} (${why})`, checkerRow });
301
+ const attested = exactlyOneMachineValue(checkerRow.stdout, ATTESTED_LINE_RE);
302
+ const consumed = exactlyOneMachineValue(checkerRow.stdout, LCOV_SHA_LINE_RE);
303
+ if (attested === null || consumed === null) {
304
+ return unreadable('the checker printed no single anchored attested= / lcov-sha256 pair — whether coverage was certified is unknowable');
305
+ }
306
+ if (attested === 'yes') {
307
+ return consumed === 'none'
308
+ ? unreadable('the checker attested over an lcov it never read — a contradictory pair, fail closed')
309
+ : { state: COVERAGE.certified, note: null, checkerRow };
310
+ }
311
+ return {
312
+ state: COVERAGE.notRun,
313
+ note: consumed === 'none'
314
+ ? `coverage=${COVERAGE.notRun} (no lcov bytes were read; no coverage verdict was issued)`
315
+ : `coverage=${COVERAGE.notRun} (an lcov was read but no verdict was issued)`,
316
+ checkerRow,
317
+ };
318
+ };
319
+
251
320
  // The ONE machine-readable summary line — always the LAST line printed for every non-usage
252
- // outcome. Schema (pinned by tests): status ∈ ok|fail|missing|empty|malformed|no-bash.
253
- export const composeSummaryLine = ({ status, results = [] }) => {
321
+ // outcome. Schema (pinned by tests): status ∈ ok|fail|missing|empty|malformed|no-bash, plus
322
+ // coverage the COVERAGE vocabulary. The coverage DEFAULT is `unknown`: a lane that ended before
323
+ // the gates could produce a signal says exactly that, never a claim it cannot support.
324
+ export const composeSummaryLine = ({ status, results = [], coverage = COVERAGE.unknown }) => {
254
325
  const passed = results.filter((result) => result.ok).length;
255
326
  const failed = results.filter((result) => !result.ok);
256
327
  const failedIds = failed.length > 0 ? failed.map((result) => result.id).join(',') : NO_FAILED_IDS;
257
- return `[run-gates] status=${status} gates=${results.length} passed=${passed} failed=${failed.length} failed_ids=${failedIds}`;
328
+ return `[run-gates] status=${status} gates=${results.length} passed=${passed} failed=${failed.length} failed_ids=${failedIds} coverage=${coverage}`;
258
329
  };
259
330
 
260
331
  // ── CLI ───────────────────────────────────────────────────────────────────────────────
@@ -655,8 +726,15 @@ export const runCli = (argv, deps = {}) => {
655
726
  return EXIT.finalFailed;
656
727
  }
657
728
  }
729
+ // The checker's position is pinned BEFORE the matrix spawns; the tree it leaves behind never
730
+ // gets to re-decide which gate this run selected.
731
+ const checkerAt = resolveCheckerIndex(selected, projectDir);
658
732
  const results = runGates(selected, { cwd: projectDir, spawn: gateSpawn, log, now });
659
- for (const line of formatTable(results)) log(line);
733
+ // Decided once, from the checker's own machine lines, and carried to BOTH surfaces of this run:
734
+ // the checker's table row and the machine summary field (Decision 7/8).
735
+ const coverage = coverageSignal(checkerAt, results);
736
+ const coverageNotes = coverage.note && coverage.checkerRow ? new Map([[coverage.checkerRow.id, coverage.note]]) : new Map();
737
+ for (const line of formatTable(results, coverageNotes)) log(line);
660
738
  const allGreen = results.every((result) => result.ok);
661
739
  if (opts.preReview) {
662
740
  // The named diagnosis (#66): review-dependence is derived, so an abstracted checker can only
@@ -675,7 +753,7 @@ export const runCli = (argv, deps = {}) => {
675
753
  && endRead.records.some((r) => r.kind === CHAIN_KIND && r.purpose === 'adoption');
676
754
  if (armedNow) {
677
755
  logError('[run-gates] --pre-review: the flow was ARMED while this run executed — the run started unarmed, so its result is NOT recorded (round-11 fold); re-run under the armed flow');
678
- log(composeSummaryLine({ status: 'fail', results }));
756
+ log(composeSummaryLine({ status: 'fail', results, coverage: coverage.state }));
679
757
  return EXIT.fail;
680
758
  }
681
759
  }
@@ -686,7 +764,7 @@ export const runCli = (argv, deps = {}) => {
686
764
  if (results.some((result) => result.code === SPAWN_FAILED_CODE)) {
687
765
  logError('[run-gates] --pre-review: a gate could not SPAWN — an infrastructure failure is not a gate red, so NO subset-attempt was recorded; fix the spawn failure and re-run');
688
766
  releaseSubsetRunLock();
689
- log(composeSummaryLine({ status: 'fail', results }));
767
+ log(composeSummaryLine({ status: 'fail', results, coverage: coverage.state }));
690
768
  return EXIT.fail;
691
769
  }
692
770
  const attemptStatus = allGreen ? 'green' : 'red';
@@ -711,23 +789,18 @@ export const runCli = (argv, deps = {}) => {
711
789
  logError(`[run-gates] --pre-review: the subset attempt could not be recorded — ${err.message}`);
712
790
  logError("[run-gates] an armed flow's subset run IS a recorded attempt; an unrecordable run refuses (fail closed)");
713
791
  releaseSubsetRunLock();
714
- log(composeSummaryLine({ status: 'fail', results }));
792
+ log(composeSummaryLine({ status: 'fail', results, coverage: coverage.state }));
715
793
  return EXIT.fail;
716
794
  }
717
795
  }
718
796
  }
719
- // A green gate's stdout is deliberately not echoed — the table IS the report. But the checker
720
- // exits 0 both when it certifies and when it WITHHOLDS a verdict, so on a plain run the table
721
- // would read PASS over a coverage claim that was never made: the same false reassurance one
722
- // layer up from the defect this whole mechanism exists to close. Surface it, and only it.
723
- if (!opts.final) {
724
- const checkerAt = selected.findIndex((gate) => matchesCanonicalCheck(FINAL_CORE_CHECKS[1], gate.cmd, projectDir));
725
- const checkerRow = checkerAt === -1 ? null : results[checkerAt];
726
- if (checkerRow?.ok && /^coverage-check: attested=no$/m.test(String(checkerRow.stdout ?? ''))) {
727
- log(`── ${checkerRow.id} — NO COVERAGE VERDICT (the gate passed; it did not certify)`);
728
- for (const line of String(checkerRow.stdout).split(/\r?\n/).filter((l) => /^coverage-check: (NO VERDICT|skipped-no-lcov)/.test(l))) log(line);
729
- log(' A coverage verdict is issued only by run-gates.mjs --final, which owns the lcov for the whole run.');
730
- }
797
+ // A green gate's stdout is deliberately not echoed — the table IS the report. The row above
798
+ // now names the withheld verdict; this block adds the checker's OWN words and the remedy, so a
799
+ // plain run never leaves a PASS standing for a coverage claim that was never made. Only that.
800
+ if (!opts.final && coverage.state === COVERAGE.notRun && coverage.checkerRow?.ok) {
801
+ log(`── ${coverage.checkerRow.id} — NO COVERAGE VERDICT (the gate passed; it did not certify)`);
802
+ for (const line of String(coverage.checkerRow.stdout).split(/\r?\n/).filter((l) => /^coverage-check: (NO VERDICT|skipped-no-lcov)/.test(l))) log(line);
803
+ log(' A coverage verdict is issued only by run-gates.mjs --final, which owns the lcov for the whole run.');
731
804
  }
732
805
  if (opts.final) {
733
806
  // The checker's verbatim diagnostics surface even on green — skipped-no-lcov and the
@@ -770,17 +843,15 @@ export const runCli = (argv, deps = {}) => {
770
843
  }
771
844
  // Exactly ONE full machine line binds the receipt — an unanchored first-match would let
772
845
  // an injected/duplicated line shadow the real one and skip the end re-hash.
773
- const shaLineRe = /^coverage-check: lcov-sha256=([0-9a-f]{64}|none)$/;
774
- const shaLines = String(checkerRow?.stdout ?? '').split(/\r?\n/).filter((l) => shaLineRe.test(l));
775
- const shaValue = shaLines.length === 1 ? shaLineRe.exec(shaLines[0])[1] : null;
846
+ const shaLines = anchoredMachineLines(checkerRow?.stdout, LCOV_SHA_LINE_RE);
847
+ const shaValue = shaLines.length === 1 ? LCOV_SHA_LINE_RE.exec(shaLines[0])[1] : null;
776
848
  const lcovSha256 = shaValue !== null && shaValue !== 'none' ? shaValue : null;
777
849
  // The attestation line, on the SAME exactly-one-anchored-line contract as the sha: a green
778
850
  // exit status alone never proves the checker certified anything — it exits 0 both when it
779
851
  // attests and when it withholds a verdict. Without this arm a gate that removed the start
780
852
  // record mid-run would yield a green receipt carrying no coverage claim at all.
781
- const attestLineRe = /^coverage-check: attested=(yes|no)$/;
782
- const attestLines = String(checkerRow?.stdout ?? '').split(/\r?\n/).filter((l) => attestLineRe.test(l));
783
- const attested = attestLines.length === 1 ? attestLineRe.exec(attestLines[0])[1] : null;
853
+ const attestLines = anchoredMachineLines(checkerRow?.stdout, ATTESTED_LINE_RE);
854
+ const attested = attestLines.length === 1 ? ATTESTED_LINE_RE.exec(attestLines[0])[1] : null;
784
855
  if (allGreen && integrityFailure === null && lcovSha256 !== null) {
785
856
  if (attestLines.length !== 1) {
786
857
  integrityFailure = attestLines.length === 0
@@ -826,6 +897,11 @@ export const runCli = (argv, deps = {}) => {
826
897
  ...(finalFlow?.present ? { flow: finalFlow.hash } : {}),
827
898
  },
828
899
  lcovSha256,
900
+ // The run's OWN coverage token, recorded rather than re-derived: `lcovSha256` says what
901
+ // the receipt binds, never whether a verdict was issued (a red run can bind a digest
902
+ // over an uncertified read, and a null digest is also what an unreadable sha line
903
+ // leaves). The stateless render reads this field instead of guessing from the digest.
904
+ coverage: coverage.state,
829
905
  integrityFailure,
830
906
  timestamp: new Date().toISOString(),
831
907
  },
@@ -848,14 +924,17 @@ export const runCli = (argv, deps = {}) => {
848
924
  // would be a silent green in the one place a reader parses instead of reads. The run lock
849
925
  // releases BEFORE the line composes so a custody violation can never hide behind status=ok.
850
926
  const runLockIssue = releaseSubsetRunLock();
851
- log(composeSummaryLine({ status: allGreen && finalError === null && runLockIssue == null ? 'ok' : 'fail', results }));
927
+ log(composeSummaryLine({ status: allGreen && finalError === null && runLockIssue == null ? 'ok' : 'fail', results, coverage: coverage.state }));
852
928
  if (finalError) return EXIT.finalFailed;
853
929
  if (runLockIssue != null) return EXIT.fail;
854
930
  return allGreen ? EXIT.ok : EXIT.fail;
855
931
  } catch (err) {
856
932
  releaseSubsetRunLock();
857
933
  logError(`[run-gates] ${err.message}`);
858
- if (err.exitCode === EXIT.malformed) log(composeSummaryLine({ status: 'malformed' }));
934
+ // The machine line is the LAST line for every NON-USAGE outcome — a thrown refusal is one, and
935
+ // the gates never produced a signal there, so it carries coverage=unknown. Usage is the single
936
+ // documented exception: it prints the usage text and no summary at all.
937
+ if (err.exitCode !== EXIT.usage) log(composeSummaryLine({ status: err.exitCode === EXIT.malformed ? 'malformed' : 'fail' }));
859
938
  return err.exitCode ?? EXIT.fail;
860
939
  }
861
940
  };