@sabaiway/agent-workflow-kit 23.5.0 → 23.7.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,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
@@ -0,0 +1,55 @@
1
+ export const helpText = ({ SOURCE_SIZE_CONFIG_REL, SOURCE_SIZE_SCHEMA, KIT_FOLDER_ROOT }) => `source-size-check — the declared source-size practice (agent-workflow family).
2
+
3
+ Usage:
4
+ node source-size-check.mjs --check [--cwd <project-root>]
5
+ node source-size-check.mjs --write-baseline [--layout] [--reason "<text>"] [--cwd <project-root>]
6
+ node source-size-check.mjs --adopt [--reason "<text>"] [--cwd <project-root>]
7
+ node source-size-check.mjs --override <id> [--value <n>] [--tolerance <p>] --reason "<text>" [--cwd <project-root>]
8
+ node source-size-check.mjs --override <id> --kit-default --reason "<text>" [--cwd <project-root>]
9
+
10
+ Judges every in-scope file against ${SOURCE_SIZE_CONFIG_REL} (schema ${SOURCE_SIZE_SCHEMA}): git-tracked files
11
+ under a declared root carrying a declared extension, minus the excluded path-segment prefixes and
12
+ the kit's own folder ${KIT_FOLDER_ROOT}, which nothing here judges and no root may declare. An
13
+ absent "roots" is the one root ".", every tracked path; a config declaring no extension judges no
14
+ file, and every check says so. With the config absent the check judges layout alone under the
15
+ kit's values. Symlinks and submodule gitlinks are skipped by kind; an unmerged index, a non-UTF-8
16
+ in-scope path, an unverifiable in-scope file and an empty declared scope are refusals.
17
+
18
+ Limits: the kit's own five, kept in its code, each with a tolerance; the config holds only a
19
+ project's reasoned overrides under "limits". A value at or under its limit is clean, above it within
20
+ the band ceil(value x tolerance / 100) a WARNING printed on every run (exit 0), and beyond the band a
21
+ stop unless a record holds it. Every --check, --write-baseline and --override run that resolves the
22
+ config and ends in no usage, config, enumeration or scope error states all five limits with value,
23
+ tolerance and source, then what it does not judge, then its warnings, then its stops; a --check that
24
+ stops opens instead with its verdict line, its findings and its remedy, its limits, notes and warnings
25
+ after them.
26
+
27
+ Counting: lines, and the longest line in BYTES. A terminator never counts (the CR of a CRLF
28
+ included); a last line with no final newline still counts; an empty file is 0 lines. Layout: the
29
+ entries of each directory and its depth below its root, over every tracked entry under a declared
30
+ root outside the kit's own folder ${KIT_FOLDER_ROOT} plus the spec store docs/ai/specs walked from
31
+ disk, and the files of each declared root.
32
+
33
+ A recorded entry is DEBT: a finding stops exactly when the regeneration would raise it, and a record
34
+ above the tree or gone warns until the regeneration lowers or removes it. Each declared root carries
35
+ the same exact ratchet over its summed lines.
36
+
37
+ --write-baseline regenerates the machine keys (baseline, aggregate, and layout where it is judged)
38
+ from the tree; on an absent config it writes a schema-2 one. --layout starts the layout record on a
39
+ present config that has none. The authored keys keep their values and their order; the file is
40
+ canonically serialized. A regeneration that RAISES any recorded value needs --reason; the string is
41
+ recorded in the entry it raised. A pure tighten needs none. A schema-1 config is moved to schema 2 in
42
+ the same write; --check stops on one until it is.
43
+
44
+ --adopt is the ONE-line adoption: it mints the record and declares the source-size gate (and NOTHING
45
+ else) in docs/ai/gates.json. It is idempotent on an already-adopted project. With the config absent
46
+ it refuses with the exact file to author. A refused declaration exits nonzero and reports both
47
+ halves: what was minted and what was not declared.
48
+
49
+ --override writes one override of a kit limit (lines-per-file, bytes-per-line, entries-per-directory,
50
+ depth: --value and/or --tolerance; files-per-root: --tolerance only), or with --kit-default removes
51
+ it; an option left out keeps the limit's current value or tolerance, and --reason is mandatory. It
52
+ runs only once regenerating the record under the current limits would raise nothing, and
53
+ regenerates the record in the same write.
54
+
55
+ Exit codes: 0 green, warnings included; 1 a stop or a refusal; 2 usage, config or enumeration error, or an unexpected error.`;
@@ -47,3 +47,7 @@ export {
47
47
  queueChecksOf,
48
48
  spliceLater,
49
49
  } from './piles.mjs';
