@sabaiway/agent-workflow-kit 23.4.1 → 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.
@@ -0,0 +1,123 @@
1
+ // verdict-block: the red block composer (spec verdict-block).
2
+ const LINE_BREAK = /[\r\n]/;
3
+ const LINE_SEPARATOR = /\r\n|[\r\n]/;
4
+ const KEBAB_WORD = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
5
+ const LINE_NUMBER = /^[1-9][0-9]*$/;
6
+ const FINDING_SEPARATOR = ': ';
7
+ const DETAIL_PREFIX = ' ';
8
+ const VERDICT_WORD = 'FAIL';
9
+ const REMEDY_WORD = 'REMEDY';
10
+ const NO_MESSAGE = 'no message';
11
+ const MIN_EXIT_CODE = 1;
12
+ const MAX_EXIT_CODE = 255;
13
+ const NOT_FOUND = -1;
14
+
15
+ const refuseField = (field) => { throw new TypeError(`Invalid ${field}`); };
16
+
17
+ const validateName = (name) => {
18
+ if (typeof name !== 'string' || KEBAB_WORD.exec(name)?.[0] !== name) refuseField('name');
19
+ };
20
+
21
+ const validateLine = (line, field, allowEmpty = false, allowIndent = false) => {
22
+ if (typeof line !== 'string' || LINE_BREAK.test(line)
23
+ || (!allowEmpty && !line.length) || (!allowIndent && line.startsWith(' '))) refuseField(field);
24
+ return line;
25
+ };
26
+
27
+ const validateList = (list, field) => {
28
+ if (!Array.isArray(list)) refuseField(field);
29
+ return Array.from(list);
30
+ };
31
+
32
+ const formatNamedLine = (name, word, text) => `${name}: ${word} — ${text}`;
33
+
34
+ const judgeNamedLine = (line, name, word) => {
35
+ const prefix = formatNamedLine(name, word, '');
36
+ return line.startsWith(prefix) && line.length > prefix.length && line[prefix.length] !== ' ';
37
+ };
38
+
39
+ const validatePlace = (place) => {
40
+ validateLine(place, 'place');
41
+ const colonIndex = place.lastIndexOf(':');
42
+ const path = colonIndex === NOT_FOUND ? place : place.slice(0, colonIndex);
43
+ const lineNumber = place.slice(colonIndex + 1);
44
+ if (!path.length || path.includes('\\') || path.startsWith('./') || path.split('/').includes('..')
45
+ || (colonIndex !== NOT_FOUND && LINE_NUMBER.exec(lineNumber)?.[0] !== lineNumber)) refuseField('place');
46
+ };
47
+
48
+ const composeFinding = (finding, name) => {
49
+ if (finding === null || typeof finding !== 'object') refuseField('findings');
50
+ validatePlace(finding.place);
51
+ validateLine(finding.text, 'text');
52
+ const line = `${finding.place}${FINDING_SEPARATOR}${finding.text}`;
53
+ if ([VERDICT_WORD, REMEDY_WORD].some((word) => judgeNamedLine(line, name, word))) refuseField('findings');
54
+ const detail = validateList(finding.detail === undefined ? [] : finding.detail, 'detail');
55
+ return [line, ...detail.map((text) => `${DETAIL_PREFIX}${validateLine(text, 'detail', false, true)}`)];
56
+ };
57
+
58
+ const validateLateLine = (line, places, field) => {
59
+ if (places.some((place) => line.startsWith(`${place}${FINDING_SEPARATOR}`))) refuseField(field);
60
+ return line;
61
+ };
62
+
63
+ export const composeRedBlock = ({ name, failed, findings = [], remedies, after = [] }) => {
64
+ validateName(name);
65
+ validateLine(failed, 'failed');
66
+ const findingList = validateList(findings, 'findings');
67
+ const findingLines = findingList.flatMap((finding) => composeFinding(finding, name));
68
+ const places = findingList.map((finding) => finding.place);
69
+ const remedyList = validateList(remedies, 'remedies');
70
+ if (!remedyList.length) refuseField('remedies');
71
+ const remedyLines = remedyList.map((remedy, index) => {
72
+ const line = formatNamedLine(name, REMEDY_WORD, validateLine(remedy, 'remedies'));
73
+ return index === 0 ? line : validateLateLine(line, places, 'remedies');
74
+ });
75
+ const afterLines = validateList(after, 'after').map((line) =>
76
+ validateLateLine(validateLine(line, 'after', true, true), places, 'after'));
77
+ return Object.freeze([formatNamedLine(name, VERDICT_WORD, failed), ...findingLines, ...remedyLines, ...afterLines]);
78
+ };
79
+
80
+ export const composeUsageRefusal = ({ name, failed, usage }) => {
81
+ validateName(name);
82
+ validateLine(failed, 'failed');
83
+ if (typeof usage !== 'string' || !usage.length) refuseField('usage');
84
+ return Object.freeze([formatNamedLine(name, VERDICT_WORD, failed), ...usage.split(LINE_SEPARATOR)]);
85
+ };
86
+
87
+ const readFirstLine = (value) => String(value).split(LINE_SEPARATOR)[0];
88
+
89
+ const readErrorLine = (error) => {
90
+ try {
91
+ return (error instanceof Error
92
+ ? readFirstLine(error.message) || readFirstLine(error.name)
93
+ : readFirstLine(error)) || NO_MESSAGE;
94
+ } catch {
95
+ return NO_MESSAGE;
96
+ }
97
+ };
98
+
99
+ const composeErrorAnswer = ({ name, exitCode, remedy }, error) => {
100
+ const stack = error instanceof Error && typeof error.stack === 'string' && error.stack.length
101
+ ? error.stack.split(LINE_SEPARATOR) : [];
102
+ return {
103
+ exitCode,
104
+ lines: Object.freeze([
105
+ formatNamedLine(name, VERDICT_WORD, `unexpected error: ${readErrorLine(error)}`),
106
+ formatNamedLine(name, REMEDY_WORD, remedy),
107
+ ...stack,
108
+ ]),
109
+ };
110
+ };
111
+
112
+ export const guardChecker = ({ name, exitCode, remedy }, run) => {
113
+ validateName(name);
114
+ validateLine(remedy, 'remedy');
115
+ if (!Number.isInteger(exitCode) || exitCode < MIN_EXIT_CODE || exitCode > MAX_EXIT_CODE) refuseField('exitCode');
116
+ const answerError = (error) => composeErrorAnswer({ name, exitCode, remedy }, error);
117
+ try {
118
+ const answer = run();
119
+ return answer instanceof Promise ? answer.catch(answerError) : answer;
120
+ } catch (error) {
121
+ return answerError(error);
122
+ }
123
+ };
@@ -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';