@sabaiway/agent-workflow-kit 20.2.0 → 21.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 (91) hide show
  1. package/CHANGELOG.md +39 -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/package.json +5 -2
  8. package/references/contracts.md +9 -9
  9. package/references/modes/bootstrap.md +3 -3
  10. package/references/modes/commit-guard.md +1 -1
  11. package/references/modes/recommendations.md +2 -2
  12. package/references/modes/upgrade.md +4 -4
  13. package/references/scripts/{archive-caps.mjs → archives/archive-caps.mjs} +1 -1
  14. package/references/scripts/{archive-changelog.mjs → archives/archive-changelog.mjs} +7 -9
  15. package/references/scripts/{archive-decisions.mjs → archives/archive-decisions.mjs} +13 -10
  16. package/references/scripts/{archive-issues.mjs → archives/archive-issues.mjs} +7 -8
  17. package/references/scripts/{check-docs-size.mjs → docs-size/check-docs-size.mjs} +3 -4
  18. package/references/scripts/docs-size/index.mjs +2 -0
  19. package/references/scripts/family.json +43 -0
  20. package/references/scripts/family.mjs +90 -0
  21. package/references/scripts/gates/kit-command-gates.mjs +117 -0
  22. package/references/scripts/{migrate-gates.mjs → gates/migrate-gates.mjs} +30 -13
  23. package/references/scripts/{install-git-hooks.mjs → git-hooks/install-git-hooks.mjs} +50 -38
  24. package/references/scripts/run.mjs +74 -0
  25. package/references/scripts/shared/index.mjs +3 -0
  26. package/references/scripts/shared/project-root.mjs +11 -0
  27. package/references/scripts/spec-schema/index.mjs +2 -0
  28. package/references/shared/composition-handoff.md +1 -1
  29. package/references/shared/deploy-tail.md +2 -2
  30. package/references/templates/SPEC_TEMPLATE.md +1 -1
  31. package/references/templates/adr-record.md +3 -3
  32. package/tools/apply-danger-check.mjs +9 -5
  33. package/tools/atomic-write.mjs +3 -1
  34. package/tools/direct-run.mjs +2 -0
  35. package/tools/distribution-files/retired.mjs +99 -0
  36. package/tools/distribution-files/scripts.mjs +67 -52
  37. package/tools/ensure-configs.mjs +21 -21
  38. package/tools/ensure-ops.mjs +60 -18
  39. package/tools/ensure-specs.mjs +82 -47
  40. package/tools/ensure-vocabulary.mjs +4 -4
  41. package/tools/epic-shape-cli.mjs +1 -1
  42. package/tools/epic-shape-ledger.mjs +1 -1
  43. package/tools/epic-shape.mjs +1 -1
  44. package/tools/family-registry.mjs +3 -1
  45. package/tools/feedback-record-cli.mjs +1 -1
  46. package/tools/fold-scope.mjs +2 -2
  47. package/tools/git-hooks.mjs +90 -65
  48. package/tools/jev-connect.mjs +1 -1
  49. package/tools/jev-guide.mjs +1 -1
  50. package/tools/jev-skill.mjs +1 -1
  51. package/tools/known-footprint.mjs +7 -29
  52. package/tools/node-evidence.mjs +29 -15
  53. package/tools/now-cli.mjs +1 -1
  54. package/tools/payload-prune.mjs +53 -58
  55. package/tools/plan-shape-cli.mjs +1 -1
  56. package/tools/plan-shape.mjs +1 -1
  57. package/tools/project-rules/rules-record.mjs +1 -1
  58. package/tools/queue-audit-cli.mjs +1 -1
  59. package/tools/queue-audit.mjs +2 -2
  60. package/tools/queue-purge-archive.mjs +1 -1
  61. package/tools/queue-purge-cli.mjs +1 -1
  62. package/tools/queue-purge.mjs +1 -1
  63. package/tools/recommendations.mjs +22 -19
  64. package/tools/script-priors.mjs +31 -3
  65. package/tools/source-size/piles.mjs +1 -1
  66. package/tools/spec-adoption.mjs +1 -1
  67. package/tools/spec-check-ops.mjs +2 -2
  68. package/tools/spec-check.mjs +2 -2
  69. package/tools/spec-coverage.mjs +1 -1
  70. package/tools/tier-guide.mjs +1 -1
  71. package/tools/transition/index.mjs +1 -1
  72. package/tools/upgrade-runlist.mjs +1 -1
  73. package/tools/write-lanes.mjs +2 -2
  74. package/references/scripts/_expect-shim.mjs +0 -41
  75. package/references/scripts/archive-caps.test.mjs +0 -321
  76. package/references/scripts/archive-changelog.test.mjs +0 -560
  77. package/references/scripts/archive-conservation.test.mjs +0 -466
  78. package/references/scripts/archive-decisions.test.mjs +0 -1503
  79. package/references/scripts/archive-issues.test.mjs +0 -825
  80. package/references/scripts/archiver-structure.test.mjs +0 -84
  81. package/references/scripts/check-docs-size-cli.test.mjs +0 -325
  82. package/references/scripts/check-docs-size-ensure.test.mjs +0 -360
  83. package/references/scripts/check-docs-size.test.mjs +0 -395
  84. package/references/scripts/install-git-hooks-repo-exec.test.mjs +0 -185
  85. package/references/scripts/install-git-hooks.test.mjs +0 -241
  86. package/references/scripts/markdown-blocks.test.mjs +0 -310
  87. package/references/scripts/migrate-gates-branches.test.mjs +0 -302
  88. package/references/scripts/migrate-gates.test.mjs +0 -517
  89. package/references/scripts/spec-schema.test.mjs +0 -352
  90. /package/references/scripts/{markdown-blocks.mjs → shared/markdown-blocks.mjs} +0 -0
  91. /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,85 @@
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 command, each at its deployed path in the kit folder
4
+ // scripts/agent-workflow/, with the bundled files they import; every other kit script is the scripts
5
+ // 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 command scripts/agent-workflow/run.mjs
13
+ // 5. the store root docs/ai/specs/index.md (placeholders rendered)
14
+ // Why the order: every file is written after the files it imports, so each pair file it leaves loads;
15
+ // the kit's bundled navigator generator collapses `specs/` into one row, while the project's pre-commit
16
+ // hook runs ITS deployed checker — an older one renders the store row by row and reds `--check-index`.
17
+ // So the checker is written before the spec store, and a write that fails stops every later one. The
18
+ // pair lines and the hook-run line are the scripts op's own, from the module's index. Each write is
19
+ // idempotent, so a stopped run converges on the next.
15
20
  //