50
+
51
+ export {
52
+ helpText,
53
+ } from './help.mjs';
@@ -29,10 +29,11 @@
29
29
  // removes one reasoned override of a kit limit and regenerates the machine keys under the new limits
30
30
  // in the same write. Every write here moves a schema-1 config to schema 2; --check stops on one.
31
31
  //
32
- // Exit codes: 0 green / 1 violation or refusal / 2 usage, config or enumeration error.
32
+ // Exit codes: 0 green / 1 violation or refusal / 2 usage, config or enumeration error, or an unexpected error.
33
33
  // Dependency-free, Node >= 22. No side effects on import.
34
34
 
35
35
  import { resolve } from 'node:path';
36
+ import { composeRedBlock, composeUsageRefusal, guardChecker } from '../references/scripts/shared/index.mjs';
36
37
  import { assertDocsAiDeployment, writeDocsAiFileAtomic } from './atomic-write.mjs';
37
38
  import { isDirectRun, sameFile } from './direct-run.mjs';
38
39
  import {
@@ -42,7 +43,7 @@ import {
42
43
  SOURCE_SIZE_SCHEMA,
43
44
  applyOverride,
44
45
  assertNoStoreRoot,
45
- checkTargetOf,
46
+ checkTargetOf, escapeForLine,
46
47
  isRaise,
47
48
  loadSourceSizeConfig,
48
49
  matchesSourceSizeGate,
@@ -63,7 +64,7 @@ import {
63
64
  TEMPLATE_READMES,
64
65
  absentRefusalLines,
65
66
  adoptAbsentRefusalLines,
66
- checkReportLines,
67
+ checkReportLines, checkStopBlock, escapeLeadingSpace,
67
68
  gateAlreadyDeclaredLines,
68
69
  gateDeclaredLines,
69
70
  gateRefusedLines,
@@ -74,15 +75,18 @@ import {
74
75
  reasonRequiredLines,
75
76
  recordNoLongerHoldsLines,
76
77
  recordRecognizedLines,
77
- schema1MovedLines,
78
- schema1StopLines,
79
- statedLimitLines,
80
- unmintedRefusalLines,
78
+ schema1MovedLines, schema1StopBlock,
79
+ statedLimitLines, unmintedRefusalLines, unmintedStopBlock,
81
80
  warningLines,
82
81
  writtenLines,
83
82
  } from './source-size-report.mjs';
84
83
 
85
- const usageFail = (message) => Object.assign(new Error(`[agent-workflow-kit] ${message}`), { exitCode: 2 });
84
+ const ERROR_PREFIX = '[agent-workflow-kit] ';
85
+ const CHECKER_NAME = 'source-size';
86
+ const USAGE_REFUSAL = Symbol('usage refusal');
87
+ const HELP_LINES = HELP.split('\n');
88
+ const USAGE = HELP_LINES.slice(HELP_LINES.indexOf('Usage:')).slice(0, 6).join('\n');
89
+ const usageFail = (message) => Object.assign(new Error(`${ERROR_PREFIX}${message}`), { exitCode: 2, [USAGE_REFUSAL]: true });
86
90
  const RECORD_NOUN = 'the source-size record';
87
91
  const LAYOUT_GROWTH_LEAD = 'source-size: --layout REFUSED — it starts the layout record and raises nothing else, but the record no longer holds for this tree, so that growth takes --write-baseline --reason first; nothing was written.';
88
92
 
@@ -94,10 +98,12 @@ const ABSENT = Object.freeze({ _README: TEMPLATE_README, schema: SOURCE_SIZE_SCH
94
98
  export const runCheck = ({ cwd, deps = {} }) => {
95
99
  const target = checkTargetOf({ loaded: loadSourceSizeConfig(cwd, deps), absentConfig: validateSourceSizeConfig(ABSENT) });
96
100
  const { config, judged } = target;
97
- if (target.stop === 'schema-1') return { code: 1, lines: schema1StopLines(cwd), config };
98
- if (target.stop === 'unminted') return { code: 1, lines: unmintedRefusalLines(cwd, { state: target.state, missing: target.missing }), config };
101
+ if (target.stop === 'schema-1') return { code: 1, block: schema1StopBlock(cwd), config };
102
+ if (target.stop === 'unminted') return { code: 1, block: unmintedStopBlock(cwd, { state: target.state, missing: target.missing }), config };
99
103
  const verdict = judgeTree(cwd, config, deps, judged);
100
- return { code: stopsOf(verdict.findings).length === 0 ? 0 : 1, lines: checkReportLines({ cwd, config, verdict, absent: judged.absent }), config, judged };
104
+ const report = { cwd, config, verdict, absent: judged.absent };
105
+ return stopsOf(verdict.findings).length > 0 ? { code: 1, block: checkStopBlock(report), config, judged }
106
+ : { code: 0, lines: checkReportLines(report), config, judged };
101
107
  };
102
108
 
103
109
  // ── the writer ────────────────────────────────────────────────────────────────────────────────────
@@ -233,7 +239,7 @@ const gateIsDeclared = (cwd, deps) => {
233
239
  // certain to red the matrix is what the offer rules refuse everywhere else.
234
240
  const recognizeRecord = ({ cwd, deps }) => {
235
241
  const verdict = runCheck({ cwd, deps });
236
- if (verdict.code !== 0) return { code: verdict.code, lines: [...verdict.lines, ...recordNoLongerHoldsLines(GATES_REL)] };
242
+ if (verdict.code !== 0) return { code: verdict.code, lines: [...composeRedBlock({ name: CHECKER_NAME, ...verdict.block }), ...recordNoLongerHoldsLines(GATES_REL)] };
237
243
  return { code: 0, lines: recordRecognizedLines(cwd) };
238
244
  };
239
245
 
@@ -357,22 +363,37 @@ export const main = (argv, ctx = {}) => {
357
363
  ? overrideOptions({ id: idOption.value, value: valueOption.value, tolerance: toleranceOption.value, kitDefault })
358
364
  : {};
359
365
  const deps = ctx.deps ?? {};
360
- const { code, lines, config, judged } = RUNS[mode]({ cwd, reason: reasonOption.value, layout, deps, ...override });
366
+ const { code, lines, block, config, judged } = RUNS[mode]({ cwd, reason: reasonOption.value, layout, deps, ...override });
361
367
  const states = STATES_LIMITS.includes(mode) && config;
362
368
  const limits = states ? statedLimitLines(config) : [];
363
369
  const notJudged = states && judged ? notJudgedLines(cwd, { ...judged, config }) : [];
364
- return { code, stdout: [...limits, ...notJudged, ...lines].join('\n'), stderr: '' };
370
+ const output = block ? composeRedBlock({ name: CHECKER_NAME, ...block, after: [...limits, ...notJudged, ...block.after] }) : [...limits, ...notJudged, ...lines];
371
+ return { code, stdout: output.join('\n'), stderr: '' };
365
372
  } catch (err) {
366
- return { code: err.exitCode ?? 1, stdout: (err.lines ?? []).join('\n'), stderr: `source-size-check: ${err.message}` };
373
+ if (err?.exitCode === undefined) throw err;
374
+ const message = err.message.startsWith(ERROR_PREFIX) ? err.message.slice(ERROR_PREFIX.length) : err.message;
375
+ const failed = escapeLeadingSpace(err[USAGE_REFUSAL] ? escapeForLine(message) : message);
376
+ const output = err[USAGE_REFUSAL] ? composeUsageRefusal({ name: CHECKER_NAME, failed, usage: USAGE })
377
+ : composeRedBlock({ name: CHECKER_NAME, failed, remedies: [err.exitCode === 2 ? 'fix the size config or the git index error the verdict line names, then re-run' : 'fix the tree condition the verdict line names, then re-run'], after: err.lines ?? [] });
378
+ return { code: err.exitCode, stdout: output.join('\n'), stderr: '' };
367
379
  }
368
380
  };
369
381
 
382
+ export const guardedMain = (argv, ctx = {}) => {
383
+ const carried = [];
384
+ const result = guardChecker({ name: CHECKER_NAME, exitCode: 2, remedy: 'fix the cause the stack below names, then re-run' }, () => {
385
+ try { return main(argv, ctx); }
386
+ catch (err) { carried.push(...(err?.lines ?? [])); throw err; }
387
+ });
388
+ return result.lines ? { code: result.exitCode, stdout: [...result.lines, ...carried].join('\n'), stderr: '' } : result;
389
+ };
390
+
370
391
  // The realpath-compare direct-run predicate now lives in tools/direct-run.mjs (the fix this file
371
392
  // carried first, extracted so every module shares one implementation); `sameFile` stays exported here
372
393
  // because this module's tests bind it as a seam.
373
394
  export { sameFile };
374
395
  if (isDirectRun(import.meta.url)) {
375
- const result = main(process.argv.slice(2));
396
+ const result = guardedMain(process.argv.slice(2));
376
397
  if (result.stdout) process.stdout.write(result.stdout.endsWith('\n') ? result.stdout : `${result.stdout}\n`);
377
398
  if (result.stderr) process.stderr.write(result.stderr.endsWith('\n') ? result.stderr : `${result.stderr}\n`);
378
399
  process.exitCode = result.code;