@sabaiway/agent-workflow-kit 20.2.0 → 22.0.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.
Files changed (98) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +7 -5
  3. package/SKILL.md +1 -1
  4. package/bin/install.mjs +10 -11
  5. package/capability.json +1 -1
  6. package/launchers/windsurf-workflow.md +3 -1
  7. package/migrations/3.0.0-hardened-core-loop.md +7 -6
  8. package/package.json +5 -2
  9. package/references/advisor-writers.md +1 -1
  10. package/references/contracts.md +11 -10
  11. package/references/modes/bootstrap.md +3 -3
  12. package/references/modes/commit-guard.md +1 -1
  13. package/references/modes/gates.md +2 -2
  14. package/references/modes/recommendations.md +3 -3
  15. package/references/modes/upgrade.md +6 -6
  16. package/references/scripts/{archive-caps.mjs → archives/archive-caps.mjs} +1 -1
  17. package/references/scripts/{archive-changelog.mjs → archives/archive-changelog.mjs} +7 -9
  18. package/references/scripts/{archive-decisions.mjs → archives/archive-decisions.mjs} +13 -10
  19. package/references/scripts/{archive-issues.mjs → archives/archive-issues.mjs} +7 -8
  20. package/references/scripts/{check-docs-size.mjs → docs-size/check-docs-size.mjs} +3 -4
  21. package/references/scripts/docs-size/index.mjs +2 -0
  22. package/references/scripts/family.json +45 -0
  23. package/references/scripts/family.mjs +90 -0
  24. package/references/scripts/gates/kit-command-gates.mjs +117 -0
  25. package/references/scripts/{migrate-gates.mjs → gates/migrate-gates.mjs} +263 -182
  26. package/references/scripts/{install-git-hooks.mjs → git-hooks/install-git-hooks.mjs} +50 -38
  27. package/references/scripts/run.mjs +90 -0
  28. package/references/scripts/shared/index.mjs +3 -0
  29. package/references/scripts/shared/project-root.mjs +11 -0
  30. package/references/scripts/spec-schema/index.mjs +2 -0
  31. package/references/scripts/test-reporter/reporter.mjs +130 -0
  32. package/references/shared/composition-handoff.md +1 -1
  33. package/references/shared/deploy-tail.md +2 -2
  34. package/references/templates/SPEC_TEMPLATE.md +1 -1
  35. package/references/templates/adr-record.md +3 -3
  36. package/tools/apply-danger-check.mjs +9 -5
  37. package/tools/atomic-write.mjs +3 -1
  38. package/tools/coverage-producer.mjs +76 -41
  39. package/tools/direct-run.mjs +2 -0
  40. package/tools/distribution-files/retired.mjs +99 -0
  41. package/tools/distribution-files/scripts.mjs +68 -52
  42. package/tools/ensure-configs.mjs +21 -21
  43. package/tools/ensure-ops.mjs +60 -18
  44. package/tools/ensure-specs.mjs +85 -47
  45. package/tools/ensure-vocabulary.mjs +4 -4
  46. package/tools/epic-shape-cli.mjs +1 -1
  47. package/tools/epic-shape-ledger.mjs +1 -1
  48. package/tools/epic-shape.mjs +1 -1
  49. package/tools/family-registry.mjs +3 -1
  50. package/tools/feedback-record-cli.mjs +1 -1
  51. package/tools/fold-scope.mjs +2 -2
  52. package/tools/gates-declaration.mjs +22 -14
  53. package/tools/gates-init.mjs +33 -17
  54. package/tools/git-hooks.mjs +90 -65
  55. package/tools/jev-connect.mjs +1 -1
  56. package/tools/jev-guide.mjs +1 -1
  57. package/tools/jev-skill.mjs +1 -1
  58. package/tools/known-footprint.mjs +7 -29
  59. package/tools/node-evidence.mjs +29 -15
  60. package/tools/now-cli.mjs +1 -1
  61. package/tools/payload-prune.mjs +53 -58
  62. package/tools/plan-shape-cli.mjs +1 -1
  63. package/tools/plan-shape.mjs +1 -1
  64. package/tools/project-rules/rules-record.mjs +1 -1
  65. package/tools/queue-audit-cli.mjs +1 -1
  66. package/tools/queue-audit.mjs +2 -2
  67. package/tools/queue-purge-archive.mjs +1 -1
  68. package/tools/queue-purge-cli.mjs +1 -1
  69. package/tools/queue-purge.mjs +1 -1
  70. package/tools/recommendations.mjs +37 -25
  71. package/tools/script-priors.mjs +31 -3
  72. package/tools/source-size/piles.mjs +1 -1
  73. package/tools/spec-adoption.mjs +1 -1
  74. package/tools/spec-check-ops.mjs +2 -2
  75. package/tools/spec-check.mjs +2 -2
  76. package/tools/spec-coverage.mjs +1 -1
  77. package/tools/tier-guide.mjs +1 -1
  78. package/tools/transition/index.mjs +1 -1
  79. package/tools/upgrade-runlist.mjs +3 -3
  80. package/tools/write-lanes.mjs +2 -2
  81. package/references/scripts/_expect-shim.mjs +0 -41
  82. package/references/scripts/archive-caps.test.mjs +0 -321
  83. package/references/scripts/archive-changelog.test.mjs +0 -560
  84. package/references/scripts/archive-conservation.test.mjs +0 -466
  85. package/references/scripts/archive-decisions.test.mjs +0 -1503
  86. package/references/scripts/archive-issues.test.mjs +0 -825
  87. package/references/scripts/archiver-structure.test.mjs +0 -84
  88. package/references/scripts/check-docs-size-cli.test.mjs +0 -325
  89. package/references/scripts/check-docs-size-ensure.test.mjs +0 -360
  90. package/references/scripts/check-docs-size.test.mjs +0 -395
  91. package/references/scripts/install-git-hooks-repo-exec.test.mjs +0 -185
  92. package/references/scripts/install-git-hooks.test.mjs +0 -241
  93. package/references/scripts/markdown-blocks.test.mjs +0 -310
  94. package/references/scripts/migrate-gates-branches.test.mjs +0 -302
  95. package/references/scripts/migrate-gates.test.mjs +0 -517
  96. package/references/scripts/spec-schema.test.mjs +0 -352
  97. /package/references/scripts/{markdown-blocks.mjs → shared/markdown-blocks.mjs} +0 -0
  98. /package/references/scripts/{spec-schema.mjs → spec-schema/spec-schema.mjs} +0 -0