16
21
  // Dependency-free, Node >= 22. Every fs primitive is injectable (deps.*). No side effects on import.
17
22
 
18
23
  import { readFileSync, lstatSync } from 'node:fs';
19
24
  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';
25
+ import { lstatNoFollow, writeContainedFileAtomic, writeProjectFileCreateOnly } from './atomic-write.mjs';
26
+ import { DEPLOYED_SCRIPTS } from './node-evidence.mjs';
27
+ import { SCRIPT_PRIORS, classifyDeployedScript } from './script-priors.mjs';
28
+ import { bundledImportsOf, composeFailure, composeOutcome, dependenciesFirst, nodeEvidenceRefusal, probeSeedTarget, tmpNote } from './ensure-ops.mjs';
23
29
  import { fileLine, hookLine } from './distribution-files/index.mjs';
24
30
 
25
31
  const OP = 'specs';
26
- const SCRIPTS_DIR = 'scripts';
27
- const BUNDLED_SCRIPTS = ['references', 'scripts'];
32
+ const READER = DEPLOYED_SCRIPTS.filter((e) => e.module === 'spec-schema');
33
+ const CHECKER = DEPLOYED_SCRIPTS.filter((e) => e.module === 'docs-size');
34
+ const COMMAND = DEPLOYED_SCRIPTS.find((e) => !e.module);
28
35
  const STORE_ROOT_REL = 'docs/ai/specs/index.md';
29
36
  const STORE_ROOT_TEMPLATE = ['references', 'templates', 'specs', 'index.md'];
