@sabaiway/agent-workflow-kit 21.0.0 → 22.1.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.
@@ -1,18 +1,19 @@
1
1
  #!/usr/bin/env node
2
- // migrate-gates.mjs — the consented LEGACY gates.json migration (strip-the-kit D8). A deployment
3
- // that predates the hardened core declares gates the stripped kit no longer ships (the
4
- // review-ledger / fold-completeness checks); this tool migrates the declaration ATOMICALLY and
5
- // COMPLETELY in one consented step: it REMOVES the canonical legacy entries, EXTENDS the
6
- // canonical `unit-tests` cmd with the built-in lcov reporters (the D3(d) coverage source), and
7
- // ADDS the coverage-check gate LAST (removal alone is not a migration — the result must satisfy
8
- // `run-gates --final` and carry a working commit path). The checker is added ONLY over a
9
- // declaration that PRODUCES the lcov it reads; with no producer it is WITHHELD with a loud
10
- // warning, because a checker with no producer passes (`skipped-no-lcov`) while verifying nothing.
2
+ // migrate-gates.mjs — the LEGACY gates.json migration (strip-the-kit D8), the kit's MANDATORY move. A
3
+ // deployment that predates the hardened core declares gates the stripped kit no longer ships (the
4
+ // review-ledger / fold-completeness checks); `--apply` migrates the declaration ATOMICALLY, with no
5
+ // question: it REMOVES a canonical legacy entry whose target is proven absent, EXTENDS the canonical
6
+ // `unit-tests` cmd, and SWITCHES every producer form an earlier kit wrote, onto the stable kit
7
+ // command's unit-tests name (the D3(d) coverage source), and moves a declared coverage-check gate LAST.
8
+ // The coverage check stays OPTIONAL: the checker is ADDED only with `--add-checker`, which the agent
9
+ // runs on the user's explicit yes, and only over a declaration that PRODUCES the lcov it reads — over
10
+ // none it is withheld, with the fact and the remedy (spec coverage-producer).
11
11
  //
12
12
  // Matching is by the DOCUMENTED cmd forms ONLY (hand-wired history included — never by seed
13
13
  // provenance): a legacy entry is `node <path>/review-ledger.mjs --check` or
14
14
  // `node <path>/fold-completeness.mjs --check` (quoted or bare path, ONE plain invocation); the
15
- // canonical unit-tests entry is id `unit-tests` with a cmd starting `node --test `. ANYTHING
15
+ // canonical unit-tests entry is id `unit-tests` with a cmd `node --test` and a path-shaped rest; an
16
+ // earlier kit's producer form is matched under any id (spec coverage-producer). ANYTHING
16
17
  // else, but a kit-check gate the switch below rewrites, is a CUSTOMIZED entry — never auto-touched: the
17
18
  // preview reports it loudly and prints the paste-ready recovery so the maintainer applies the intent by
18
19
  // hand; the commit guard is NOT to be installed until the declaration is final-run-capable.
@@ -20,8 +21,8 @@
20
21
  // A kit-check gate over a current kit folder that the rules above do not hold customized is SWITCHED to the stable kit command (spec kit-command, read by
21
22
  // ./kit-command-gates.mjs); any other form is named.
22
23
  //
23
- // Write discipline (the family's consented-writer contract): preview (dry-run) is the DEFAULT
24
- // and writes NOTHING; `--apply` rewrites docs/ai/gates.json via exclusive tmp+rename in the same
24
+ // Write discipline (the family's writer contract): preview (dry-run) is the DEFAULT and writes
25
+ // NOTHING, `--add-checker` included; `--apply` rewrites docs/ai/gates.json via exclusive tmp+rename in the same
25
26
  // directory; a symlinked gates.json (or docs/ai parent) is a STOP; a malformed declaration is
26
27
  // never written over. `--kit-tools <dir>` names the installed kit's tools directory — the
27
28
  // migration writes RESOLVED, QUOTED paths for the coverage-check gate (no runtime guessing).
@@ -30,7 +31,7 @@
30
31
  // Dependency-free. No side effects on import.
31
32
 
32
33
  import { existsSync, lstatSync, readFileSync, writeFileSync, renameSync, unlinkSync, realpathSync } from 'node:fs';
33
- import { join, resolve, isAbsolute } from 'node:path';
34
+ import { dirname, join, resolve, isAbsolute } from 'node:path';
34
35
  import { fileURLToPath } from 'node:url';
35
36
  import { randomBytes } from 'node:crypto';
36
37
  import { spawnSync } from 'node:child_process';
@@ -45,7 +46,7 @@ export const GATES_REL = join('docs', 'ai', 'gates.json');
45
46
 
46
47
  // The documented canonical forms — ONE plain invocation, quoted or bare path, `--check` at END
47
48
  // (the run-gates strict-matcher shape; a masked/compound form is a CUSTOMIZED entry).