@@ -27,7 +27,7 @@
27
27
 
28
28
  import { readFileSync, lstatSync, unlinkSync } from 'node:fs';
29
29
  import { spawnSync } from 'node:child_process';
30
- import { join } from 'node:path';
30
+ import { join, posix } from 'node:path';
31
31
  import { CONFIG_REL, SEED_CONFIG, loadConfig } from './orchestration-config.mjs';
32
32
  import { NOTE_ROUTE, readmeState, withCurrentReadme } from './orchestration-readme.mjs';
33
33
  import { seedConfig, writeConfig } from './orchestration-write.mjs';
@@ -36,9 +36,9 @@ import { GATES_REL } from './gates-declaration.mjs';
36
36
  import { AUTONOMY_REL } from './autonomy-config.mjs';
37
37
  import { VEHICLES_REL } from './vehicle-settings.mjs';
38
38
  import { ENSURE_TOKENS, FAILURE_CAUSES } from './ensure-vocabulary.mjs';
39
- import { NODE_EVIDENCE, describeNodeProbes, probeNodeEvidence } from './node-evidence.mjs';
39
+ import { DEPLOYED_SCRIPTS, NODE_EVIDENCE, describeNodeProbes, probeNodeEvidence } from './node-evidence.mjs';
40
40
  import { classifyDeployedScript } from './script-priors.mjs';
41
- import { parseFrontmatter } from '../references/scripts/check-docs-size.mjs';
41
+ import { parseFrontmatter } from '../references/scripts/docs-size/index.mjs';
42
42
 
43
43
  // The closed vocabulary lives in its own PURE leaf so the read-only doc-parity lint can bind the
44
44
  // relayed token set without importing this module's writer graph. Re-exported here because every
