@sabaiway/agent-workflow-kit 23.7.0 → 23.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,13 +22,20 @@
22
22
 
23
23
  import { lstatSync, readFileSync, realpathSync } from 'node:fs';
24
24
  import { createHash } from 'node:crypto';
25
- import { join } from 'node:path';
25
+ import { join, resolve } from 'node:path';
26
26
  import { spawnSync } from 'node:child_process';
27
27
  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
+ import { resolveDeclaredListPath, readDeclaredList, judgeDeclaredList, compareDeclaredAttest, declaredPassLine } from './coverage-declared/index.mjs';
32
+ import { composeUsageRefusal } from '../references/scripts/shared/index.mjs';
33
+ import { runCheckerTail } from './checker-block/index.mjs';
34
+ import {
35
+ CHECKER_NAME, LCOV_BASENAME, composeCoverageBlock, isRed, composeHelp, composeUsage,
36
+ buildDeclaredFindings, buildLcovFindings, buildUncoveredFindings, buildRedProofFindings,
37
+ buildEvidenceFindings, buildAttestationFindings,
38
+ } from './coverage-check/index.mjs';
32
39
  import {
33
40
  computeTreeFingerprint,
34
41
  resolveBase,
@@ -45,9 +52,12 @@ import {
45
52
  } from './core-evidence.mjs';
46
53
 
47
54
  export const COVERAGE_CHECK_STOP = 'COVERAGE_CHECK_STOP';
48
- const usageFail = (message) => Object.assign(new Error(`[agent-workflow-kit] ${message}`), { exitCode: 2 });
49
-
50
- export const LCOV_BASENAME = 'agent-workflow-lcov.info';
55
+ export { LCOV_BASENAME };
56
+ const USAGE_EXIT_CODE = 2;
57
+ const ERROR_EXIT_CODE = 1;
58
+ const NOT_FOUND = -1;
59
+ const LINE_FEED = '\n';
60
+ const ERROR_REMEDY = 'fix the cause the stack below names, then re-run';
51
61
 
52
62
  const gitLine = (args, cwd) => {
53
63
  const r = spawnSync('git', args, { cwd, maxBuffer: GIT_MAX_BUFFER, windowsHide: true });
@@ -70,19 +80,18 @@ export const resolveLcovPath = (cwd, env = process.env) => {
70
80
  const checkCoverage = ({ rootTop, lcovPath, judgeDeclared }) => {
71
81
  const notes = [];
72
82
  const failures = [];
73
- let st = null;
74
- try {
75
- st = lstatSync(lcovPath);
76
- } catch (error) {
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, declared: judgeDeclared(null) };
83
+ const status = (() => {
84
+ try {
85
+ return { file: lstatSync(lcovPath) };
86
+ } catch (error) {
87
+ return { error };
79
88
  }
80
- failures.push(`${lcovPath}: status could not be read (${error?.code ?? 'fs error'})`);
81
- return { failures, notes, skipped: false, lcovSha256: null, declared: judgeDeclared(null) };
89
+ })();
90
+ if (status.error?.code === 'ENOENT') {
91
+ 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) };
82
92
  }
83
- if (!st.isFile()) {
84
- failures.push(`${lcovPath}: not a regular file (a symlink/device is never read — fail closed)`);
85
- return { failures, notes, skipped: false, lcovSha256: null, declared: judgeDeclared(null) };
93
+ if (status.error || !status.file.isFile()) {
94
+ return { failures, lcovFailure: { path: resolve(lcovPath), error: status.error }, notes, skipped: false, lcovSha256: null, declared: judgeDeclared(null) };
86
95
  }
87
96
  const surface = computeChangedSurface(rootTop);
88
97
  const lcovBytes = readFileSync(lcovPath);
@@ -94,10 +103,10 @@ const checkCoverage = ({ rootTop, lcovPath, judgeDeclared }) => {
94
103
  const key = keyFor(rootTop, rel);
95
104
  const uncovered = uncoveredChangedFromLcov(covered, key, lines);
96
105
  if (uncovered === null) {
97
- failures.push(`${rel}: absent from coverage — the suite never executed this changed file`);
106
+ failures.push({ path: rel });
98
107
  continue;
99
108
  }
100
- for (const n of uncovered) failures.push(`${rel}:${n}`);
109
+ for (const n of uncovered) failures.push({ path: rel, line: n });
101
110
  }
102
111
  if (surface.outOfDomain.length > 0) {
103
112
  notes.push(`out-of-domain changed files (no Node-line coverage claim; covered by their own suites): ${surface.outOfDomain.join(', ')}`);
@@ -209,17 +218,17 @@ const verifyRedProofs = ({ rootTop, cwd, env }) => {
209
218
  for (const record of bound) {
210
219
  const id = record.testId;
211
220
  if (record.fingerprint === fingerprint) {
212
- failures.push(`${id}: the record's pre-fix fingerprint EQUALS the current tree — nothing changed since the observed red (reuse/forgery); re-observe on the pre-fix tree`);
221
+ failures.push({ file: record.file, testId: id, reason: "the record's pre-fix fingerprint EQUALS the current tree — nothing changed since the observed red (reuse/forgery); re-observe on the pre-fix tree" });
213
222
  continue;
214
223
  }
215
224
  const resolved = resolveTestFile(rootTop, record.file);
216
225
  if (!resolved.ok) {
217
- failures.push(`${id}: the bound test file ${resolved.reason.includes('does not exist') ? 'was deleted — ' : ''}${resolved.reason}`);
226
+ failures.push({ file: record.file, testId: id, reason: `the bound test file ${resolved.reason.includes('does not exist') ? 'was deleted — ' : ''}${resolved.reason}` });
218
227
  continue;
219
228
  }
220
229
  const currentHash = hashFileBytes(resolved.abs);
221
230
  if (currentHash !== record.fileHash) {
222
- failures.push(`${id}: the bound test file's content changed since the observed red (hash mismatch) — re-observe red at the new expectations`);
231
+ failures.push({ file: record.file, testId: id, reason: "the bound test file's content changed since the observed red (hash mismatch) — re-observe red at the new expectations" });
223
232
  continue;
224
233
  }
225
234
  let greens = 0;
@@ -232,11 +241,11 @@ const verifyRedProofs = ({ rootTop, cwd, env }) => {
232
241
  if (p.resolvable && p.baselineGreen) greens += 1;
233
242
  }
234
243
  if (executed === 0) {
235
- failures.push(`${id}: the pattern selects no test (zero-match) — the declared red→green pin is gone`);
244
+ failures.push({ file: record.file, testId: id, reason: 'the pattern selects no test (zero-match) — the declared red→green pin is gone' });
236
245
  continue;
237
246
  }
238
247
  if (greens !== reruns) {
239
- failures.push(`${id}: not green ${reruns}/${reruns} at the final run (${greens}/${reruns} green) — the declared fix is red`);
248
+ failures.push({ file: record.file, testId: id, reason: `not green ${reruns}/${reruns} at the final run (${greens}/${reruns} green) — the declared fix is red` });
240
249
  }
241
250
  }
242
251
  return { failures, verified: bound.length };
@@ -250,7 +259,6 @@ export const runCheck = ({ cwd = process.cwd(), env = process.env } = {}) => {
250
259
  const read = readDeclaredList(resolveDeclaredListPath(rootTop));
251
260
  const lcovPath = resolveLcovPath(cwd, env);
252
261
  const lines = [];
253
- let failed = false;
254
262
  // The identity is read BEFORE the coverage arm and again AFTER it: a single up-front comparison
255
263
  // leaves a window in which the tree moves between the surface walk and the verdict.
256
264
  const identityBefore = { fingerprint: computeTreeFingerprint(cwd), base: resolveBase(cwd) };
@@ -264,29 +272,10 @@ export const runCheck = ({ cwd = process.cwd(), env = process.env } = {}) => {
264
272
  lines.push(`coverage-check: lcov-sha256=${cov.lcovSha256 ?? 'none'}`);
265
273
  for (const note of cov.notes) lines.push(`coverage-check: ${note}`);
266
274
  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}`);
276
- }
277
275
  // The probes must never inherit a live attestation capability (a detached descendant could keep it).
278
276
  const red = verifyRedProofs({ rootTop, cwd, env: withoutAttestEnv(env) });
279
- if (red.storeFailure) {
280
- failed = true;
281
- lines.push(`coverage-check: FAIL — ${red.storeFailure}`);
282
- } else {
283
- if (red.failures.length > 0) {
284
- failed = true;
285
- lines.push('coverage-check: FAIL — red-proof obligations not satisfied:');
286
- for (const f of red.failures) lines.push(` ${f}`);
287
- } else if (red.verified > 0) {
288
- lines.push(`coverage-check: ${red.verified} red-proof record(s) verified green N/N with custody intact`);
289
- }
277
+ if (!red.storeFailure && red.failures.length === 0 && red.verified > 0) {
278
+ lines.push(`coverage-check: ${red.verified} red-proof record(s) verified green N/N with custody intact`);
290
279
  }
291
280
  // Re-read the identity AFTER the coverage arm and re-decide: the attestation must describe the
292
281
  // tree the verdict was actually computed over, not the one it started over.
@@ -303,10 +292,16 @@ export const runCheck = ({ cwd = process.cwd(), env = process.env } = {}) => {
303
292
  // EXACTLY ONE fully anchored machine line, the lcov-sha256 contract's sibling — the runner binds
304
293
  // it, so a missing/duplicated/injected one is an integrity failure rather than a silent green.
305
294
  lines.push(`coverage-check: attested=${attesting ? 'yes' : 'no'}`);
306
- if (attestation.refusal) {
307
- failed = true;
308
- lines.push(`coverage-check: REFUSED — ${attestation.refusal}`);
309
- } else if (!attesting) {
295
+ const classes = [
296
+ buildDeclaredFindings(declared),
297
+ buildLcovFindings(cov.lcovFailure),
298
+ buildUncoveredFindings(cov.failures),
299
+ buildRedProofFindings(red.failures ?? []),
300
+ buildEvidenceFindings(red.storeFailure ? resolve(storePath) : storePath, red.storeFailure),
301
+ buildAttestationFindings(rootTop, attestation.refusal),
302
+ ];
303
+ const failed = isRed(classes);
304
+ if (!attestation.refusal && !attesting) {
310
305
  lines.push(`coverage-check: NO VERDICT — ${contextValid ? NO_BYTES_NO_VERDICT : attestation.reason}`);
311
306
  }
312
307
  // The attestation gates ONLY the coverage claim. Every pre-existing fail-closed refusal above
@@ -314,71 +309,28 @@ export const runCheck = ({ cwd = process.cwd(), env = process.env } = {}) => {
314
309
  if (attesting && !failed && cov.failures.length === 0) {
315
310
  lines.push(declaredPassLine(declared.notJudged.length));
316
311
  }
317
- return { code: failed ? 1 : 0, lines };
312
+ return { code: failed ? 1 : 0, lines: composeCoverageBlock({ root: rootTop, classes, after: lines, withoutContext: !contextValid }) };
318
313
  };
319
314
 
320
315
  // ── CLI ───────────────────────────────────────────────────────────────────────────────────────────
321
316
 
322
- const HELP = `coverage-check — the D3(c)+(d) final-run checker (agent-workflow family).
323
-
324
- Usage:
325
- node coverage-check.mjs --check [--cwd <dir>]
326
-
327
- Reads the FIXED kit-owned lcov file (<git dir>/${LCOV_BASENAME}; AW_LCOV_FILE overrides —
328
- produced by the declared unit-tests gate cmd's --experimental-test-coverage lcov reporters and
329
- deleted fresh by run-gates --final), lists uncovered CHANGED executable Node lines file:line,
330
- lists changed out-of-domain files (the coverage claim is narrowed to Node lines), and VERIFIES
331
- every current-base red-proof record: bound test present, content hash unchanged, green N/N
332
- (AW_CORE_EVIDENCE_RERUNS, default 3), pre-fix fingerprint differing from the current tree.
333
- An absent lcov file (ENOENT) is a LOUD skipped-no-lcov (exit 0 — NO coverage check ran, stated).
334
- Any other lcov status failure, a symlinked lcov path, an uncovered line, a broken red-proof
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.
340
-
341
- A coverage VERDICT is issued ONLY inside the run that owns the artifact's lifetime: run-gates
342
- --final deletes the lcov before any gate spawns and hands this checker an attestation context
343
- (a nonce whose one-way commitment over {nonce, fingerprint, base} is the final-start attempt id).
344
- One anchored machine line rides every run: coverage-check: attested=<yes|no>. It states whether a
345
- coverage VERDICT was ISSUED — pass OR fail — never that coverage passed.
346
- attested=yes → a verdict was issued over the lcov BYTES this run read (a failing one still
347
- exits 1); the predicate is the consumed digest, never the skip flag.
348
- attested=no → NO VERDICT: no handshake, or no lcov bytes were read at all (an absent file or a
349
- refused path — nothing read, nothing certified). Withholding a verdict never
350
- changes an exit code: an absent lcov stays exit 0, a refused non-regular path
351
- keeps its own fail-closed exit 1, and uncovered lines still exit 1. Findings are
352
- still printed; run-gates carries the withheld verdict as coverage=not-run.
353
- REFUSED (exit 1) → the context describes another tree or another declared list, or matches no recorded attempt.
354
- Residual, stated: ownership of the fixed path is CONVENTION, not enforcement — a concurrent writer
355
- to it can still place foreign evidence (queued as LCOV-EXCLUSIVE-OWNERSHIP).
356
-
357
- Sandbox-safe: no network; writes nothing; spawns read-only git queries and the bound-test
358
- probes (node --test, shell-free) — the D4 sandbox lane. The attestation variables are consumed and
359
- removed from this process's environment before anything spawns, so no child inherits the capability.
360
- Read-only. Exit codes: 0 pass / no-verdict / skipped-loud; 1 fail or REFUSED; 2 usage.`;
361
-
362
317
  export const main = (argv, ctx = {}) => {
318
+ if (argv.includes('--help') || argv.includes('-h')) return { code: 0, stdout: composeHelp(), stderr: '' };
363
319
  const env = ctx.env ?? process.env;
364
- try {
365
- if (argv.includes('--help') || argv.includes('-h')) return { code: 0, stdout: HELP, stderr: '' };
366
- let cwd = ctx.cwd ?? process.cwd();
367
- const rest = [...argv];
368
- const cwdAt = rest.indexOf('--cwd');
369
- if (cwdAt !== -1) {
370
- cwd = rest[cwdAt + 1];
371
- if (cwd === undefined) throw usageFail('--cwd needs a directory');
372
- rest.splice(cwdAt, 2);
373
- }
374
- const checkAt = rest.indexOf('--check');
375
- if (checkAt !== -1) rest.splice(checkAt, 1);
376
- if (rest.length > 0) throw usageFail(`unknown argument: ${rest[0]}`);
377
- const { code, lines } = runCheck({ cwd, env });
378
- return { code, stdout: lines.join('\n'), stderr: '' };
379
- } catch (err) {
380
- return { code: err.exitCode ?? 1, stdout: '', stderr: `coverage-check: ${err.message}` };
381
- }
320
+ const rest = [...argv];
321
+ const cwdAt = rest.indexOf('--cwd');
322
+ const refuseUsage = (failed) => ({
323
+ code: USAGE_EXIT_CODE,
324
+ stdout: composeUsageRefusal({ name: CHECKER_NAME, failed, usage: composeUsage() }).join(LINE_FEED),
325
+ stderr: '',
326
+ });
327
+ if (cwdAt !== NOT_FOUND && rest[cwdAt + 1] === undefined) return refuseUsage('--cwd needs a directory');
328
+ const cwd = cwdAt === NOT_FOUND ? ctx.cwd ?? process.cwd() : rest.splice(cwdAt, 2)[1];
329
+ const checkAt = rest.indexOf('--check');
330
+ if (checkAt !== NOT_FOUND) rest.splice(checkAt, 1);
331
+ if (rest.length > 0) return refuseUsage(`unknown argument: ${JSON.stringify(rest[0])}`);
332
+ const { code, lines } = runCheck({ cwd, env });
333
+ return { code, stdout: lines.join(LINE_FEED), stderr: '' };
382
334
  };
383
335
 
384
336
  if (isDirectRun(import.meta.url)) {
@@ -391,8 +343,6 @@ if (isDirectRun(import.meta.url)) {
391
343
  .map((k) => [k, process.env[k]]),
392
344
  );
393
345
  for (const k of Object.keys(attest)) delete process.env[k];
394
- const r = main(process.argv.slice(2), { env: { ...process.env, ...attest } });
395
- if (r.stdout) process.stdout.write(r.stdout.endsWith('\n') ? r.stdout : `${r.stdout}\n`);
396
- if (r.stderr) process.stderr.write(r.stderr.endsWith('\n') ? r.stderr : `${r.stderr}\n`);
397
- process.exitCode = r.code;
346
+ runCheckerTail({ name: CHECKER_NAME, exitCode: ERROR_EXIT_CODE, remedy: ERROR_REMEDY },
347
+ () => main(process.argv.slice(2), { env: { ...process.env, ...attest } }), process);
398
348
  }
@@ -18,11 +18,10 @@ const HEX_RADIX = 16;
18
18
  const ESCAPE_WIDTH = 4;
19
19
  const ESCAPE_PADDING = '0';
20
20
  const EMPTY_TEXT = '';
21
- const CONFIG_FAILURE_PREFIX = `coverage-check: FAIL — ${COVERAGE_DECLARED_REL}: `;
22
21
  const PASS_LINE = 'coverage-check: PASS — every changed Node line is covered';
23
22
 
24
23
  const makeResult = (configFailure = null) => ({ configFailure, notJudged: [], lines: [], failures: [] });
25
- const makeConfigFailure = (defect) => makeResult(`${CONFIG_FAILURE_PREFIX}${defect}`);
24
+ const makeConfigFailure = (defect) => makeResult(defect);
26
25
  const renderAsciiLine = (value) => Array.from(String(value), (character) => {
27
26
  const codePoint = character.codePointAt(ZERO);
28
27
  return codePoint >= ASCII_FIRST && codePoint <= ASCII_LAST
@@ -55,7 +54,7 @@ export const judgeDeclaredList = ({ top, read, changed, spawn }) => {
55
54
  continue;
56
55
  }
57
56
  if (probe.outcome === FOREIGN || probe.outcome === ERROR) {
58
- result.failures.push(`${entry.path}: listed in ${COVERAGE_DECLARED_REL} but not a regular file`);
57
+ result.failures.push({ path: entry.path, text: `listed in ${COVERAGE_DECLARED_REL} but not a regular file` });
59
58
  continue;
60
59
  }
61
60
  if (changed === null) continue;
@@ -71,12 +71,12 @@ import { assertDocsAiDeployment, writeDocsAiFileAtomic, lstatNoFollow } from './
71
71
  // The source-size practice, through its PURE READ core only (D-18): this module asks whether the
72
72
  // practice is minted, never how to mint it — the checker's writer half stays outside the read graph.
73
73
  import {
74
- INITIAL_ADOPTION_REASON,
75
74
  SOURCE_SIZE_GATE_ID,
76
75
  SOURCE_SIZE_TOOL_PATH,
77
76
  escapeForLine,
78
77
  isLineUnsafe,
79
78
  loadSourceSizeConfig,
79
+ mintReasonOf,
80
80
  } from './source-size-core.mjs';
81
81
 
82
82
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -469,7 +469,7 @@ export const sourceSizeCandidate = (cwd, deps = {}) => {
469
469
  // every run, so pointing there would hand the reader their next failure as the way out.
470
470
  const lane = state === 'minted'
471
471
  ? `${schema1 ? 'move the record to schema 2 first — run source-size-check.mjs --write-baseline with the working directory set to this project, then ' : ''}declare the gate by hand`
472
- : `mint the record first — run source-size-check.mjs --adopt --reason "${INITIAL_ADOPTION_REASON}" with the working directory set to this project, then declare the gate by hand`;
472
+ : `mint the record first — run source-size-check.mjs --adopt --reason "${mintReasonOf(config)}" with the working directory set to this project, then declare the gate by hand`;
473
473
  return {
474
474
  candidate: null,
475
475
  note:
@@ -480,14 +480,14 @@ export const sourceSizeCandidate = (cwd, deps = {}) => {
480
480
  }
481
481
  if (state !== 'minted') {
482
482
  // The named recovery is the reader's next keystroke, so it is a command they can actually run:
483
- // the resolved absolute path and an explicit --cwd, carrying the reason a FIRST mint requires
483
+ // the resolved absolute path and an explicit --cwd, carrying the reason the mint's rule gives
484
484
  // (recording a value for the first time is a raise, and the bare verb would refuse). The
485
485
  // PROJECT path is screened by the same predicate — a rendered command naming a path the shell
486
486
  // would read differently could run somewhere other than the project it names.
487
487
  const project = resolve(cwd);
488
488
  const recovery = unrenderableToolPath(project)
489
- ? `run source-size-check.mjs --adopt --reason "${INITIAL_ADOPTION_REASON}" yourself, with the working directory set to this project (no command is printed: this project's path cannot be rendered into one)`
490
- : `run node "${toolPath}" --adopt --reason "${INITIAL_ADOPTION_REASON}" --cwd "${project}"`;
489
+ ? `run source-size-check.mjs --adopt --reason "${mintReasonOf(config)}" yourself, with the working directory set to this project (no command is printed: this project's path cannot be rendered into one)`
490
+ : `run node "${toolPath}" --adopt --reason "${mintReasonOf(config)}" --cwd "${project}"`;
491
491
  return {
492
492
  candidate: null,
493
493
  note:
@@ -71,7 +71,7 @@ import { takeCensus, censusFact, CENSUS_VERDICT } from './tracked-tree-census.mj
71
71
  // fill's own WRITER is never called from here — the advisor renders its consent-gated command, it
72
72
  // does not run it.
73
73
  import { buildOffer } from './gates-init.mjs';
74
- import { CHECKER_CLAIM, INITIAL_ADOPTION_REASON, SOURCE_SIZE_GATE_ID, classifySourceSizeGate, loadSourceSizeConfig, readLayoutSetup, readPileOffer } from './source-size-core.mjs';
74
+ import { CHECKER_CLAIM, SOURCE_SIZE_GATE_ID, classifySourceSizeGate, loadSourceSizeConfig, mintReasonOf, presentHalves, readLayoutSetup, readPileOffer } from './source-size-core.mjs';
75
75
  // The declared-path resolution + segment containment this item's convergence lane shares with the
76
76
  // autonomy render's allowWrite degrade — ONE leaf, so the two answers cannot drift.
77
77
  import { resolveDeclaredDir, dirCovers, isResolvableDeclaredEntry } from './declared-paths.mjs';
@@ -133,6 +133,8 @@ const HOOK_CHECKS_UNMANAGED_HOOK = 'an UNMANAGED pre-commit hook exists \u2014 t
133
133
  const HOOK_CHECKS_WAIT = 'the layout line follows the source-size.layout record \u2014 apply that item first; this item\'s check line then arms the layout line too';
134
134
  const HOOK_CHECKS_COMMAND = "the hook runs the kit's checks by flat paths this upgrade removes — once they are gone every commit stops until this item is applied";
135
135
  const LAYOUT_RECORD_RECIPE = 'the hook is per clone and the config per branch: a branch or linked worktree with no size config is judged under the kit\'s values and stops on its piles until it takes the record (a hidden deployment\'s linked worktree carries none); one with an older config without layout is not judged on layout; one whose config is schema 1 or unminted stops every commit on that config\'s own stop until it takes the current config';
136
+ const REASON_AUTHOR_RECIPE = 'the reason is yours to write, with no question to the user: where you made the growth, say why this size is accepted; where an entry grew before this write (a half-written record, a raise after the schema move, a teammate\'s growth), write that it grew before this write and its cause was not recorded';
137
+ const SOURCE_SIZE_KEPT_WHAT = 'no source-size gate is declared — the size record is kept as it is; declaring the gate adds the size check to the gate matrix';
136
138
  const LAYOUT_HELD = {
137
139
  stops: () => 'the source-size check stops on this tree, so a layout record or layout line not yet in place waits \u2014 record that growth first with the reasoned --write-baseline its stop names, then re-run',
138
140
  'store-root': ({ root }) => `the source-size config declares the root "${root}" at or inside the spec store docs/ai/specs \u2014 the layout record starts once that root is declared outside it`,
@@ -284,13 +286,13 @@ export const WHATS = Object.freeze({
284
286
  'gates-inert.no-verification': "all {n} declared gate(s) are the kit's own checkers — the matrix runs no project-verification command",
285
287
  'gates-inert.producer-unrecognized': 'the coverage checker ({id}) has NO producer declared and none offerable, on a tree the changed-line domain barely reaches',
286
288
  'gates-inert.coverage-domain-narrow': 'certification covers the assessable minority only — {ext} dominate(s) the tracked tree, and the changed-line domain excludes them',
287
- 'source-size': 'no source-size gate — module size drifts unmeasured, and an over-cap file is invisible instead of recorded debt',
289
+ 'source-size': 'no source-size gate is declared — the gate matrix runs no size check, so no gate run stops a file beyond its limits',
288
290
  'source-size.unminted': 'the source-size gate is declared over an unminted record ({state}) — the check refuses it, or if absent judges layout alone, no line',
289
291
  'source-size.schema-1': 'the source-size config is schema 1, which the check stops on — the writer moves it to schema 2 in one write',
290
292
  'source-size.layout': 'the layout record is not started — starting it records any directory already beyond the layout limits, so the commit hook can judge layout',
291
293
  'source-size.piles': '{n} recorded pile(s) have no queue row planning their cleanup — one row each goes to the end of the queue\'s Later bucket',
292
294
  'source-size.adopted-elsewhere': "the source-size gate runs a DIFFERENT copy of this checker ({n} declared) — adopted here, just not through this kit's own tool",
293
- 'source-size.id-squatter': 'a gate carries the source-size id but is not this checker — the practice reads as declared while nothing measures module size',
295
+ 'source-size.id-squatter': 'a gate carries the source-size id but is not this checker — the gate matrix reads as running the size check while it runs none',
294
296
  'gate-hook': '{n} declared gate(s) prompt per run — the gate-approval hook is not wired',
295
297
  'gate-hook.not-current': `${HOOK_FILE_REL} is absent or differs from the body the kit writes for it — written with that body, with no question`,
296
298
  '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',
@@ -857,9 +859,13 @@ export const probeGatesInert = ({ root, deps, add, skip }) => {
857
859
  // practice question outright; else any tool-elsewhere claim; else the id collision; else the offer.
858
860
  // A MINTED schema-1 config is asked first, ahead of the gate arms: the check stops on it whatever is
859
861
  // declared. Its line carries no reason, since a pinned one would launder a raise; an unreadable
860
- // config keeps today's arms, which report it.
861
- const schema1Minted = (root, deps) => {
862
- try { const { state, config } = loadSourceSizeConfig(root, deps); return state === 'minted' && config.schema === 1; } catch { return false; }
862
+ // config (null here) keeps today's arms, which report it.
863
+ const readSizeConfig = (root, deps) => {
864
+ try {
865
+ return loadSourceSizeConfig(root, deps);
866
+ } catch {
867
+ return null;
868
+ }
863
869
  };
864
870
 
865
871
  // The layout setup's answer for the layout arm; its throw is a stated skip, and the other arms still speak.
@@ -889,8 +895,10 @@ const pilesArm = (root, declaration, deps, add, skip) => {
889
895
  const probeSourceSize = ({ root, deps, add, skip, shared }) => {
890
896
  try {
891
897
  const tool = toolPath('source-size-check.mjs');
892
- if (schema1Minted(root, deps)) {
893
- add('source-size', fillTemplate(WHATS['source-size.schema-1'], {}), `node ${q(tool)} --write-baseline --cwd ${q(root)}`, 'source-size.schema-1');
898
+ const loaded = readSizeConfig(root, deps);
899
+ const recipe = presentHalves(loaded?.config).length > 0 ? REASON_AUTHOR_RECIPE : null;
900
+ if (loaded?.state === 'minted' && loaded.config.schema === 1) {
901
+ add('source-size', fillTemplate(WHATS['source-size.schema-1'], {}), `node ${q(tool)} --write-baseline --cwd ${q(root)}`, 'source-size.schema-1', REASON_AUTHOR_RECIPE);
894
902
  return;
895
903
  }
896
904
  // The layout arm, additive: the record renders as its own item ahead of the other arms; a held answer
@@ -906,10 +914,8 @@ const probeSourceSize = ({ root, deps, add, skip, shared }) => {
906
914
  pilesArm(root, declaration, deps, add, skip);
907
915
  if (loadError !== null) throw loadError;
908
916
  const gates = declaration.outcome === 'loaded' ? declaration.gates : [];
909
- // The reason string is PINNED, not composed: it is copied unchanged into every entry the first
910
- // mint records, and a first mint records the whole tree — so "this is what the tree already
911
- // carried when the practice arrived" is the one sentence that is true of all of them.
912
- const adoptLine = `node ${q(tool)} --adopt --reason "${INITIAL_ADOPTION_REASON}" --cwd ${q(root)}`;
917
+ const mintReason = mintReasonOf(loaded?.config);
918
+ const adoptLine = `node ${q(tool)} --adopt --reason "${mintReason}" --cwd ${q(root)}`;
913
919
  const claims = gates.map((gate) => ({ gate, claim: classifySourceSizeGate(gate.cmd, root) }));
914
920
  const canonical = claims.filter((c) => c.claim === CHECKER_CLAIM.CANONICAL);
915
921
  const elsewhere = claims.filter((c) => c.claim === CHECKER_CLAIM.ELSEWHERE);
@@ -919,18 +925,13 @@ const probeSourceSize = ({ root, deps, add, skip, shared }) => {
919
925
  // absent one it judges layout alone and no line. The declaration alone would report that deployment
920
926
  // as adopted and say nothing about the one thing wrong with it. The split changes NOTHING here —
921
927
  // the outcome, its attention class and its immunity to every ack are the same whichever copy runs.
922
- const { state } = loadSourceSizeConfig(root, deps);
928
+ const { state } = loaded ?? loadSourceSizeConfig(root, deps);
923
929
  if (state !== 'minted') {
924
930
  // Only the way OUT differs. With the gate declared through another copy, `--adopt` would
925
931
  // mint the record and then be refused by the fill on the id it is already looking at, so the
926
932
  // rendered verb is the mint alone: the declaration is not the half that is missing.
927
- const mintLine = `node ${q(tool)} --write-baseline --reason "${INITIAL_ADOPTION_REASON}" --cwd ${q(root)}`;
928
- add(
929
- 'source-size',
930
- fillTemplate(WHATS['source-size.unminted'], { state }),
931
- canonical.length > 0 ? adoptLine : mintLine,
932
- 'source-size.unminted',
933
- );
933
+ const mintLine = `node ${q(tool)} --write-baseline --reason "${mintReason}" --cwd ${q(root)}`;
934
+ add('source-size', fillTemplate(WHATS['source-size.unminted'], { state }), canonical.length > 0 ? adoptLine : mintLine, 'source-size.unminted', recipe);
934
935
  return;
935
936
  }
936
937
  if (canonical.length > 0) return; // adopted through THIS copy and armed — converged
@@ -941,12 +942,9 @@ const probeSourceSize = ({ root, deps, add, skip, shared }) => {
941
942
  // realpaths, which are machine-specific and would churn a committed ack between machines.
942
943
  const fingerprint = factFingerprint(JSON.stringify([...new Set(elsewhere.map((c) => c.gate.cmd))].sort()));
943
944
  if (readAckValue(root, deps, ACKS_SOURCE_SIZE_COPY_KEY) === fingerprint) return; // acknowledged
944
- add(
945
- 'source-size',
946
- fillTemplate(WHATS['source-size.adopted-elsewhere'], { n: elsewhere.length }),
945
+ add('source-size', fillTemplate(WHATS['source-size.adopted-elsewhere'], { n: elsewhere.length }),
947
946
  `node ${q(toolPath('ack-write.mjs'))} --lane source-size-copy --fingerprint ${fingerprint} --cwd ${q(root)}`,
948
- 'source-size.adopted-elsewhere',
949
- );
947
+ 'source-size.adopted-elsewhere');
950
948
  return;
951
949
  }
952
950
  // The id SQUATTER — the id says the practice is declared, the cmd is not this checker under any
@@ -958,7 +956,8 @@ const probeSourceSize = ({ root, deps, add, skip, shared }) => {
958
956
  'source-size.id-squatter');
959
957
  return;
960
958
  }
961
- add('source-size', fillTemplate(WHATS['source-size'], {}), adoptLine);
959
+ if (loaded?.state === 'minted') add('source-size', SOURCE_SIZE_KEPT_WHAT, `node ${q(tool)} --adopt --cwd ${q(root)}`, 'source-size', recipe);
960
+ else add('source-size', fillTemplate(WHATS['source-size'], {}), adoptLine, 'source-size', recipe);
962
961
  } catch (err) {
963
962
  skip('source-size', err);
964
963
  }
@@ -39,7 +39,8 @@ from the tree; on an absent config it writes a schema-2 one. --layout starts the
39
39
  present config that has none. The authored keys keep their values and their order; the file is
40
40
  canonically serialized. A regeneration that RAISES any recorded value needs --reason; the string is
41
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.
42
+ the same write, a minted one in a write of its own where the regeneration is refused; --check
43
+ stops on one until it is.
43
44
 
44
45
  --adopt is the ONE-line adoption: it mints the record and declares the source-size gate (and NOTHING
45
46
  else) in docs/ai/gates.json. It is idempotent on an already-adopted project. With the config absent
@@ -51,3 +51,13 @@ export {
51
51
  export {
52
52
  helpText,
53
53
  } from './help.mjs';
54
+
55
+ export {
56
+ INITIAL_ADOPTION_REASON,
57
+ GROWTH_REASON_PLACEHOLDER,
58
+ halfOf,
59
+ presentHalves,
60
+ refusedRaises,
61
+ mintReasonOf,
62
+ commandReasonDefect,
63
+ } from './reason.mjs';
@@ -0,0 +1,32 @@
1
+ export const INITIAL_ADOPTION_REASON = 'initial adoption';
2
+ export const GROWTH_REASON_PLACEHOLDER = '<why this size is accepted>';
3
+
4
+ const HALF_OF_DIMENSION = Object.freeze({
5
+ lines: 'baseline',
6
+ maxLineBytes: 'baseline',
7
+ 'aggregate lines': 'aggregate',
8
+ files: 'layout',
9
+ entries: 'layout',
10
+ depth: 'layout',
11
+ });
12
+ const MACHINE_HALVES = Object.freeze([...new Set(Object.values(HALF_OF_DIMENSION))]);
13
+ const PLACEHOLDER_RE = /^<.*>$/;
14
+
15
+ export const halfOf = ({ dimension }) => HALF_OF_DIMENSION[dimension];
16
+
17
+ export const presentHalves = (config) => MACHINE_HALVES.filter((half) => config?.[half] != null);
18
+
19
+ export const refusedRaises = ({ plan, config, reason }) => {
20
+ const present = presentHalves(config);
21
+ return reason === INITIAL_ADOPTION_REASON ? plan.raises.filter((delta) => present.includes(halfOf(delta))) : [];
22
+ };
23
+
24
+ export const mintReasonOf = (config) => presentHalves(config).length > 0 ? GROWTH_REASON_PLACEHOLDER : INITIAL_ADOPTION_REASON;
25
+
26
+ export const commandReasonDefect = (reason, { override = false } = {}) => {
27
+ if (PLACEHOLDER_RE.test(reason)) return `--reason still carries the placeholder ${reason} — write the reason in its place; the command line never takes a placeholder as a reason`;
28
+ if (override && reason === INITIAL_ADOPTION_REASON) {
29
+ return `--override takes its own reason — "${INITIAL_ADOPTION_REASON}" is the kit's sentence for a record's first entries, and an override is a reasoned change of a kit number`;
30
+ }
31
+ return null;
32
+ };