48
- const legacyRe = (basename) => new RegExp(`^node\\s+(?:"(?:[^"]*[/\\\\])?${basename}"|(?:[^\\s"]*[/\\\\])?${basename})\\s+--check$`);
49
+ const legacyRe = (basename) => new RegExp(`^node\\s+(?:"((?:[^"]*[/\\\\])?${basename})"|((?:[^\\s"]*[/\\\\])?${basename}))\\s+--check$`);
49
50
  export const LEGACY_FORMS = Object.freeze([
50
51
  { name: 'review-ledger', re: legacyRe('review-ledger\\.mjs') },
51
52
  { name: 'fold-completeness', re: legacyRe('fold-completeness\\.mjs') },
@@ -58,31 +59,17 @@ export const LEGACY_FORMS = Object.freeze([
58
59
  // bytes — so a TEXT drift guard beside the root's copy holds them equal. Edit BOTH, then re-run the
59
60
  // mirror sync.
60
61
  //
61
- // The destination is written against AW_GIT_DIR, which run-gates exports to every gate child on a
62
- // plain run AND on --final (AW_LCOV_FILE is --final only), so one cmd survives the unmet
63
- // producer-variable preflight in both modes. The `:?` is not decoration either: this cmd is also
64
- // PASTE-READY, and the required-parameter form makes bash refuse BY NAME when AW_GIT_DIR is unset
65
- // or EMPTY, where a bare `$AW_GIT_DIR` expanded to empty and wrote the lcov to the filesystem ROOT.
66
- // Residual, stated: `:?` says nothing about the value's ORIGIN — a STALE exported AW_GIT_DIR
67
- // expands fine and the lcov lands under it; only the runner's own injection makes it the right dir.
68
- // The explicit stdout reporter keeps the human stream: without it the lcov reporter swallows the
69
- // TAP/spec output.
70
- export const UNIT_TESTS_COVERAGE_FLAGS =
71
- '--experimental-test-coverage --test-reporter=lcov --test-reporter-destination="${AW_GIT_DIR:?exported by run-gates}/agent-workflow-lcov.info" --test-reporter=spec --test-reporter-destination=stdout';
72
-
73
- // Every flag set the kit has EVER emitted — APPEND-ONLY, newest first. Emission uses the head; the
74
- // tail exists so a declaration written by an EARLIER kit and living on disk in a deployed project
75
- // keeps reading as the producer it is. De-recognizing a prior form would silently reclassify a
76
- // working suite gate as customized and withhold the checker over it.
77
- export const KNOWN_COVERAGE_FLAG_SETS = Object.freeze([
78
- UNIT_TESTS_COVERAGE_FLAGS,
62
+ // The ONE producer form the kit writes: the stable kit command's unit-tests name (spec kit-command) —
63
+ // the Node test runner with the lcov reporter under AW_GIT_DIR and the kit test reporter on stdout.
64
+ export const COVERAGE_PRODUCER_BODY = 'node scripts/agent-workflow/run.mjs unit-tests';
65
+
66
+ // The reporter flag sets earlier kits wrote after `node --test`, newest first, byte for byte: a MOVE
67
+ // LIST the gate migration switches onto the body above, never read as a producer.
68
+ export const RETIRED_COVERAGE_FLAG_SETS = Object.freeze([
69
+ '--experimental-test-coverage --test-reporter=lcov --test-reporter-destination="${AW_GIT_DIR:?exported by run-gates}/agent-workflow-lcov.info" --test-reporter=spec --test-reporter-destination=stdout',
79
70
  '--experimental-test-coverage --test-reporter=lcov --test-reporter-destination="$AW_GIT_DIR/agent-workflow-lcov.info" --test-reporter=spec --test-reporter-destination=stdout',
80
71
  ]);
81
-
82
- // The ONE suite body that produces that lcov with no extra dependency (the EMITTED form), beside
83
- // the closed set of bodies recognition accepts.
84
- export const COVERAGE_PRODUCER_BODY = `node --test ${UNIT_TESTS_COVERAGE_FLAGS}`;
85
- const KNOWN_PRODUCER_BODIES = Object.freeze(KNOWN_COVERAGE_FLAG_SETS.map((flags) => `node --test ${flags}`));
72
+ const RETIRED_BODIES = Object.freeze(RETIRED_COVERAGE_FLAG_SETS.map((flags) => `node --test ${flags}`));
86
73
 
87
74
  // The per-PM exec wrappers a fill offer puts that body behind. Recognition must cover every form
88
75
  // the kit has EMITTED, so the prefixes are matched literally; gates-init's execCmdFor stays the one
@@ -95,11 +82,11 @@ const PRODUCER_EXEC_PREFIXES = Object.freeze([
95
82
 
96
83
  // A trailing suffix is the project's own test paths; a leading one would mean the body is not what
97
84
  // this cmd runs. The tail passes a POSITIVE closed grammar — every whitespace-separated token must
98
- // be path-shaped — never an operator blocklist: `node --test <flags> && rm -f <lcov>` runs the
99
- // suite and then DELETES the file, so an open-ended tail would certify a producer that leaves
100
- // nothing behind, and scanning for operator BYTES would put the incomplete-scan failure on the
101
- // unsafe side (a missed operator is a dead pair) instead of the mild one (an unrecognised
102
- // legitimate tail merely withholds the offer — add the gate by hand).
85
+ // be path-shaped — never an operator blocklist: `<body> && rm -f <lcov>` runs the suite and then
86
+ // DELETES the file, so an open-ended tail would certify a producer that leaves nothing behind, and
87
+ // scanning for operator BYTES would put the incomplete-scan failure on the unsafe side (a missed
88
+ // operator is a dead pair) instead of the mild one (an unrecognised legitimate tail merely
89
+ // withholds the offer — add the gate by hand). No flag either: the command hands it to the runner.
103
90
  // The token set is everything that appears in a PATH or a glob and can never sequence, redirect or
104
91
  // substitute a command — quoting and `~` included, `( ) $ ` ; & | < > # \` excluded. SCOPE, stated
105
92
  // exactly: the screen judges each token's SOURCE bytes. Quote removal adds none, but brace SEQUENCE
@@ -114,22 +101,65 @@ const PRODUCER_EXEC_PREFIXES = Object.freeze([
114
101
  // `skipped-no-lcov`.
115
102
  const PRODUCER_PATH_TOKEN = /^(?!-)[A-Za-z0-9_./*{},:@+=~?[\]!'"-]+$/;
116
103
  const pathShapedTail = (tail) => tail === '' || tail.split(/[ \t]+/).every((token) => PRODUCER_PATH_TOKEN.test(token));
117
- const carriesProducerBody = (text) =>
118
- KNOWN_PRODUCER_BODIES.some(
119
- (body) => text === body || (text.startsWith(`${body} `) && pathShapedTail(text.slice(body.length).trim())),
120
- );
104
+
105
+ // The exec prefix the trimmed text opens with ('' for none), and the rest after it.
106
+ const splitExecPrefix = (text) => {
107
+ const prefix = PRODUCER_EXEC_PREFIXES.find((p) => text.startsWith(p)) ?? '';
108
+ return [prefix, text.slice(prefix.length)];
109
+ };
110
+
111
+ // The rest after `body` (trimmed; '' when nothing follows), or null unless the text is the body, then nothing or one space.
112
+ const bodyRest = (text, body) => {
113
+ if (text === body) return '';
114
+ return text.startsWith(`${body} `) ? text.slice(body.length).trim() : null;
115
+ };
121
116
 
122
117
  // matchesCoverageProducer(cmd) → CLOSED-WORLD over the full command forms the kit emits, never a
123
- // substring probe: `echo "$AW_GIT_DIR/agent-workflow-lcov.info"`, a half-written reporter flag set,
124
- // or the path as a bare substring must all read as NOT a producer — otherwise the checker is
125
- // declared over a gate that writes nothing and then PASSES while certifying nothing.
118
+ // substring probe: `echo <body>`, the quoted body or a retired flag set is NOT a producer — else the
119
+ // checker is declared over a gate that writes nothing and then PASSES while certifying nothing.
126
120
  export const matchesCoverageProducer = (cmd) => {
127
121
  if (typeof cmd !== 'string') return false;
128
- const trimmed = cmd.trim();
129
- if (carriesProducerBody(trimmed)) return true;
130
- return PRODUCER_EXEC_PREFIXES.some((prefix) => trimmed.startsWith(prefix) && carriesProducerBody(trimmed.slice(prefix.length)));
122
+ const [, text] = splitExecPrefix(cmd.trim());
123
+ const rest = bodyRest(text, COVERAGE_PRODUCER_BODY);
124
+ return rest !== null && pathShapedTail(rest);
131
125
  };
132
126
 
127
+ // retiredProducerFormOf(cmd) → { prefix (as written, or ''), tail (trimmed), pathShaped } when the
128
+ // trimmed cmd is no or one exec prefix, `node --test`, a retired flag set and nothing or one space and
129
+ // a rest; null for every other value. The switch carries only a path-shaped tail onto the body.
130
+ export const retiredProducerFormOf = (cmd) => {
131
+ if (typeof cmd !== 'string') return null;
132
+ const [prefix, text] = splitExecPrefix(cmd.trim());
133
+ for (const body of RETIRED_BODIES) {
134
+ const tail = bodyRest(text, body);
135
+ if (tail !== null) return { prefix, tail, pathShaped: pathShapedTail(tail) };
136
+ }
137
+ return null;
138
+ };
139
+
140
+ // unitTestsGuardFailure → the guard on every write of the body: run.mjs a regular file equal to `ownRun`, then the reporter
141
+ // a regular file, every folder on the way a directory (lstat: a link fails); null, or the first failing path and kind,
142
+ // worded by guardRemedy with the caller's upgrade.
143
+ const GUARD_PATHS = Object.freeze(['scripts/agent-workflow/run.mjs', 'scripts/agent-workflow/test-reporter/reporter.mjs']);
144
+ export const unitTestsGuardFailure = (projectDir, ownRun, { lstatSync, readFileSync }) => {
145
+ for (const rel of GUARD_PATHS) {
146
+ const parts = rel.split('/');
147
+ for (let depth = 1; depth <= parts.length; depth += 1) {
148
+ const at = parts.slice(0, depth).join('/');
149
+ const st = lstatSync(`${projectDir}/${at}`, { throwIfNoEntry: false });
150
+ if (st === undefined) return { path: rel, kind: 'absent' };
151
+ if (depth < parts.length ? !st.isDirectory() : !st.isFile()) return { path: at, kind: 'wrong-kind' };
152
+ }
153
+ if (rel === GUARD_PATHS[0] && !readFileSync(`${projectDir}/${rel}`).equals(readFileSync(ownRun))) return { path: rel, kind: 'earlier' };
154
+ }
155
+ return null;
156
+ };
157
+ export const guardRemedy = (kind, upgrade) => ({
158
+ absent: `is absent — the kit's upgrade places the kit folder only where Node evidence stands (a root package.json, or a kit script): add one if this project runs Node, then run ${upgrade}.`,
159
+ earlier: `differs from this kit's — run ${upgrade}, whose configs step writes the current one`,
160
+ 'wrong-kind': `is not what the kit writes there — a directory, a link, or a file where a folder belongs — beside which the specs op writes nothing: clear it by hand first, then run ${upgrade}`,
161
+ })[kind];
162
+
133
163
  // isCoverageProducerGate(gate) → the GATE-level producer question, and the ONE predicate every
134
164
  // consumer asks it through: does THIS declared entry write the lcov the canonical checker reads?
135
165
  // Exactly two ways to be one — the cmd passes the closed world above, or the declaration CLAIMS
@@ -149,6 +179,11 @@ export const isCoverageProducerGate = (gate) => {
149
179
  if (gate.cmd.trim() === '' || /[\r\n]/.test(gate.cmd)) return false;
150
180
  return matchesCoverageProducer(gate.cmd) || gate.lcovProducer === true;
151
181
  };
182
+ // readsAsCoverageProducer(gate, claim) → the ONE producer question of a declared row, asked by both hosts: `claim` is
183
+ // the row's claim on the coverage-check tool through the checker-claim canon, and only a row that is not the tool
184
+ // (`'not-the-tool'`, equal by test to CHECKER_CLAIM.NOT_THE_TOOL) can produce — a checker, canonical or vendored,
185
+ // consumes the lcov it reads, so its marker claims nothing.
186
+ export const readsAsCoverageProducer = (gate, claim) => claim === 'not-the-tool' && isCoverageProducerGate(gate);
152
187
  // coverage-producer canon <<< END drift-guarded region
153
188
 
154
189
  // checker-claim canon >>> BEGIN drift-guarded region
@@ -246,7 +281,7 @@ export const classifyCheckerClaim = (tool, cmd, projectDir) => {
246
281
  // checker-claim canon <<< END drift-guarded region
247
282
 
248
283
  // The RETIRED kit-owned git-dir stores the deleted machinery wrote — dead data a consumer's
249
- // upgrade would otherwise strand forever. The migration cleans them (consented via the preview;
284
+ // upgrade would otherwise strand forever. The migration cleans them on apply (named by the preview;
250
285
  // ENOENT is a silent no-op; any other unlink error is reported loudly but never fails the
251
286
  // migration — the stores are not a gate input).
252
287
  export const RETIRED_STORE_BASENAMES = Object.freeze([
@@ -267,7 +302,31 @@ export const findRetiredStores = (cwd) => {
267
302
  return RETIRED_STORE_BASENAMES.map((name) => join(gitDir, name)).filter((p) => existsSync(p));
268
303
  };
269
304
 
270
- const UNIT_TESTS_PREFIX = 'node --test ';
305
+ const SUITE_LINE = `${COVERAGE_PRODUCER_BODY} <your test paths>`;
306
+ // Every checker line: one positional fact and one remedy; why a gate was kept rides that gate's own line.
307
+ const [WITHHELD_FACT, POSITIONAL_FACT] = ['no declared gate is a producer this kit reads', 'no gate before it is a producer this kit reads'];
308
+ const CHECKER_REMEDY = `declare or move one before it: ${SUITE_LINE}, or mark your own suite gate "lcovProducer": true`;
309
+
310
+ // The guard reads the project's kit folder against this migration's own ../run.mjs; the memory substrate names no sibling skill.
311
+ const OWN_RUN = join(dirname(fileURLToPath(import.meta.url)), '..', 'run.mjs');
312
+ const UPGRADE = "the kit's upgrade";
313
+ const guardLine = ({ id, path, kind }) =>
314
+ ` KEPT ${id}: ${path} ${guardRemedy(kind, UPGRADE)} — once that is resolved, ${UPGRADE} moves this gate with no question.`;
315
+
316
+ // legacyTargetAbsent(re, cmd, projectDir) → whether a legacy check's invocation target, resolved from the project root as
317
+ // run-gates resolves a declared token, is PROVEN absent: the checker-claim quoting screens admit the token and its lstat
318
+ // answers ENOENT. A file, a directory or a link there, or a token the screens refuse (`~`, `$`), is no proof.
319
+ const legacyTargetAbsent = (re, cmd, projectDir) => {
320
+ const [, quoted, bare] = re.exec(cmd.trim());
321
+ const token = quoted ?? bare;
322
+ if (!(quoted !== undefined ? !dqUnsafePath(token) : bareTokenSafe(token)) || token.startsWith('-')) return false;
323
+ try {
324
+ lstatSync(isAbsolute(token) ? token : join(projectDir, token));
325
+ return false;
326
+ } catch (err) {
327
+ return err.code === 'ENOENT';
328
+ }
329
+ };
271
330
 
272
331
  // The core checks the stripped core anchors on, asked through the checker-claim canon above — the
273
332
  // SAME three outcomes, so a declared cmd is read as what it is: this copy of the tool, a DIFFERENT
@@ -278,17 +337,22 @@ const CORE_CHECK_NAMES = Object.freeze(['coverage-check', 'review-state']);
278
337
  const coreCheckTools = (kitToolsDir) =>
279
338
  Object.fromEntries(CORE_CHECK_NAMES.map((name) => [name, checkerClaimTool(`${name}.mjs`, join(kitToolsDir, `${name}.mjs`))]));
280
339
 
281
- // buildMigrationPlan(gates, kitToolsDir, projectDir) → the migration plan.
282
- // plan rows: { action: 'keep' | 'remove' | 'extend' | 'switch' | 'move' | 'add', entry, reason }.
340
+ // buildMigrationPlan(gates, kitToolsDir, projectDir, { addChecker }) → the migration plan.
341
+ // plan rows: { action: 'keep' | 'remove' | 'extend' | 'switch' | 'move' | 'add', entry, reason, claim }.
283
342
  // finalCapable mirrors the run-gates --final acceptance shape: the canonical review-state check
284
343
  // must be PRESENT (the checker itself is guaranteed last by the plan) — missing means the result
285
344
  // is NOT final-run-capable and the preview says so loudly with the paste-ready candidate. An
286
345
  // EXTERNAL-COPY core check withholds that claim too: the runner anchors on the installed copy.
287
- export const buildMigrationPlan = (gates, kitToolsDir, projectDir) => {
346
+ // Every row but the checker add is a mechanical move; the add joins the plan only with `addChecker`
347
+ // (the user's yes), else `checkerOffered` says it would.
348
+ export const buildMigrationPlan = (gates, kitToolsDir, projectDir, { addChecker = false } = {}) => {
288
349
  if (typeof projectDir !== 'string') {
289
350
  throw stop('buildMigrationPlan needs the project root — a declared cmd may name a core check by a RELATIVE path, and only the project root resolves it the way the runner does');
290
351
  }
291
352
  const kit = planKitCommandGates(gates, projectDir);
353
+ let guard;
354
+ const guardFailure = () => (guard === undefined ? (guard = unitTestsGuardFailure(projectDir, OWN_RUN, { lstatSync, readFileSync })) : guard);
355
+ const guardKept = [];
292
356
  const tools = coreCheckTools(kitToolsDir);
293
357
  const claimOf = (name, cmd) => classifyCheckerClaim(tools[name], cmd, projectDir);
294
358
  const plan = [];
@@ -304,20 +368,26 @@ export const buildMigrationPlan = (gates, kitToolsDir, projectDir) => {
304
368
  for (const [at, gate] of gates.entries()) {
305
369
  const legacy = LEGACY_FORMS.find((f) => f.re.test(gate.cmd.trim()));
306
370
  if (legacy) {
307
- plan.push({ action: 'remove', entry: gate, reason: `the ${legacy.name} check died with its tool (strip-the-kit)` });
371
+ // Removed only over a target proven absent: anything standing there may be the project's own, so it is CUSTOMIZED.
372
+ if (legacyTargetAbsent(legacy.re, gate.cmd, projectDir)) {
373
+ plan.push({ action: 'remove', entry: gate, reason: `was: ${gate.cmd} — the ${legacy.name} check died with its tool (strip-the-kit), its target absent` });
374
+ continue;
375
+ }
376
+ customized.push(gate);
377
+ plan.push({ action: 'keep', entry: gate, reason: null, claim: CHECKER_CLAIM.NOT_THE_TOOL });
308
378
  continue;
309
379
  }
310
380
  const coverageClaim = claimOf('coverage-check', gate.cmd);
381
+ const keep = { action: 'keep', entry: gate, reason: null, claim: coverageClaim };
311
382
  if (coverageClaim === CHECKER_CLAIM.CANONICAL) {
312
- const row = { action: 'keep', entry: gate, reason: null };
313
- checkerRows.push(row);
314
- plan.push(row);
383
+ checkerRows.push(keep);
384
+ plan.push(keep);
315
385
  continue;
316
386
  }
317
387
  const reviewClaim = claimOf('review-state', gate.cmd);
318
388
  if (reviewClaim === CHECKER_CLAIM.CANONICAL) {
319
389
  hasReviewState = true;
320
- plan.push({ action: 'keep', entry: gate, reason: null });
390
+ plan.push(keep);
321
391
  continue;
322
392
  }
323
393
  // The third outcome: this IS the tool, from a copy the caller did not name. A vendored
@@ -330,43 +400,47 @@ export const buildMigrationPlan = (gates, kitToolsDir, projectDir) => {
330
400
  ? 'coverage-check'
331
401
  : reviewClaim === CHECKER_CLAIM.ELSEWHERE ? 'review-state' : null;
332
402
  if (elsewhereName !== null) {
333
- const row = { action: 'keep', entry: gate, reason: null };
334
- externalCoreChecks.push({ name: elsewhereName, entry: gate, installed: join(kitToolsDir, `${elsewhereName}.mjs`), row });
335
- plan.push(row);
403
+ externalCoreChecks.push({ name: elsewhereName, entry: gate, installed: join(kitToolsDir, `${elsewhereName}.mjs`), row: keep });
404
+ plan.push(keep);
336
405
  continue;
337
406
  }
338
- if (gate.id === 'unit-tests') {
339
- // Already fully configured — decided by the CLOSED predicate, never a substring probe, and
340
- // over ANY flag set the kit has emitted: a declaration written by an earlier kit stays a
341
- // zero-diff keep (the constant moving must not re-read a working gate as customized), while a
342
- // cmd that merely CONTAINS the bytes — `echo <flags>`, a `&& rm -f <lcov>` tail — is not a
343
- // producer and must reach the CUSTOMIZED report with its recovery instead of a silent keep.
344
- // A declared `lcovProducer` marker settles it the same way: the entry claims production, so
345
- // there is nothing to extend and nothing to report as unverifiable.
346
- if (isCoverageProducerGate(gate)) {
347
- plan.push({ action: 'keep', entry: gate, reason: null });
348
- continue;
349
- }
350
- if (gate.cmd.startsWith(UNIT_TESTS_PREFIX) && !/--experimental-test-coverage|--test-reporter/.test(gate.cmd)) {
351
- const extended = { ...gate, cmd: `node --test ${UNIT_TESTS_COVERAGE_FLAGS} ${gate.cmd.slice(UNIT_TESTS_PREFIX.length)}` };
352
- plan.push({ action: 'extend', entry: extended, reason: 'the unit-tests cmd gains the built-in lcov reporters (the D3(d) coverage source)' });
353
- unitTestsExtended = true;
407
+ // An earlier kit's producer form (any id, marked or not, read BEFORE the marker keep) is SWITCHED,
408
+ // and the unit-tests gate's `node --test` EXTENDED, onto the command body: only over a path-shaped
409
+ // tail (a flag there is CUSTOMIZED, never rewritten) and while the guard holds, else kept with the
410
+ // guard's line. So no form is written that the next run reports CUSTOMIZED.
411
+ const retired = retiredProducerFormOf(gate.cmd);
412
+ const unitRest = retired === null && gate.id === 'unit-tests' && !isCoverageProducerGate(gate) ? bodyRest(gate.cmd.trim(), 'node --test') : null;
413
+ const move = retired ?? (unitRest === null ? null : { prefix: '', tail: unitRest, pathShaped: pathShapedTail(unitRest) });
414
+ if (move !== null) {
415
+ if (!move.pathShaped) customized.push(gate);
416
+ else if (guardFailure() !== null) guardKept.push({ id: gate.id, ...guardFailure() });
417
+ else {
418
+ const entry = { ...gate, cmd: `${move.prefix}${COVERAGE_PRODUCER_BODY}${move.tail ? ` ${move.tail}` : ''}` };
419
+ plan.push(retired !== null
420
+ ? { action: 'switch', entry, reason: `was: ${gate.cmd} — the unit tests run through the stable kit command`, claim: coverageClaim }
421
+ : { action: 'extend', entry, reason: `was: ${gate.cmd} — the unit-tests cmd runs through the stable kit command, which adds the lcov reporter (the D3(d) coverage source)`, claim: coverageClaim });
422
+ unitTestsExtended ||= retired === null;
354
423
  continue;
355
424
  }
356
- // npm test / a wrapper / a partial flag set: the coverage contract cannot be VERIFIED on a
357
- // cmd this tool does not understand — customized, never silently counted as configured.
358
- customized.push(gate);
359
- plan.push({ action: 'keep', entry: gate, reason: null });
425
+ plan.push(keep);
426
+ continue;
427
+ }
428
+ if (gate.id === 'unit-tests') {
429
+ // Already configured — decided by the CLOSED predicate, never a substring probe — or a declared
430
+ // `lcovProducer` marker: keep. `echo <body>`, a `&& rm -f <lcov>` tail, `npm test` or a wrapper
431
+ // cannot be VERIFIED as a producer: CUSTOMIZED with its recovery, never a silent keep.
432
+ if (!isCoverageProducerGate(gate)) customized.push(gate);
433
+ plan.push(keep);
360
434
  continue;
361
435
  }
362
436
  // A dead-tool reference or a core-check LOOKALIKE in a non-canonical form — reported, never touched.
363
437
  const deadTool = /review-ledger|fold-completeness|verification-profile|seed-gates|sarif|coverage-check\.mjs|review-state\.mjs/.test(gate.cmd);
364
438
  if (deadTool) customized.push(gate);
365
439
  if (kit.gates[at] !== gate && !deadTool) {
366
- plan.push({ action: 'switch', entry: kit.gates[at], reason: `was: ${gate.cmd} — the kit check runs through the stable kit command` });
440
+ plan.push({ action: 'switch', entry: kit.gates[at], reason: `was: ${gate.cmd} — the kit check runs through the stable kit command`, claim: coverageClaim });
367
441
  continue;
368
442
  }
369
- plan.push({ action: 'keep', entry: gate, reason: null });
443
+ plan.push(keep);
370
444
  }
371
445
  // A gate the kit reading would switch but the rules above keep untouched is named with its repoint instead.
372
446
  const switchedEntries = new Set(plan.filter((r) => r.action === 'switch').map((r) => r.entry));
@@ -375,61 +449,50 @@ export const buildMigrationPlan = (gates, kitToolsDir, projectDir) => {
375
449
  const checkerRow = checkerRows[checkerRows.length - 1] ?? null;
376
450
  const externalCoverageChecks = externalCoreChecks.filter((c) => c.name === 'coverage-check');
377
451
  // The checker READS an lcov; something has to WRITE it FIRST. Adding the checker over a
378
- // declaration with no producer creates the dead pair — the gate PASSES (`skipped-no-lcov`) and
379
- // certifies nothing, so the migration withholds it and says why instead.
380
- // POSITIONAL, like every other producer question in the family: the checker always ends up LAST
381
- // here (added last, or moved last), so the producers are exactly the rows that are not a checker.
382
- // EVERY checker row is excluded, not merely the one that ends up last — a checker cannot produce
383
- // the lcov it reads, so a marker on a DUPLICATE checker must not read as the producer for the
384
- // other one; that pair would claim final-capability while nothing wrote the file. A VENDORED
385
- // checker is excluded for the identical reason: which copy runs changes nothing about the fact
386
- // that a checker consumes the lcov rather than writing it.
387
- const consumerRows = new Set([...checkerRows, ...externalCoverageChecks.map((c) => c.row)]);
388
- const isProducerRow = (row) => !consumerRows.has(row) && isCoverageProducerGate(row.entry);
452
+ // declaration with no producer creates the dead pair, so the migration withholds it and says why.
453
+ // A row is a producer through the ONE question both hosts ask (readsAsCoverageProducer): a row
454
+ // claiming the coverage checker, the canonical copy or a vendored one, consumes the lcov rather
455
+ // than writing it, so its marker never pairs it with itself or with a duplicate.
456
+ const isProducerRow = (row) => readsAsCoverageProducer(row.entry, row.claim);
389
457
  const hasProducer = kept.some(isProducerRow);
390
458
  let collision = null;
391
459
  let checkerWithheld = false;
460
+ let checkerOffered = false;
392
461
  if (checkerRow !== null) {
393
462
  if (kept[kept.length - 1] !== checkerRow) {
394
463
  checkerRow.action = 'move';
395
- checkerRow.reason = 'the canonical checker must be the LAST declared gate (nothing may run after it consumed the lcov)';
464
+ checkerRow.reason = `was: before ${kept.slice(kept.indexOf(checkerRow) + 1).map((r) => r.entry.id).join(', ')} — the canonical checker must be the LAST declared gate (nothing may run after it consumed the lcov)`;
396
465
  }
397
466
  } else if (externalCoverageChecks.length > 0) {
398
467
  // The checker IS declared, from another copy. Adding the canonical one beside it would create
399
- // the very duplicate the collision STOP exists to prevent — and rewriting the row the
400
- // deployment chose is not this tool's call. Nothing is added, nothing is moved, nothing
401
- // collides; the verify warning below carries what the maintainer has to decide.
468
+ // a duplicate — and rewriting the row the deployment chose is not this tool's call. Nothing is
469
+ // added, nothing is moved; the verify lines below carry what the maintainer has to decide.
402
470
  } else if (kept.some((r) => r.entry.id === 'coverage-check')) {
403
- // A surviving NON-canonical entry already holding the checker's id blocks the add — two
404
- // `coverage-check` rows would be ambiguous; the customized entry must be resolved by hand
405
- // FIRST (the caller turns this into a loud STOP on preview and apply alike).
471
+ // A surviving row other than a checker holding the checker's id withholds only the add — two
472
+ // `coverage-check` rows would be ambiguous — and stops no mechanical row.
406
473
  collision = 'coverage-check';
407
474
  } else if (!hasProducer) {
408
475
  checkerWithheld = true;
409
- } else {
476
+ } else if (addChecker) {
410
477
  plan.push({
411
478
  action: 'add',
412
479
  entry: { id: 'coverage-check', title: 'Changed-line coverage + red-proof verification (the final-run checker)', cmd: coverageCmd },
413
480
  reason: 'run-gates --final requires the canonical checker as the LAST declared gate',
414
481
  });
482
+ } else {
483
+ checkerOffered = true;
415
484
  }
416
485
  // An ALREADY-declared checker over no producer is the same dead pair the withhold prevents — an
417
486
  // earlier deployment could have created it. The migration removes no declared gate, so it reports
418
- // the inertness and refuses to call the result final-run-capable.
487
+ // the fact and refuses to call the result final-run-capable.
419
488
  //
420
- // The two checker kinds need DIFFERENT questions, and asking one question would be wrong for one
421
- // of them. A canonical checker always ENDS UP LAST here — added last, or moved last — so "a
422
- // producer exists at all" and "a producer runs before it" are the same fact. A VENDORED checker is
423
- // deliberately left where the deployment put it, so for that row the question is POSITIONAL: a
424
- // producer declared AFTER it writes the lcov the checker has already read past, and counting it
425
- // would report a live pair over one that certifies nothing.
426
- // Tracked PER ROW, not as one flag: the renderer has to name the edit for the row it is talking
427
- // about, and a single boolean is what let one preview demand a removal and a reorder at once.
489
+ // The question is POSITIONAL for both checker kinds: a canonical checker always ENDS UP LAST here
490
+ // (moved last), so its producers are every kept row; a VENDORED checker is left where the
491
+ // deployment put it, so a producer declared AFTER it writes the lcov it has already read past.
492
+ // Tracked PER ROW: the renderer names the edit for the row it is talking about.
428
493
  const inertExternalRows = new Set(
429
494
  externalCoverageChecks.filter(({ row }) => !kept.slice(0, kept.indexOf(row)).some(isProducerRow)).map(({ row }) => row),
430
495
  );
431
- // The canonical checker's ONLY inert cause is that nothing produces at all — it always ends up
432
- // last — so its sentence never has to speak about order.
433
496
  const canonicalCheckerInert = checkerRow !== null && !hasProducer;
434
497
  const checkerInert = canonicalCheckerInert || inertExternalRows.size > 0;
435
498
  // `--final` accepts EXACTLY ONE canonical checker, so a declaration carrying two is not
@@ -437,15 +500,17 @@ export const buildMigrationPlan = (gates, kitToolsDir, projectDir) => {
437
500
  // so it names the duplication and withholds the claim instead of over-promising a green.
438
501
  const duplicateCheckers = checkerRows.length;
439
502
  const reviewStateCandidate = `{ "id": "review-state", "title": "Review receipts converged (D3(b))", "cmd": "node \\"${join(kitToolsDir, 'review-state.mjs')}\\" --check" }`;
503
+ // finalCapable judges the result with the offered add landed: the offer line carries the one step left.
440
504
  return {
441
505
  plan,
442
506
  customized,
443
507
  unitTestsExtended,
444
508
  finalCapable:
445
- hasReviewState && !checkerWithheld && !checkerInert && duplicateCheckers <= 1 && externalCoreChecks.length === 0,
509
+ hasReviewState && !checkerWithheld && collision === null && !checkerInert && duplicateCheckers <= 1 && externalCoreChecks.length === 0,
446
510
  hasProducer,
447
511
  hasReviewState,
448
512
  checkerWithheld,
513
+ checkerOffered,
449
514
  checkerInert,
450
515
  duplicateCheckers,
451
516
  // The plan ROW is an internal handle (the move arm mutates it) — consumers get the facts only.
@@ -460,10 +525,12 @@ export const buildMigrationPlan = (gates, kitToolsDir, projectDir) => {
460
525
  inert: inertExternalRows.has(row),
461
526
  })),
462
527
  canonicalCheckerInert,
528
+ canonicalCheckerId: checkerRow?.entry.id ?? null,
463
529
  reviewStateCandidate,
464
530
  collision,
465
531
  repoints,
466
532
  withheld: kit.withheld,
533
+ guardKept,
467
534
  };
468
535
  };
469
536
 
@@ -476,16 +543,22 @@ export const resultingGates = (plan) => {
476
543
 
477
544
  const MARKER_LANE = 'or, if your suite cmd already writes that lcov in a form this check cannot recognise, add "lcovProducer": true to that gate in docs/ai/gates.json';
478
545
 
479
- // The per-entry customized recovery: a unit-tests-class entry gets the FULL canonical flag set
480
- // (the intent is known — the cmd shape just cannot be verified); anything else gets the
481
- // dead-tool recovery.
482
- const customizedRecovery = (gate) =>
483
- gate.id === 'unit-tests'
484
- ? `declare the canonical suite gate by hand so the coverage contract is verifiable: node --test ${UNIT_TESTS_COVERAGE_FLAGS} <your test paths> — ${MARKER_LANE}`
546
+ // The per-entry customized recovery: a unit-tests-class entry — the unit-tests id, or an earlier
547
+ // kit's producer form under any id — gets the command's suite line (the intent is known — the cmd
548
+ // shape just cannot be verified); a legacy check whose target stands gets the hand decision; anything else the dead-tool recovery.
549
+ const customizedRecovery = (gate) => {
550
+ if (gate.id === 'unit-tests' || retiredProducerFormOf(gate.cmd) !== null) {
551
+ return `declare the canonical suite gate by hand so the coverage contract is verifiable: ${SUITE_LINE} — ${MARKER_LANE}`;
552
+ }
553
+ const legacy = LEGACY_FORMS.find((f) => f.re.test(gate.cmd.trim()));
554
+ return legacy
555
+ ? `the ${legacy.name} check is retired, but its target is not proven absent (something stands at that path, or its token is one the kit does not resolve) — remove the entry by hand if it runs the retired tool; if it is your own check, move its file to a path that does not contain ${legacy.name} and point the gate at it.`
485
556
  : 'remove the entry, or repoint it at a living check — the review-ledger / fold-completeness tools no longer exist.';
557
+ };
486
558
 
487
- const warningLines = ({ customized, finalCapable, hasReviewState = finalCapable, hasProducer = false, checkerWithheld = false, canonicalCheckerInert = false, duplicateCheckers = 0, externalCoreChecks = [], reviewStateCandidate, repoints = [], withheld = [] }) => {
559
+ const warningLines = ({ customized, finalCapable, hasReviewState = finalCapable, checkerWithheld = false, checkerOffered = false, canonicalCheckerInert = false, canonicalCheckerId = 'coverage-check', duplicateCheckers = 0, externalCoreChecks = [], reviewStateCandidate, repoints = [], withheld = [], guardKept = [], collision = null, addCheckerHint = 'this migration with --apply --add-checker' }) => {
488
560
  const lines = [];
561
+ for (const kept of guardKept) lines.push(guardLine(kept));
489
562
  for (const { id, path } of withheld) lines.push(` WARNING: ${id} runs a kit check, but the kit folder is not current (${path}) — kept as declared; refresh the kit's scripts, then re-run this migration.`);
490
563
  for (const { id, repoint } of repoints) lines.push(` REPOINT (untouched): ${id}: run ${repoint} in place of its invocation of that check, its arguments kept.`);
491
564
  for (const gate of customized) {
@@ -505,33 +578,22 @@ const warningLines = ({ customized, finalCapable, hasReviewState = finalCapable,
505
578
  ? ` the INSTALLED ${name} check is declared here too, so repointing this cmd would leave TWO — run-gates --final accepts exactly ONE canonical check. Remove THIS entry by hand and keep the canonical one.`
506
579
  : ` run-gates --final anchors on the installed copy by realpath, so the result is NOT final-run-capable while this entry stands: either repoint the cmd at ${installed}, or upgrade through the kit that owns the copy it names.`,
507
580
  );
508
- // The inertness of THIS row, said on THIS row, with exactly one edit attached — and when the
509
- // entry is already destined for removal, no second edit at all.
510
- if (inert && canonicalTwin) {
511
- lines.push(' it is also INERT as declared — nothing produces the lcov before it — and removing it, as above, is the ONE edit that resolves both.');
512
- } else if (inert && hasProducer) {
513
- lines.push(' it is also INERT as declared: a gate DOES produce the lcov, but it runs AFTER this entry, so this checker reads nothing (or stale bytes) and passes while verifying nothing — a checker belongs LAST, after its producer.');
514
- } else if (inert) {
515
- lines.push(` it is also INERT as declared: no declared gate PRODUCES the lcov it reads, so it passes while verifying nothing — declare the suite gate: node --test ${UNIT_TESTS_COVERAGE_FLAGS} <your test paths> — ${MARKER_LANE}`);
516
- }
581
+ // The fact of THIS row, said on THIS row, with its one remedy — the removal above when a canonical twin stands.
582
+ if (inert) lines.push(` it also reads as inert: ${POSITIONAL_FACT} — ${canonicalTwin ? 'removing it, as above, is the one edit' : CHECKER_REMEDY}`);
517
583
  }
518
584
  if (externalCoreChecks.length) {
519
585
  // The same consequence the customized block carries, for the same reason: a declaration --final
520
586
  // refuses mints no receipt, and the commit guard then refuses every commit.
521
587
  lines.push(' IMPORTANT: do NOT install the commit guard while the entr(ies) above stand — a declaration that cannot pass run-gates --final would block every commit.');
522
588
  }
523
- if (checkerWithheld) {
524
- lines.push(' WARNING: the canonical coverage-check gate was NOT added — no declared gate would PRODUCE the lcov it reads, and a checker with no producer passes while verifying nothing. Declare the suite gate first, then re-run this migration:');
525
- lines.push(` node --test ${UNIT_TESTS_COVERAGE_FLAGS} <your test paths>`);
526
- lines.push(` ${MARKER_LANE}, then re-run this migration`);
527
- }
528
- // The CANONICAL checker's inertness only. An external row's is said on the row itself above, with
529
- // the edit that fits that row — this block would otherwise add a second, contradictory one.
530
- if (canonicalCheckerInert) {
531
- lines.push(' WARNING: the DECLARED coverage-check gate is INERT — no declared gate PRODUCES the lcov it reads, so it passes while verifying nothing. Nothing is removed for you; declare the suite gate:');
532
- lines.push(` node --test ${UNIT_TESTS_COVERAGE_FLAGS} <your test paths>`);
533
- lines.push(` ${MARKER_LANE}`);
589
+ if (collision !== null) {
590
+ lines.push(` WARNING: the canonical coverage-check gate was not added — a row that is not the checker already holds the id ${collision}: rename that row by hand.`);
534
591
  }
592
+ if (checkerWithheld) lines.push(` WARNING: the canonical coverage-check gate was not added — ${WITHHELD_FACT}; ${CHECKER_REMEDY}`);
593
+ // The coverage check is optional: its add is the one step that waits for the user's explicit yes.
594
+ if (checkerOffered) lines.push(` OFFER coverage-check: a declared gate is a producer this kit reads and no checker is declared — on the user's explicit yes, add the canonical checker last: ${addCheckerHint}`);
595
+ // The CANONICAL checker's fact only; an external row's is said on the row itself above.
596
+ if (canonicalCheckerInert) lines.push(` WARNING: the declared coverage checker (${canonicalCheckerId}): ${POSITIONAL_FACT} — ${CHECKER_REMEDY}`);
535
597
  if (duplicateCheckers > 1) {
536
598
  lines.push(` WARNING: ${duplicateCheckers} declared gates are the canonical coverage checker — run-gates --final accepts EXACTLY ONE, so the result is NOT final-run-capable. Nothing is removed for you; keep a single checker and delete the rest by hand.`);
537
599
  }
@@ -545,27 +607,28 @@ const warningLines = ({ customized, finalCapable, hasReviewState = finalCapable,
545
607
  return lines;
546
608
  };
547
609
 
610
+ // Each acted row, printed alike by the preview and the apply: its action, id, cmd and its reason (a moved or removed gate's `was:`).
611
+ const actedLines = (plan) => plan.filter((r) => r.action !== 'keep').map((r) => ` ${r.action.toUpperCase()} ${r.entry.id}: ${r.entry.cmd} (${r.reason})`);
612
+
548
613
  export const formatPreview = (analysis, applyHint) => {
549
- const { plan, unitTestsExtended, finalCapable, hasProducer = unitTestsExtended, retiredStores = [] } = analysis;
614
+ const { plan, unitTestsExtended, finalCapable, checkerOffered = false, hasProducer = unitTestsExtended, retiredStores = [] } = analysis;
550
615
  const lines = ['[agent-workflow] legacy gates.json migration preview (dry-run — nothing was written):'];
551
- const acted = plan.filter((r) => r.action !== 'keep');
552
- for (const r of acted) {
553
- lines.push(` ${r.action.toUpperCase()} ${r.entry.id}: ${r.entry.cmd} (${r.reason})`);
554
- }
616
+ const acted = actedLines(plan);
617
+ lines.push(...acted);
555
618
  for (const p of retiredStores) {
556
619
  lines.push(` CLEAN ${p} (a retired kit-owned store the deleted machinery wrote — dead data, unlinked on apply)`);
557
620
  }
558
621
  if (!acted.length && !retiredStores.length) {
559
622
  lines.push(
560
- finalCapable
623
+ finalCapable && !checkerOffered
561
624
  ? ' nothing to migrate — no canonical legacy entries, no retired stores, and the declaration is already final-run-capable.'
562
- : ' nothing to migrate mechanically — no canonical legacy entries and no retired stores; the warnings below still need a hand.',
625
+ : ' nothing to migrate mechanically — no canonical legacy entries and no retired stores; the lines below still need a hand.',
563
626
  );
564
627
  }
565
628
  // Keyed on the ID, but a PRODUCER is recognized under any id — repeating this advice over a
566
629
  // working producer sends the user to fix nothing.
567
630
  if (!hasProducer && !unitTestsExtended && !plan.some((r) => r.entry.id === 'unit-tests')) {
568
- lines.push(' note: no canonical `unit-tests` entry found — declare your suite gate with the lcov reporters by hand (the coverage-check gate reads the file it produces).');
631
+ lines.push(` note: no canonical \`unit-tests\` entry found — declare your suite gate by hand as ${SUITE_LINE} (the coverage-check gate reads the lcov it produces).`);
569
632
  }
570
633
  lines.push(...warningLines(analysis));
571
634
  if (acted.length || retiredStores.length) {
@@ -637,11 +700,12 @@ const writeAtomic = (cwd, body, lstatFn) => {
637
700
  };
638
701
 
639
702
  export const parseArgs = (argv) => {
640
- const args = { cwd: process.cwd(), apply: false, kitTools: null, help: false };
703
+ const args = { cwd: process.cwd(), apply: false, addChecker: false, kitTools: null, help: false };
641
704
  for (let i = 0; i < argv.length; i += 1) {
642
705
  const a = argv[i];
643
706
  if (a === '--help' || a === '-h') args.help = true;
644
707
  else if (a === '--apply') args.apply = true;
708
+ else if (a === '--add-checker') args.addChecker = true;
645
709
  else if (a === '--dry-run') args.apply = false;
646
710
  else if (a === '--cwd') {
647
711
  i += 1;
@@ -656,20 +720,23 @@ export const parseArgs = (argv) => {
656
720
  return args;
657
721
  };
658
722
 
659
- const HELP = `migrate-gates — the consented legacy gates.json migration (strip-the-kit D8).
723
+ const HELP = `migrate-gates — the legacy gates.json migration (strip-the-kit D8), the kit's mandatory move.
660
724
 
661
725
  Usage:
662
- node migrate-gates.mjs --kit-tools <installed-kit-tools-dir> [--cwd <project>] [--apply]
663
-
664
- Default is a dry-run PREVIEW (writes nothing). --apply rewrites ${GATES_REL} atomically:
665
- canonical legacy entries (review-ledger / fold-completeness --check, matched by their documented
666
- single-invocation forms) are REMOVED; the canonical unit-tests cmd gains the built-in lcov
667
- reporters; the coverage-check gate is ADDED last (resolved, QUOTED path) — and WITHHELD, loudly,
668
- when no declared gate produces the lcov it reads. A kit-check gate over a current kit folder is
669
- SWITCHED in place to node scripts/agent-workflow/run.mjs <name>, unless it is a customized entry below,
670
- a flat scripts/<file> only when nothing stands at that path; any other form naming a kit check is kept, named with its repoint. Customized entries are
671
- NEVER auto-touched — the preview names each with a paste-ready recovery, and the commit guard
672
- must not be installed until they are resolved.`;
726
+ node migrate-gates.mjs --kit-tools <installed-kit-tools-dir> [--cwd <project>] [--apply [--add-checker]]
727
+
728
+ Default is a dry-run PREVIEW (writes nothing, --add-checker included). --apply rewrites ${GATES_REL}
729
+ atomically with every mechanical row, the upgrade's gates-migration step running it with no question:
730
+ a canonical legacy entry (review-ledger / fold-completeness --check, matched by its documented
731
+ single-invocation form) is REMOVED when its target is proven absent; the canonical unit-tests cmd and
732
+ every earlier kit's producer form run through ${COVERAGE_PRODUCER_BODY} (while the kit folder holds this
733
+ kit's command and reporter); a kit-check gate over a current kit folder is SWITCHED in place to
734
+ node scripts/agent-workflow/run.mjs <name>, unless it is a customized entry below, a flat scripts/<file>
735
+ only when nothing stands at that path; any other form naming a kit check is kept, named with its repoint;
736
+ a declared coverage-check gate is moved last. The coverage-check gate is ADDED last (resolved, QUOTED path)
737
+ only with --add-checker, on the user's explicit yes, and only when a declared gate produces the lcov it
738
+ reads. Customized entries are NEVER auto-touched — each is named with a paste-ready recovery, and the
739
+ commit guard must not be installed until they are resolved.`;
673
740
 
674
741
  export const main = (argv = process.argv.slice(2), io = {}) => {
675
742
  const out = io.log ?? console.log;
@@ -699,14 +766,10 @@ export const main = (argv = process.argv.slice(2), io = {}) => {
699
766
  return 0;
700
767
  }
701
768
  const parsed = declaration.outcome === 'loaded' ? declaration.parsed : { gates: [] };
702
- const analysis = { ...buildMigrationPlan(parsed.gates, kitTools, resolve(args.cwd)), retiredStores };
703
- if (analysis.collision) {
704
- throw stop(
705
- `id collision — a NON-canonical entry already uses id "${analysis.collision}"; resolve it by hand first ` +
706
- '(two rows under the checker id would be ambiguous — the canonical checker is never added alongside a customized twin)',
707
- );
708
- }
709
- const applyHint = `node "${fileURLToPath(import.meta.url)}" --kit-tools "${kitTools}" --cwd "${args.cwd}" --apply`;
769
+ const command = `node "${fileURLToPath(import.meta.url)}" --kit-tools "${kitTools}" --cwd "${args.cwd}"`;
770
+ const addCheckerHint = `${command} --apply --add-checker`;
771
+ const analysis = { ...buildMigrationPlan(parsed.gates, kitTools, resolve(args.cwd), { addChecker: args.addChecker }), retiredStores, addCheckerHint };
772
+ const applyHint = args.addChecker ? addCheckerHint : `${command} --apply`;
710
773
  if (!args.apply) {
711
774
  out(formatPreview(analysis, applyHint));
712
775
  return 0;
@@ -715,6 +778,7 @@ export const main = (argv = process.argv.slice(2), io = {}) => {
715
778
  if (acted.length && declaration.outcome === 'loaded') {
716
779
  const merged = { ...parsed, gates: resultingGates(analysis.plan) };
717
780
  const writtenPath = writeAtomic(args.cwd, `${JSON.stringify(merged, null, 2)}\n`, lstatFn);
781
+ for (const line of actedLines(analysis.plan)) out(line);
718
782
  out(`[agent-workflow] migrated ${writtenPath}: ${acted.map((r) => `${r.action} ${r.entry.id}`).join(', ')}`);
719
783
  }
720
784
  for (const p of retiredStores) {
@@ -729,9 +793,9 @@ export const main = (argv = process.argv.slice(2), io = {}) => {
729
793
  for (const line of warningLines(analysis)) out(line);
730
794
  if (!acted.length && !retiredStores.length) {
731
795
  out(
732
- analysis.finalCapable
796
+ analysis.finalCapable && !analysis.checkerOffered
733
797
  ? '[agent-workflow] nothing to migrate — the declaration is already final-run-capable and no retired stores remain.'
734
- : '[agent-workflow] nothing to migrate mechanically — no canonical legacy entries and no retired stores remain; the warnings above still need a hand.',
798
+ : '[agent-workflow] nothing to migrate mechanically — no canonical legacy entries and no retired stores remain; the lines above still need a hand.',
735
799
  );
736
800
  }
737
801
  return 0;