30
37
  const DATE_PLACEHOLDER = '{{DATE}}';
31
38
 
32
39
  const causeOf = (err) => String((err && err.message) || err);
33
40
  const todayIso = () => new Date().toISOString().slice(0, 10);
41
+ const kindOfDir = (st) => (st.isSymbolicLink() ? 'a symlink' : st.isFile() ? 'a regular file' : 'not a directory');
42
+ 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
43
 
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) };
44
+ // ── the survey: the pairs, the files they import and the store root classified, nothing written ───
45
+
46
+ // The bundled side: the pairs and their whole import closure in write order → { files } | { refusal }.
47
+ const readBundles = (kitRoot, read) => {
48
+ const byPath = new Map();
49
+ const queue = [...READER, ...CHECKER, COMMAND];
50
+ for (const entry of queue) {
51
+ if (byPath.has(entry.path)) continue;
52
+ let bundle;
53
+ try {
54
+ bundle = read(join(kitRoot, entry.bundled));
55
+ } catch (err) {
56
+ return { refusal: composeFailure(OP, 'bundle-unreadable', `${entry.deployed}: the bundled script could not be read, so nothing was written — reinstall the kit. ${causeOf(err)}`) };
57
+ }
58
+ const imports = bundledImportsOf(entry.path, bundle);
59
+ byPath.set(entry.path, { path: entry.path, rel: entry.deployed, bundle, imports });
60
+ queue.push(...DEPLOYED_SCRIPTS.filter((e) => imports.includes(e.path)));
61
+ }
62
+ const of = (entries) => (path) => entries.some((e) => e.path === path);
63
+ const group = (keep) => dependenciesFirst([...byPath.values()].filter((f) => keep(f.path)));
64
+ return { files: [...group((p) => !of(READER)(p) && !of(CHECKER)(p) && p !== COMMAND.path), ...group(of(READER)), ...group(of(CHECKER)), ...group((p) => p === COMMAND.path)] };
65
+ };
66
+
67
+ // Each folder on the way to a pair file or a file it imports, lstat-ed without following a link → a refusal or null.
68
+ const folderRefusal = (cwd, files, lstat) => {
69
+ const folders = new Set(files.flatMap((f) => f.rel.split('/').slice(0, -1).map((_, at, parts) => parts.slice(0, at + 1).join('/'))));
70
+ for (const rel of folders) {
71
+ const st = lstatNoFollow(join(cwd, rel), lstat);
72
+ if (st !== null && (!st.isDirectory() || st.isSymbolicLink())) return wrongKind(`${rel}/`, kindOfDir(st));
46
73
  }
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 };
74
+ return null;
75
+ };
76
+
77
+ // One deployed script → its state against the bundled body, by the catalog seam keyed by manifest path.
78
+ const surveyScript = (cwd, f, deps, read, lstat) => {
79
+ const probe = probeSeedTarget(join(cwd, f.rel), lstat);
80
+ if (probe.wrongKind) return { ...f, state: 'wrong-kind', wrongKind: probe.wrongKind };
81
+ if (!probe.present) return { ...f, state: 'absent' };
82
+ return { ...f, state: classifyDeployedScript(read(join(cwd, f.rel)), f.path, f.bundle, deps.priors ?? SCRIPT_PRIORS) };
51
83
  };
52
84
 