@@ -231,7 +231,9 @@ export const nodeEvidenceRefusal = (op, cwd, lstat) => {
231
231
  // the one-generator rule exists to prevent. Under a hook module that is not the bundled one, the
232
232
  // project's own checker judges the navigator and a write it rejects is put back (spec docs-navigator).
233
233
  const INDEX_REL = 'docs/ai/index.md';
234
- const GENERATOR_PATH = ['references', 'scripts', 'check-docs-size.mjs'];
234
+ // The docs checker is the docs-size module's one deployed entry: bundled, it is the generator; deployed,
235
+ // the kept probe. A flat scripts/check-docs-size.mjs is no deployed checker (story S4 reads it).
236
+ const CHECKER = DEPLOYED_SCRIPTS.find(({ module }) => module === 'docs-size');
235
237
  const ENSURE_INDEX_OUTCOME = /^ensure-index: (regenerated|already-current)\b/m;
236
238
  const ENSURE_INDEX_REFUSAL = /^ensure-index: (write-refused|probe-failed)\b/m;
237
239
  // The probe has no machine line, so its two ANSWERS are matched against the canonical sentences it
@@ -247,28 +249,68 @@ const describeExit = (result) => (result.signal ? `on signal ${result.signal}` :
247
249
  const bothStreams = (result) => `${String(result.stdout ?? '')}${String(result.stderr ?? '')}`.trim();
248
250
  const describeExitWithOutput = (result, subject = 'it') => `${subject} exited ${describeExit(result)}${bothStreams(result) ? `: ${bothStreams(result)}` : ''}`;
249
251
 
250
- const HOOK_MODULES = ['check-docs-size.mjs', 'spec-schema.mjs'];
251
- const KEPT_JUDGE = `the project's own checker (${SCRIPTS_DIR}/check-docs-size.mjs --check-index)`;
252
+ const KEPT_JUDGE = `the project's own checker (${CHECKER.deployed} --check-index)`;
252
253
  const KEPT_FITS = `in sync under ${KEPT_JUDGE} and within the maxLines it stamps`;
253
254
  const KEPT_ROUTE = "the spec layer's write of the bundled modules the project's hook loads, then this step again";
254
255
  const KEPT_PROBE_TIMEOUT_MS = 30_000;
255
256
  const countLines = (text) => text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
256
257
  const readStampedCap = (text) => { const value = parseFrontmatter(text)?.maxLines; const cap = value ? Number(value) : NaN; return Number.isNaN(cap) ? undefined : cap; };
257
258
 
258
- const surveyHookModule = (cwd, kitRoot, name, read, lstat) => {
259
- const rel = `${SCRIPTS_DIR}/${name}`;
260
- const probe = (() => { try { return probeSeedTarget(join(cwd, rel), lstat); } catch (err) { if (err?.code === 'ENOTDIR') return { present: false }; throw err; } })();
261
- if (probe.wrongKind || !probe.present) return { rel, state: probe.wrongKind ? 'wrong-kind' : 'absent', wrongKind: probe.wrongKind };
262
- const deployed = read(join(cwd, rel));
263
- try {
264
- return { rel, state: classifyDeployedScript(deployed, name, read(join(kitRoot, ...GENERATOR_PATH.slice(0, 2), name))) };
265
- } catch (err) {
266
- return { rel, state: 'bundle-unreadable', error: causeOf(err) };
259
+ const DEPLOYED_BY_PATH = new Map(DEPLOYED_SCRIPTS.map((entry) => [entry.path, entry]));
260
+ const RELATIVE_IMPORT = /(?:\bfrom\s*|\bimport\s*\(?\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
261
+ const pathIn = (root, rel) => join(root, ...rel.split('/'));
262
+
263
+ // The one reading of the family's bundled imports, shared by the index, scripts and specs ops: the deployed
264
+ // manifest paths `bundle` (the bytes at manifest path `path`) imports by a relative specifier.
265
+ export const bundledImportsOf = (path, bundle) => [...String(bundle).matchAll(RELATIVE_IMPORT)]
266
+ .map(([, spec]) => posix.join(posix.dirname(path), spec)).filter((dep) => DEPLOYED_BY_PATH.has(dep));
267
+ // Each of `files` ({ path, imports }) after every one of them it imports, by manifest path in code-unit order
268
+ // otherwise, so each file a run leaves loads. A cycle is a broken bundle, never a silent order.
269
+ export const dependenciesFirst = (files) => {
270
+ const left = new Map(files.map((f) => [f.path, f]));
271
+ const out = [];
272
+ while (left.size > 0) {
273
+ const next = [...left.values()].sort((a, b) => (a.path < b.path ? -1 : 1)).find((f) => f.imports.every((dep) => !left.has(dep)));
274
+ if (!next) throw new Error(`the bundled scripts import one another in a cycle: ${[...left.keys()].join(', ')} — reinstall the kit`);
275
+ out.push(next);
276
+ left.delete(next.path);
267
277
  }
278
+ return out;
279
+ };
280
+
281
+ // The modules the project's hook loads, the checker first: the deployed files of the docs-size and
282
+ // spec-schema modules, and the shared files the checker reaches through its bundled relative imports.
283
+ const hookModulesOf = (bundleOf) => {
284
+ const reached = new Set([CHECKER.path]);
285
+ for (const path of reached) for (const dep of bundledImportsOf(path, bundleOf(DEPLOYED_BY_PATH.get(path)).bytes ?? '')) reached.add(dep);
286
+ const loaded = ({ module, path }) => module === 'docs-size' || module === 'spec-schema' || (module === 'shared' && reached.has(path));
287
+ return [CHECKER, ...DEPLOYED_SCRIPTS.filter((entry) => entry !== CHECKER && loaded(entry))];
288
+ };
289
+
290
+ // A regular file where a folder on the way belongs (ENOTDIR) holds no module.
291
+ const probeHookModule = (cwd, entry, lstat) => { try { return probeSeedTarget(pathIn(cwd, entry.deployed), lstat); } catch (err) { if (err?.code === 'ENOTDIR') return { present: false }; throw err; } };
292
+
293
+ // → one { rel, state } per hook module: absent, wrong-kind, bundle-unreadable or the classifier's word.
294
+ // No deployed checker → that one entry, absent; every kind is probed before any project file is read.
295
+ const surveyHook = (cwd, kitRoot, read, lstat) => {
296
+ const checker = probeHookModule(cwd, CHECKER, lstat);
297
+ if (checker.wrongKind || !checker.present) return [{ rel: CHECKER.deployed, state: checker.wrongKind ? 'wrong-kind' : 'absent', wrongKind: checker.wrongKind }];
298
+ const bundles = new Map();
299
+ const readBundle = (entry) => { try { return { bytes: read(pathIn(kitRoot, entry.bundled)) }; } catch (err) { return { error: causeOf(err) }; } };
300
+ const bundleOf = (entry) => (bundles.has(entry.path) ? bundles : bundles.set(entry.path, readBundle(entry))).get(entry.path);
301
+ const probes = hookModulesOf(bundleOf).map((entry) => ({ entry, rel: entry.deployed, probe: entry === CHECKER ? checker : probeHookModule(cwd, entry, lstat) }));
302
+ const wrong = probes.find(({ probe }) => probe.wrongKind);
303
+ if (wrong) return [{ rel: wrong.rel, state: 'wrong-kind', wrongKind: wrong.probe.wrongKind }];
304
+ return probes.map(({ entry, rel, probe }) => {
305
+ if (!probe.present) return { rel, state: 'absent' };
306
+ const deployed = read(pathIn(cwd, entry.deployed));
307
+ const { bytes, error } = bundleOf(entry);
308
+ return error === undefined ? { rel, state: classifyDeployedScript(deployed, entry.path, bytes) } : { rel, state: 'bundle-unreadable', error };
309
+ });
268
310
  };
269
311
 
270
312
  const judgeKept = ({ cwd, spawn, read, lstat, deps }) => {
271
- const result = spawn(process.execPath, [join(cwd, SCRIPTS_DIR, 'check-docs-size.mjs'), '--check-index'], { cwd, encoding: 'utf8', timeout: deps.keptProbeTimeoutMs ?? KEPT_PROBE_TIMEOUT_MS, killSignal: 'SIGKILL' });
313
+ const result = spawn(process.execPath, [pathIn(cwd, CHECKER.deployed), '--check-index'], { cwd, encoding: 'utf8', timeout: deps.keptProbeTimeoutMs ?? KEPT_PROBE_TIMEOUT_MS, killSignal: 'SIGKILL' });
272
314
  if (result.error) return { error: `${causeOf(result.error)}${result.signal ? `, killed on signal ${result.signal}` : ''}` };
273
315
  if (result.status !== 0) return { accepted: false, said: describeExitWithOutput(result), half: 'its index check' };
274
316
  const text = lstatNoFollow(join(cwd, INDEX_REL), lstat)?.isFile() ? String(read(join(cwd, INDEX_REL), 'utf8')) : null;
@@ -329,7 +371,7 @@ export const ensureIndex = ({ cwd, kitRoot, dryRun = false, deps = {} }) => {
329
371
  const lstat = deps.lstat ?? lstatSync;
330
372
  const read = deps.readFile ?? readFileSync;
331
373
  const spawn = deps.spawnSync ?? spawnSync;
332
- const generator = join(kitRoot, ...GENERATOR_PATH);
374
+ const generator = pathIn(kitRoot, CHECKER.bundled);
333
375
  const drive = (mode) => spawn(process.execPath, [generator, mode, `--root=${cwd}`], { encoding: 'utf8' });
334
376
  const unlaunchable = (result) =>
335
377
  loud('index', 'generator-unlaunchable', `${INDEX_REL}: the bundled generator could not be started, so nothing was probed or written — reinstall the kit. ${causeOf(result.error)}`);
@@ -338,7 +380,7 @@ export const ensureIndex = ({ cwd, kitRoot, dryRun = false, deps = {} }) => {
338
380
  if (probe.wrongKind) {
339
381
  return loud('index', 'wrong-node-kind', `${INDEX_REL}: exists but is ${probe.wrongKind} — the navigator is a generated file and this is not one; nothing was read or written, resolve it by hand and re-run`);
340
382
  }
341
- const hook = HOOK_MODULES.reduce((acc, name) => (acc[0]?.state === 'absent' || acc[0]?.wrongKind ? acc : [...acc, surveyHookModule(cwd, kitRoot, name, read, lstat)]), []);
383
+ const hook = surveyHook(cwd, kitRoot, read, lstat);
342
384
  const wrong = hook.find((entry) => entry.state === 'wrong-kind');
343
385
  if (wrong) return loud('index', 'wrong-node-kind', `${wrong.rel}: exists but is ${wrong.wrongKind} — the project's hook loads it, so nothing was read or written; resolve it by hand and re-run`);
344
386
  const kept = hook[0].state !== 'absent' && !hook.every((entry) => entry.state === 'current');
@@ -1,53 +1,88 @@
1
1
  // ensure-specs.mjs — the SIXTH upgrade ensure: the spec layer (memory 4.6.0, AD-112) kept current on an
2
- // EXISTING deployment. Four deployed scripts (the pairs script-priors.mjs names; every other kit script
3
- // is the scripts ensure's) and one store root, by the scripts op's rule (distribution-files/): every
4
- // file is surveyed by proof first, then on every plain run a prior body is refreshed and an edited one
5
- // replaced in place, an absent one placed create-only and an absent store root seeded create-only, with
6
- // no question and no copy kept; a current file is left. The writes run in a FIXED order:
7
- // 1. the reader pair scripts/spec-schema.mjs + .test.mjs
8
- // 2. the checker pair scripts/check-docs-size.mjs + .test.mjs
9
- // 3. the store root docs/ai/specs/index.md (placeholders rendered)
10
- // Why the order: the kit's bundled navigator generator collapses `specs/` into one row, while the
11
- // project's pre-commit hook runs ITS deployed checker — an older one renders the store row by row and
12
- // reds `--check-index`. So the checker is written before the spec store, and a write that fails stops
13
- // every later one. The pair lines and the hook-run line are the scripts op's own, from the module's
14
- // index. Each write is idempotent, so a stopped run converges on the next.
2
+ // EXISTING deployment. Its scripts are the reader pair (the deployed entries of the spec-schema module)
3
+ // and the checker pair (the docs-size module's), plus the test reporter and the command, each at its deployed
4
+ // path in the kit folder scripts/agent-workflow/, with the bundled files they import; every other kit script is
5
+ // the scripts ensure's. They and one store root follow the scripts op's rule (distribution-files/): every file is
6
+ // surveyed by proof first, then on every plain run a prior body is refreshed and an edited one replaced
7
+ // in place, an absent one placed create-only and an absent store root seeded create-only, with no
8
+ // question and no copy kept; a current file is left. The writes run in a FIXED order:
9
+ // 1. the files the pairs import scripts/agent-workflow/shared/... (dependencies first)
10
+ // 2. the reader pair scripts/agent-workflow/spec-schema/...
11
+ // 3. the checker pair scripts/agent-workflow/docs-size/check-docs-size.mjs
12
+ // 4. the test reporter scripts/agent-workflow/test-reporter/reporter.mjs
13
+ // 5. the command scripts/agent-workflow/run.mjs, which runs the reporter
14
+ // 6. the store root docs/ai/specs/index.md (placeholders rendered)
15
+ // Why the order: every file is written after the files it imports, so each pair file it leaves loads;
16
+ // the kit's bundled navigator generator collapses `specs/` into one row, while the project's pre-commit
17
+ // hook runs ITS deployed checker — an older one renders the store row by row and reds `--check-index`.
18
+ // So the checker is written before the spec store, and a write that fails stops every later one. The
19
+ // pair lines and the hook-run line are the scripts op's own, from the module's index. Each write is
20
+ // idempotent, so a stopped run converges on the next.
15
21
  //
16
22
  // Dependency-free, Node >= 22. Every fs primitive is injectable (deps.*). No side effects on import.
17
23
 
18
24
  import { readFileSync, lstatSync } from 'node:fs';
19
25
  import { join } from 'node:path';
20
- import { writeContainedFileAtomic, writeProjectFileCreateOnly } from './atomic-write.mjs';
21
- import { CHECKER_PAIR, READER_PAIR, classifyDeployedScript } from './script-priors.mjs';
22
- import { composeFailure, composeOutcome, nodeEvidenceRefusal, probeSeedTarget, tmpNote } from './ensure-ops.mjs';
26
+ import { lstatNoFollow, writeContainedFileAtomic, writeProjectFileCreateOnly } from './atomic-write.mjs';
27
+ import { DEPLOYED_SCRIPTS } from './node-evidence.mjs';
28
+ import { SCRIPT_PRIORS, classifyDeployedScript } from './script-priors.mjs';
29
+ import { bundledImportsOf, composeFailure, composeOutcome, dependenciesFirst, nodeEvidenceRefusal, probeSeedTarget, tmpNote } from './ensure-ops.mjs';
23
30
  import { fileLine, hookLine } from './distribution-files/index.mjs';
24
31
 
25
32
  const OP = 'specs';
26
- const SCRIPTS_DIR = 'scripts';
27
- const BUNDLED_SCRIPTS = ['references', 'scripts'];
33
+ const READER = DEPLOYED_SCRIPTS.filter((e) => e.module === 'spec-schema');
34
+ const CHECKER = DEPLOYED_SCRIPTS.filter((e) => e.module === 'docs-size');
35
+ const REPORTER = DEPLOYED_SCRIPTS.filter((e) => e.module === 'test-reporter');
36
+ const COMMAND = DEPLOYED_SCRIPTS.find((e) => !e.module);
28
37
  const STORE_ROOT_REL = 'docs/ai/specs/index.md';
29
38
  const STORE_ROOT_TEMPLATE = ['references', 'templates', 'specs', 'index.md'];
30
39
  const DATE_PLACEHOLDER = '{{DATE}}';
31
40
 
32
41
  const causeOf = (err) => String((err && err.message) || err);
33
42
  const todayIso = () => new Date().toISOString().slice(0, 10);
43
+ const kindOfDir = (st) => (st.isSymbolicLink() ? 'a symlink' : st.isFile() ? 'a regular file' : 'not a directory');
44
+ const wrongKind = (rel, kind) => composeFailure(OP, 'wrong-node-kind', `${rel}: exists but is ${kind} — nothing was read or written; resolve it by hand, then re-run`);
34
45
 
35
- // ── the survey: five paths classified, nothing written ────────────────────────────────────────────
36
-
37
- // One deployed script → { rel, name, state, bundle }; `wrongKind` carries the node kind for the
38
- // refusal, `prior`/`custom` come from the catalog classifier against the bundled body.
39
- const surveyScript = ({ cwd, kitRoot, name, read, lstat }) => {
40
- const rel = `${SCRIPTS_DIR}/${name}`;
41
- let bundle;
42
- try {
43
- bundle = read(join(kitRoot, ...BUNDLED_SCRIPTS, name));
44
- } catch (err) {
45
- return { rel, name, state: 'bundle-unreadable', error: causeOf(err) };
46
+ // ── the survey: the pairs, the files they import and the store root classified, nothing written ───
47
+
48
+ // The bundled side: the pairs, the reporter, the command and their whole import closure in write order → { files } | { refusal }.
49
+ const readBundles = (kitRoot, read) => {
50
+ const byPath = new Map();
51
+ const queue = [...READER, ...CHECKER, ...REPORTER, COMMAND];
52
+ for (const entry of queue) {
53
+ if (byPath.has(entry.path)) continue;
54
+ let bundle;
55
+ try {
56
+ bundle = read(join(kitRoot, entry.bundled));
57
+ } catch (err) {
58
+ return { refusal: composeFailure(OP, 'bundle-unreadable', `${entry.deployed}: the bundled script could not be read, so nothing was written — reinstall the kit. ${causeOf(err)}`) };
59
+ }
60
+ const imports = bundledImportsOf(entry.path, bundle);
61
+ byPath.set(entry.path, { path: entry.path, rel: entry.deployed, bundle, imports });
62
+ queue.push(...DEPLOYED_SCRIPTS.filter((e) => imports.includes(e.path)));
63
+ }
64
+ const of = (entries) => (path) => entries.some((e) => e.path === path);
65
+ const group = (keep) => dependenciesFirst([...byPath.values()].filter((f) => keep(f.path)));
66
+ const own = [READER, CHECKER, REPORTER].map(of);
67
+ return { files: [...group((p) => !own.some((is) => is(p)) && p !== COMMAND.path), ...own.flatMap(group), ...group((p) => p === COMMAND.path)] };
68
+ };
69
+
70
+ // Each folder on the way to a pair file or a file it imports, lstat-ed without following a link → a refusal or null.
71
+ const folderRefusal = (cwd, files, lstat) => {
72
+ const folders = new Set(files.flatMap((f) => f.rel.split('/').slice(0, -1).map((_, at, parts) => parts.slice(0, at + 1).join('/'))));
73
+ for (const rel of folders) {
74
+ const st = lstatNoFollow(join(cwd, rel), lstat);
75
+ if (st !== null && (!st.isDirectory() || st.isSymbolicLink())) return wrongKind(`${rel}/`, kindOfDir(st));
46
76
  }
47
- const probe = probeSeedTarget(join(cwd, SCRIPTS_DIR, name), lstat);
48
- if (probe.wrongKind) return { rel, name, state: 'wrong-kind', wrongKind: probe.wrongKind, bundle };
49
- if (!probe.present) return { rel, name, state: 'absent', bundle };
50
- return { rel, name, state: classifyDeployedScript(read(join(cwd, SCRIPTS_DIR, name)), name, bundle), bundle };
77
+ return null;
78
+ };
79
+
80
+ // One deployed script → its state against the bundled body, by the catalog seam keyed by manifest path.
81
+ const surveyScript = (cwd, f, deps, read, lstat) => {
82
+ const probe = probeSeedTarget(join(cwd, f.rel), lstat);
83
+ if (probe.wrongKind) return { ...f, state: 'wrong-kind', wrongKind: probe.wrongKind };
84
+ if (!probe.present) return { ...f, state: 'absent' };
85
+ return { ...f, state: classifyDeployedScript(read(join(cwd, f.rel)), f.path, f.bundle, deps.priors ?? SCRIPT_PRIORS) };
51
86
  };
52
87
 
53
88
  const surveyStoreRoot = (cwd, lstat) => {
@@ -78,8 +113,6 @@ const composeLines = ({ files, store, fates, dryRun }) => [
78
113
  const partialNote = (count) =>
79
114
  (count > 0 ? [`the writes stopped PARTWAY — the ${count} file(s) named above were already written and are NOT rolled back`] : []);
80
115
 
81
- // ── the ensure ────────────────────────────────────────────────────────────────────────────────────
82
-
83
116
  // The store body is read and rendered BEFORE the first write, so a missing or unrenderable template
84
117
  // refuses with nothing written.
85
118
  const renderStoreRoot = (kitRoot, read, today) => {
@@ -89,7 +122,7 @@ const renderStoreRoot = (kitRoot, read, today) => {
89
122
  };
90
123
 
91
124
  // One write per due path in write order: a prior refreshed and an edit replaced by the atomic write,
92
- // an absent pair file and the store root written create-only. → { fates, notes, failure? }
125
+ // an absent script and the store root written create-only. → { fates, notes, failure? }
93
126
  const writeAll = ({ cwd, due, storeBody, deps, read }) => {
94
127
  const fates = new Map();
95
128
  const notes = [];
@@ -98,15 +131,15 @@ const writeAll = ({ cwd, due, storeBody, deps, read }) => {
98
131
  let result;
99
132
  try {
100
133
  result = isStore ? writeProjectFileCreateOnly(cwd, f.rel, storeBody, deps, { noun: 'the spec store root' })
101
- : f.state === 'absent' ? writeProjectFileCreateOnly(cwd, f.rel, String(f.bundle), deps, { noun: 'a seeded spec-layer script' })
102
- : writeContainedFileAtomic(cwd, join(cwd, f.rel), String(f.bundle), deps, { label: f.rel });
134
+ : f.state === 'absent' ? writeProjectFileCreateOnly(cwd, f.rel, f.bundle, deps, { noun: 'a seeded spec-layer script' })
135
+ : writeContainedFileAtomic(cwd, join(cwd, f.rel), f.bundle, deps, { label: f.rel });
103
136
  } catch (err) {
104
137
  if (!isStore) fates.set(f.rel, 'refused');
105
138
  return { fates, notes, failure: ['write-refused', `${f.rel}: ${causeOf(err)}`] };
106
139
  }
107
140
  notes.push(...tmpNote(f.rel, result.tmpLeftBehind));
108
141
  const stood = f.state === 'absent' && !result.created;
109
- if (stood && !isStore && classifyDeployedScript(read(join(cwd, f.rel)), f.name, f.bundle) !== 'current') {
142
+ if (stood && !isStore && classifyDeployedScript(read(join(cwd, f.rel)), f.path, f.bundle) !== 'current') {
110
143
  fates.set(f.rel, 'refused');
111
144
  return { fates, notes, failure: ['race-unresolved', `${f.rel}: appeared while this run was placing it and does not carry the bundled body — nothing further written, re-run when the tree is settled`] };
112
145
  }
@@ -115,19 +148,24 @@ const writeAll = ({ cwd, due, storeBody, deps, read }) => {
115
148
  return { fates, notes };
116
149
  };
117
150
 
151
+ const placedAnswer = (files) => {
152
+ const placedScripts = files.filter((f) => f.path && f.state === 'absent').map((f) => f.rel);
153
+ return placedScripts.length ? { placedScripts } : {};
154
+ };
155
+
118
156
  export const ensureSpecs = ({ cwd, kitRoot, dryRun = false, deps = {} }) => {
119
157
  const lstat = deps.lstat ?? lstatSync;
120
158
  const read = deps.readFile ?? readFileSync;
121
159
  const refusal = nodeEvidenceRefusal(OP, cwd, lstat);
122
160
  if (refusal) return refusal;
123
- const survey = (name) => surveyScript({ cwd, kitRoot, name, read, lstat });
124
- const files = [...READER_PAIR.map(survey), ...CHECKER_PAIR.map(survey)];
161
+ const bundled = readBundles(kitRoot, read);
162
+ if (bundled.refusal) return bundled.refusal;
163
+ const folders = folderRefusal(cwd, bundled.files, lstat);
164
+ if (folders) return folders;
165
+ const files = bundled.files.map((f) => surveyScript(cwd, f, deps, read, lstat));
125
166
  const store = surveyStoreRoot(cwd, lstat);
126
- for (const f of files) {
127
- if (f.state === 'bundle-unreadable') return composeFailure(OP, 'bundle-unreadable', `${f.rel}: the bundled script could not be read, so nothing was written — reinstall the kit. ${f.error}`);
128
- }
129
167
  for (const f of [...files, store]) {
130
- if (f.state === 'wrong-kind') return composeFailure(OP, 'wrong-node-kind', `${f.rel}: exists but is ${f.wrongKind} — nothing was read or written; resolve it by hand, then re-run`);
168
+ if (f.state === 'wrong-kind') return wrongKind(f.rel, f.wrongKind);
131
169
  }
132
170
 
133
171
  const due = [...files.filter((f) => f.state !== 'current'), ...(store.state === 'absent' ? [store] : [])];
@@ -135,7 +173,7 @@ export const ensureSpecs = ({ cwd, kitRoot, dryRun = false, deps = {} }) => {
135
173
  const refreshes = (fs) => fs.some((f) => f.state === 'prior' || f.state === 'custom');
136
174
  if (dryRun) {
137
175
  const token = seeds(due) ? 'would-seed' : refreshes(due) ? 'would-refresh' : 'already-present';
138
- return composeOutcome(OP, token, [...composeLines({ files, store, fates: new Map(), dryRun }), ...(due.length > 0 ? [hookLine(false, true)] : [])], false);
176
+ return { ...composeOutcome(OP, token, [...composeLines({ files, store, fates: new Map(), dryRun }), ...(due.length > 0 ? [hookLine(false, true)] : [])], false), ...placedAnswer(files) };
139
177
  }
140
178
 
141
179
  let storeBody = null;
@@ -150,5 +188,5 @@ export const ensureSpecs = ({ cwd, kitRoot, dryRun = false, deps = {} }) => {
150
188
  const written = due.filter((f) => fates.get(f.rel) === 'written');
151
189
  const lines = [...composeLines({ files, store, fates, dryRun }), ...(written.length > 0 ? [hookLine(false, false)] : []), ...notes];
152
190
  if (failure) return composeFailure(OP, failure[0], failure[1], ...lines, ...partialNote(written.length));
153
- return composeOutcome(OP, seeds(written) ? 'seeded' : refreshes(written) ? 'refreshed' : 'already-present', lines, false);
191
+ return { ...composeOutcome(OP, seeds(written) ? 'seeded' : refreshes(written) ? 'refreshed' : 'already-present', lines, false), ...placedAnswer(written) };
154
192
  };
@@ -8,13 +8,13 @@
8
8
  // read-only tool's import graph. Vocabulary here, behaviour in ensure-ops.mjs.
9
9
 
10
10
  // The FIXED order the CLI runs them in — the order references/modes/upgrade.md already prescribed.
11
- // `specs` sits after `scripts` (its reader pair is a scripts/ seed too) and BEFORE `index`: the store
12
- // root it seeds is a docs/ai file the navigator must count. `specs` writes its pairs and `scripts`
13
- // every kit script with no question and no copy kept, and `scripts` then
11
+ // `specs` sits before `scripts`, so its pairs, their imports and the command run.mjs stand before `scripts`
12
+ // removes the old flat files, and before `index`, whose navigator counts the store root it seeds. `specs` and
13
+ // `scripts` write with no question and no copy kept, and `scripts` then
14
14
  // runs the project's rotator (`--ensure-current`), which brings the ADR store current.
15
15
  // `executor` follows `vehicles`: its body is derived from the settings file that op seeds.
16
16
  // `rules` follows `specs` and precedes `index`: the rules files it lays are docs/ai files the navigator counts.
17
- export const ENSURE_OPS = Object.freeze(['orchestration', 'gates', 'autonomy', 'vehicles', 'executor', 'scripts', 'specs', 'rules', 'index']);
17
+ export const ENSURE_OPS = Object.freeze(['orchestration', 'gates', 'autonomy', 'vehicles', 'executor', 'specs', 'scripts', 'rules', 'index']);
18
18
 
19
19
  // Tokens that assert a WRITE happened. --dry-run may never emit one of these (the CLI's contract test
20
20
  // walks this set), and each has exactly one `would-` counterpart below. `refreshed` is the spec-layer
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { constants, openSync, closeSync, fstatSync, writeSync, ftruncateSync } from 'node:fs';
3
3
  import { basename, dirname, resolve } from 'node:path';
4
- import { fail } from '../references/scripts/markdown-blocks.mjs';
4
+ import { fail } from '../references/scripts/shared/index.mjs';
5
5
  import { isDirectRun } from './direct-run.mjs';
6
6
  import { readRegularFileNoFollow } from './fs-read-nofollow.mjs';
7
7
  import { readEpicEntries } from './epic-store.mjs';
@@ -1,5 +1,5 @@
1
1
  import { posix } from 'node:path';
2
- import { tokenizeMarkdown } from '../references/scripts/markdown-blocks.mjs';
2
+ import { tokenizeMarkdown } from '../references/scripts/shared/index.mjs';
3
3
  import { parseHeader, checkEpic } from './epic-shape.mjs';
4
4
  import { auditQueue } from './queue-audit.mjs';
5
5
  import { hasPathOverlap, findReachable, listStories, unique } from './claim-relation.mjs';
@@ -1,4 +1,4 @@
1
- import { tokenizeMarkdown } from '../references/scripts/markdown-blocks.mjs';
1
+ import { tokenizeMarkdown } from '../references/scripts/shared/index.mjs';
2
2
  import { bulletBlocks, getLineCount, unique } from './plan-shape.mjs';
3
3
 
4
4
  export const EPIC_SECTIONS = Object.freeze([
@@ -85,6 +85,8 @@ import { toViewModel } from './view-model.mjs';
85
85
  import { render } from './renderers.mjs';
86
86
  // The feature-spec adoption state (contract: kit/spec-adoption) — read-only leaves, no cycle.
87
87
  import { ADOPTION, readDeclineAck, surveySpecAdoption } from './spec-adoption.mjs';
88
+ // The kit's one door to the script family: where a deployment holds the decisions rotator.
89
+ import { DEPLOYED_SCRIPTS } from './node-evidence.mjs';
88
90
 
89
91
  // ── manifestState values — re-export the EXACT public subset family-registry exported before B1 ─────
90
92
  // (the 7 state constants + DISPLAY_NAMES) so every existing importer (uninstall.mjs, the test suites)
@@ -356,7 +358,7 @@ export const ADR_LAYOUT_PATHS = Object.freeze({
356
358
  // The DEPLOYED rotator is the discriminator: the new-scheme file names the store path, the
357
359
  // pre-migration one does not. Never "has decisions.md, lacks adr/" — that shape false-positives a
358
360
  // tree whose NEW rotator already reds its own gate, and every No-Node project.
359
- rotator: 'scripts/archive-decisions.mjs',
361
+ rotator: DEPLOYED_SCRIPTS.find(({ path }) => path === 'archives/archive-decisions.mjs').deployed,
360
362
  storeMarker: 'docs/ai/adr',
361
363
  });
362
364
  const ENOENT = 'ENOENT';
@@ -4,7 +4,7 @@
4
4
  import { readFileSync, realpathSync, writeFileSync } from 'node:fs';
5
5
  import { spawnSync } from 'node:child_process';
6
6
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
7
- import { fail } from '../references/scripts/markdown-blocks.mjs';
7
+ import { fail } from '../references/scripts/shared/index.mjs';
8
8
  import { isDirectRun } from './direct-run.mjs';
9
9
  import { readFileBytesNoFollowCapped } from './fs-read-nofollow.mjs';
10
10
  import { GIT_MAX_BUFFER, resolveGitLocation, stripGitLocationEnv, withGitPath } from './git-env.mjs';
@@ -10,7 +10,7 @@
10
10
  // fix ships now, only the generalization defers.
11
11
  // blocking no correct narrow fix exists -> the phase does not close; there is no queue arm.
12
12
  //
13
- // Markdown is read through the family's ONE block model (references/scripts/markdown-blocks.mjs, the
13
+ // Markdown is read through the family's ONE block model (references/scripts/shared/index.mjs, the
14
14
  // module the archivers already read through): fenced regions, ATX headings at 0-3 columns of indent,
15
15
  // CRLF and the backtick-info-string rule are ITS problem, not a second hand-rolled grammar here. A
16
16
  // document it refuses is a loud refusal, never a silent empty read.
@@ -21,7 +21,7 @@
21
21
  // Pure string functions - every input is text; the CLI half (fold-scope-cli.mjs) owns the fs.
22
22
  // Dependency-free, Node >= 22.
23
23
 
24
- import { tokenizeMarkdown } from '../references/scripts/markdown-blocks.mjs';
24
+ import { tokenizeMarkdown } from '../references/scripts/shared/index.mjs';
25
25
  import { PLAN_HEADINGS, bulletBlocks } from './plan-shape.mjs';
26
26
 
27
27
  export { bulletBlocks };
@@ -11,7 +11,7 @@ import { join, isAbsolute } from 'node:path';
11
11
  import { fileURLToPath } from 'node:url';
12
12
  import { CHECKER_CLAIM, checkerClaimTool, classifyCheckerClaim } from './checker-claim.mjs';
13
13
  import { fail, loadConfig, CONFIG_REL } from './orchestration-config.mjs';
14
- import { isCoverageProducerGate } from './coverage-producer.mjs';
14
+ import { readsAsCoverageProducer, retiredProducerFormOf } from './coverage-producer.mjs';
15
15
  import { matchesSourceSizeGate } from './source-size-core.mjs';
16
16
 
17
17
  // The per-project declaration (strict JSON, hand-editable). cwd-relative — errors show a path the
@@ -158,11 +158,21 @@ export const isFinalCapableDeclaration = (gates, projectDir) => {
158
158
  // so the checker reads nothing — or, worse, stale bytes an earlier run left behind — and still
159
159
  // passes. ONE home for the rule: the written-declaration defects below and the advisor's
160
160
  // inert-declaration item both decide through it, so they cannot drift apart. Producer-ness itself is
161
- // the canon's gate-level predicate (cmd closed-world OR the declared marker), so the slice is the
162
- // only thing this function owns — and the slice is what keeps a marker on the CHECKER from
163
- // self-pairing.
164
- export const coverageProducerPrecedes = (gates, checkerIndex) =>
165
- gates.slice(0, checkerIndex).some((gate) => isCoverageProducerGate(gate));
161
+ // the canon's one row question (readsAsCoverageProducer: the gate-level predicate, asked only of a
162
+ // row that does not claim the coverage checker), so the slice is the only thing this function owns.
163
+ const COVERAGE_CHECK_TOOL = checkerClaimTool('coverage-check.mjs', fileURLToPath(new URL('./coverage-check.mjs', import.meta.url)));
164
+ export const coverageProducerPrecedes = (gates, checkerIndex, projectDir) =>
165
+ gates.slice(0, checkerIndex).some((gate) => readsAsCoverageProducer(gate, classifyCheckerClaim(COVERAGE_CHECK_TOOL, gate?.cmd, projectDir)));
166
+
167
+ // movableEarlierForm(gates) → whether a gate an earlier kit wrote, which the upgrade's gates-migration
168
+ // step moves (a retired form with a path-shaped tail), stands anywhere in the declaration (spec
169
+ // coverage-producer, the remedy route). A flagged tail is not movable: its remedy is its CUSTOMIZED line.
170
+ export const movableEarlierForm = (gates) => gates.some((gate) => retiredProducerFormOf(gate?.cmd)?.pathShaped === true);
171
+
172
+ // The checker lines' one fact and one remedy, and the upgrade's words, which predict nothing about the run.
173
+ export const NO_PRODUCER_FACT = 'no gate before it is a producer this kit reads';
174
+ export const NO_PRODUCER_REMEDY = 'declare or move one before it: node scripts/agent-workflow/run.mjs unit-tests <your test paths>, or mark your own suite gate "lcovProducer": true';
175
+ export const UPGRADE_MOVES = "it moves an earlier kit's gate with no question, or a line of its report names what stops it";
166
176
 
167
177
  // coverageDeclarationDefects(gates, projectDir) → the WRITTEN-declaration coverage rule, as a list
168
178
  // of named defects (empty = satisfied): at most ONE canonical coverage checker; if one is present
@@ -193,14 +203,12 @@ export const coverageDeclarationDefects = (gates, projectDir) => {
193
203
  'places a new entry before a trailing checker, but it never reorders what it did not write)',
194
204
  }];
195
205
  }
196
- if (!coverageProducerPrecedes(gates, index)) {
197
- return [{
198
- kind: 'no-producer',
199
- message:
200
- `${GATES_REL}: the canonical coverage checker (${checkers[0].id}) is declared but NO gate would produce the lcov it reads — ` +
201
- 'the checker would pass while verifying nothing. Declare a suite gate carrying the coverage reporters ' +
202
- '(references/modes/gates.md names the exact form), or drop the checker',
203
- }];
206
+ if (!coverageProducerPrecedes(gates, index, projectDir)) {
207
+ // One fact; the remedy is the upgrade's gates-migration step while a gate it moves stands anywhere.
208
+ const remedy = movableEarlierForm(gates)
209
+ ? `run the gates-migration step of /agent-workflow-kit upgrade: ${UPGRADE_MOVES}`
210
+ : NO_PRODUCER_REMEDY;
211
+ return [{ kind: 'no-producer', message: `${GATES_REL}: the canonical coverage checker (${checkers[0].id}): ${NO_PRODUCER_FACT} — ${remedy}` }];
204
212
  }
205
213
  return [];
206
214
  };