53
85
  const surveyStoreRoot = (cwd, lstat) => {
@@ -78,8 +110,6 @@ const composeLines = ({ files, store, fates, dryRun }) => [
78
110
  const partialNote = (count) =>
79
111
  (count > 0 ? [`the writes stopped PARTWAY — the ${count} file(s) named above were already written and are NOT rolled back`] : []);
80
112
 
81
- // ── the ensure ────────────────────────────────────────────────────────────────────────────────────
82
-
83
113
  // The store body is read and rendered BEFORE the first write, so a missing or unrenderable template
84
114
  // refuses with nothing written.
85
115
  const renderStoreRoot = (kitRoot, read, today) => {
@@ -89,7 +119,7 @@ const renderStoreRoot = (kitRoot, read, today) => {
89
119
  };
90
120
 
91
121
  // 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? }
122
+ // an absent script and the store root written create-only. → { fates, notes, failure? }
93
123
  const writeAll = ({ cwd, due, storeBody, deps, read }) => {
94
124
  const fates = new Map();
95
125
  const notes = [];
@@ -98,15 +128,15 @@ const writeAll = ({ cwd, due, storeBody, deps, read }) => {
98
128
  let result;
99
129
  try {
100
130
  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 });
131
+ : f.state === 'absent' ? writeProjectFileCreateOnly(cwd, f.rel, f.bundle, deps, { noun: 'a seeded spec-layer script' })
132
+ : writeContainedFileAtomic(cwd, join(cwd, f.rel), f.bundle, deps, { label: f.rel });
103
133
  } catch (err) {
104
134
  if (!isStore) fates.set(f.rel, 'refused');
105
135
  return { fates, notes, failure: ['write-refused', `${f.rel}: ${causeOf(err)}`] };
106
136
  }
107
137
  notes.push(...tmpNote(f.rel, result.tmpLeftBehind));
108
138
  const stood = f.state === 'absent' && !result.created;
109
- if (stood && !isStore && classifyDeployedScript(read(join(cwd, f.rel)), f.name, f.bundle) !== 'current') {
139
+ if (stood && !isStore && classifyDeployedScript(read(join(cwd, f.rel)), f.path, f.bundle) !== 'current') {
110
140
  fates.set(f.rel, 'refused');
111
141
  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
142
  }
@@ -115,19 +145,24 @@ const writeAll = ({ cwd, due, storeBody, deps, read }) => {
115
145
  return { fates, notes };
116
146
  };
117
147
 
148
+ const placedAnswer = (files) => {
149
+ const placedScripts = files.filter((f) => f.path && f.state === 'absent').map((f) => f.rel);
150
+ return placedScripts.length ? { placedScripts } : {};
151
+ };
152
+
118
153
  export const ensureSpecs = ({ cwd, kitRoot, dryRun = false, deps = {} }) => {
119
154
  const lstat = deps.lstat ?? lstatSync;
120
155
  const read = deps.readFile ?? readFileSync;
121
156
  const refusal = nodeEvidenceRefusal(OP, cwd, lstat);
122
157
  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)];
158
+ const bundled = readBundles(kitRoot, read);
159
+ if (bundled.refusal) return bundled.refusal;
160
+ const folders = folderRefusal(cwd, bundled.files, lstat);
161
+ if (folders) return folders;
162
+ const files = bundled.files.map((f) => surveyScript(cwd, f, deps, read, lstat));
125
163
  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
164
  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`);
165
+ if (f.state === 'wrong-kind') return wrongKind(f.rel, f.wrongKind);
131
166
  }
132
167
 
133
168
  const due = [...files.filter((f) => f.state !== 'current'), ...(store.state === 'absent' ? [store] : [])];
@@ -135,7 +170,7 @@ export const ensureSpecs = ({ cwd, kitRoot, dryRun = false, deps = {} }) => {
135
170
  const refreshes = (fs) => fs.some((f) => f.state === 'prior' || f.state === 'custom');
136
171
  if (dryRun) {
137
172
  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);
173
+ return { ...composeOutcome(OP, token, [...composeLines({ files, store, fates: new Map(), dryRun }), ...(due.length > 0 ? [hookLine(false, true)] : [])], false), ...placedAnswer(files) };
139
174
  }
140
175
 
141
176
  let storeBody = null;
@@ -150,5 +185,5 @@ export const ensureSpecs = ({ cwd, kitRoot, dryRun = false, deps = {} }) => {
150
185
  const written = due.filter((f) => fates.get(f.rel) === 'written');
151
186
  const lines = [...composeLines({ files, store, fates, dryRun }), ...(written.length > 0 ? [hookLine(false, false)] : []), ...notes];
152
187
  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);
188
+ return { ...composeOutcome(OP, seeds(written) ? 'seeded' : refreshes(written) ? 'refreshed' : 'already-present', lines, false), ...placedAnswer(written) };
154
189
  };
@@ -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 };