@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
@@ -1,7 +1,8 @@
1
- // coverage-producer.mjs — the kit's half of the shared coverage-producer vocabulary: the reporter
2
- // flags the canonical suite gate carries, and the CLOSED predicate deciding whether a declared gate
3
- // cmd actually WRITES the lcov the canonical checker reads. A LEAF — imports nothing, so every
4
- // consumer (gates-init, gates-declaration, the advisor) decides through ONE predicate.
1
+ // coverage-producer.mjs — the kit's half of the shared coverage-producer vocabulary (spec
2
+ // coverage-producer): the one command body the suite gate runs, the move list of the flag sets
3
+ // earlier kits wrote, and the CLOSED predicate deciding whether a declared gate cmd actually WRITES
4
+ // the lcov the canonical checker reads. A LEAF — imports nothing, so every consumer (gates-init,
5
+ // gates-declaration, the advisor) decides through ONE predicate.
5
6
  // Dependency-free, Node >= 22. No side effects on import.
6
7
 
7
8
  // coverage-producer canon >>> BEGIN drift-guarded region
@@ -11,31 +12,17 @@
11
12
  // bytes — so a TEXT drift guard beside the root's copy holds them equal. Edit BOTH, then re-run the
12
13
  // mirror sync.
13
14
  //
14
- // The destination is written against AW_GIT_DIR, which run-gates exports to every gate child on a
15
- // plain run AND on --final (AW_LCOV_FILE is --final only), so one cmd survives the unmet
16
- // producer-variable preflight in both modes. The `:?` is not decoration either: this cmd is also
17
- // PASTE-READY, and the required-parameter form makes bash refuse BY NAME when AW_GIT_DIR is unset
18
- // or EMPTY, where a bare `$AW_GIT_DIR` expanded to empty and wrote the lcov to the filesystem ROOT.
19
- // Residual, stated: `:?` says nothing about the value's ORIGIN — a STALE exported AW_GIT_DIR
20
- // expands fine and the lcov lands under it; only the runner's own injection makes it the right dir.
21
- // The explicit stdout reporter keeps the human stream: without it the lcov reporter swallows the
22
- // TAP/spec output.
23
- export const UNIT_TESTS_COVERAGE_FLAGS =
24
- '--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';
15
+ // The ONE producer form the kit writes: the stable kit command's unit-tests name (spec kit-command) —
16
+ // the Node test runner with the lcov reporter under AW_GIT_DIR and the kit test reporter on stdout.
17
+ export const COVERAGE_PRODUCER_BODY = 'node scripts/agent-workflow/run.mjs unit-tests';
25
18
 
26
- // Every flag set the kit has EVER emitted — APPEND-ONLY, newest first. Emission uses the head; the
27
- // tail exists so a declaration written by an EARLIER kit and living on disk in a deployed project
28
- // keeps reading as the producer it is. De-recognizing a prior form would silently reclassify a
29
- // working suite gate as customized and withhold the checker over it.
30
- export const KNOWN_COVERAGE_FLAG_SETS = Object.freeze([
31
- UNIT_TESTS_COVERAGE_FLAGS,
19
+ // The reporter flag sets earlier kits wrote after `node --test`, newest first, byte for byte: a MOVE
20
+ // LIST the gate migration switches onto the body above, never read as a producer.
21
+ export const RETIRED_COVERAGE_FLAG_SETS = Object.freeze([
22
+ '--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',
32
23
  '--experimental-test-coverage --test-reporter=lcov --test-reporter-destination="$AW_GIT_DIR/agent-workflow-lcov.info" --test-reporter=spec --test-reporter-destination=stdout',
33
24
  ]);
34
-
35
- // The ONE suite body that produces that lcov with no extra dependency (the EMITTED form), beside
36
- // the closed set of bodies recognition accepts.
37
- export const COVERAGE_PRODUCER_BODY = `node --test ${UNIT_TESTS_COVERAGE_FLAGS}`;
38
- const KNOWN_PRODUCER_BODIES = Object.freeze(KNOWN_COVERAGE_FLAG_SETS.map((flags) => `node --test ${flags}`));
25
+ const RETIRED_BODIES = Object.freeze(RETIRED_COVERAGE_FLAG_SETS.map((flags) => `node --test ${flags}`));
39
26
 
40
27
  // The per-PM exec wrappers a fill offer puts that body behind. Recognition must cover every form
41
28
  // the kit has EMITTED, so the prefixes are matched literally; gates-init's execCmdFor stays the one
@@ -48,11 +35,11 @@ const PRODUCER_EXEC_PREFIXES = Object.freeze([
48
35
 
49
36
  // A trailing suffix is the project's own test paths; a leading one would mean the body is not what
50
37
  // this cmd runs. The tail passes a POSITIVE closed grammar — every whitespace-separated token must
51
- // be path-shaped — never an operator blocklist: `node --test <flags> && rm -f <lcov>` runs the
52
- // suite and then DELETES the file, so an open-ended tail would certify a producer that leaves
53
- // nothing behind, and scanning for operator BYTES would put the incomplete-scan failure on the
54
- // unsafe side (a missed operator is a dead pair) instead of the mild one (an unrecognised
55
- // legitimate tail merely withholds the offer — add the gate by hand).
38
+ // be path-shaped — never an operator blocklist: `<body> && rm -f <lcov>` runs the suite and then
39
+ // DELETES the file, so an open-ended tail would certify a producer that leaves nothing behind, and
40
+ // scanning for operator BYTES would put the incomplete-scan failure on the unsafe side (a missed
41
+ // operator is a dead pair) instead of the mild one (an unrecognised legitimate tail merely
42
+ // withholds the offer — add the gate by hand). No flag either: the command hands it to the runner.
56
43
  // The token set is everything that appears in a PATH or a glob and can never sequence, redirect or
57
44
  // substitute a command — quoting and `~` included, `( ) $ ` ; & | < > # \` excluded. SCOPE, stated
58
45
  // exactly: the screen judges each token's SOURCE bytes. Quote removal adds none, but brace SEQUENCE
@@ -67,21 +54,64 @@ const PRODUCER_EXEC_PREFIXES = Object.freeze([
67
54
  // `skipped-no-lcov`.
68
55
  const PRODUCER_PATH_TOKEN = /^(?!-)[A-Za-z0-9_./*{},:@+=~?[\]!'"-]+$/;
69
56
  const pathShapedTail = (tail) => tail === '' || tail.split(/[ \t]+/).every((token) => PRODUCER_PATH_TOKEN.test(token));
70
- const carriesProducerBody = (text) =>
71
- KNOWN_PRODUCER_BODIES.some(
72
- (body) => text === body || (text.startsWith(`${body} `) && pathShapedTail(text.slice(body.length).trim())),
73
- );
57
+
58
+ // The exec prefix the trimmed text opens with ('' for none), and the rest after it.
59
+ const splitExecPrefix = (text) => {
60
+ const prefix = PRODUCER_EXEC_PREFIXES.find((p) => text.startsWith(p)) ?? '';
61
+ return [prefix, text.slice(prefix.length)];
62
+ };
63
+
64
+ // The rest after `body` (trimmed; '' when nothing follows), or null unless the text is the body, then nothing or one space.
65
+ const bodyRest = (text, body) => {
66
+ if (text === body) return '';
67
+ return text.startsWith(`${body} `) ? text.slice(body.length).trim() : null;
68
+ };
74
69
 
75
70
  // matchesCoverageProducer(cmd) → CLOSED-WORLD over the full command forms the kit emits, never a
76
- // substring probe: `echo "$AW_GIT_DIR/agent-workflow-lcov.info"`, a half-written reporter flag set,
77
- // or the path as a bare substring must all read as NOT a producer — otherwise the checker is
78
- // declared over a gate that writes nothing and then PASSES while certifying nothing.
71
+ // substring probe: `echo <body>`, the quoted body or a retired flag set is NOT a producer — else the
72
+ // checker is declared over a gate that writes nothing and then PASSES while certifying nothing.
79
73
  export const matchesCoverageProducer = (cmd) => {
80
74
  if (typeof cmd !== 'string') return false;
81
- const trimmed = cmd.trim();
82
- if (carriesProducerBody(trimmed)) return true;
83
- return PRODUCER_EXEC_PREFIXES.some((prefix) => trimmed.startsWith(prefix) && carriesProducerBody(trimmed.slice(prefix.length)));
75
+ const [, text] = splitExecPrefix(cmd.trim());
76
+ const rest = bodyRest(text, COVERAGE_PRODUCER_BODY);
77
+ return rest !== null && pathShapedTail(rest);
78
+ };
79
+
80
+ // retiredProducerFormOf(cmd) → { prefix (as written, or ''), tail (trimmed), pathShaped } when the
81
+ // trimmed cmd is no or one exec prefix, `node --test`, a retired flag set and nothing or one space and
82
+ // a rest; null for every other value. The switch carries only a path-shaped tail onto the body.
83
+ export const retiredProducerFormOf = (cmd) => {
84
+ if (typeof cmd !== 'string') return null;
85
+ const [prefix, text] = splitExecPrefix(cmd.trim());
86
+ for (const body of RETIRED_BODIES) {
87
+ const tail = bodyRest(text, body);
88
+ if (tail !== null) return { prefix, tail, pathShaped: pathShapedTail(tail) };
89
+ }
90
+ return null;
91
+ };
92
+
93
+ // unitTestsGuardFailure → the guard on every write of the body: run.mjs a regular file equal to `ownRun`, then the reporter
94
+ // a regular file, every folder on the way a directory (lstat: a link fails); null, or the first failing path and kind,
95
+ // worded by guardRemedy with the caller's upgrade.
96
+ const GUARD_PATHS = Object.freeze(['scripts/agent-workflow/run.mjs', 'scripts/agent-workflow/test-reporter/reporter.mjs']);
97
+ export const unitTestsGuardFailure = (projectDir, ownRun, { lstatSync, readFileSync }) => {
98
+ for (const rel of GUARD_PATHS) {
99
+ const parts = rel.split('/');
100
+ for (let depth = 1; depth <= parts.length; depth += 1) {
101
+ const at = parts.slice(0, depth).join('/');
102
+ const st = lstatSync(`${projectDir}/${at}`, { throwIfNoEntry: false });
103
+ if (st === undefined) return { path: rel, kind: 'absent' };
104
+ if (depth < parts.length ? !st.isDirectory() : !st.isFile()) return { path: at, kind: 'wrong-kind' };
105
+ }
106
+ if (rel === GUARD_PATHS[0] && !readFileSync(`${projectDir}/${rel}`).equals(readFileSync(ownRun))) return { path: rel, kind: 'earlier' };
107
+ }
108
+ return null;
84
109
  };
110
+ export const guardRemedy = (kind, upgrade) => ({
111
+ 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}.`,
112
+ earlier: `differs from this kit's — run ${upgrade}, whose configs step writes the current one`,
113
+ '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}`,
114
+ })[kind];
85
115
 
86
116
  // isCoverageProducerGate(gate) → the GATE-level producer question, and the ONE predicate every
87
117
  // consumer asks it through: does THIS declared entry write the lcov the canonical checker reads?
@@ -102,4 +132,9 @@ export const isCoverageProducerGate = (gate) => {
102
132
  if (gate.cmd.trim() === '' || /[\r\n]/.test(gate.cmd)) return false;
103
133
  return matchesCoverageProducer(gate.cmd) || gate.lcovProducer === true;
104
134
  };
135
+ // readsAsCoverageProducer(gate, claim) → the ONE producer question of a declared row, asked by both hosts: `claim` is
136
+ // the row's claim on the coverage-check tool through the checker-claim canon, and only a row that is not the tool
137
+ // (`'not-the-tool'`, equal by test to CHECKER_CLAIM.NOT_THE_TOOL) can produce — a checker, canonical or vendored,
138
+ // consumes the lcov it reads, so its marker claims nothing.
139
+ export const readsAsCoverageProducer = (gate, claim) => claim === 'not-the-tool' && isCoverageProducerGate(gate);
105
140
  // coverage-producer canon <<< END drift-guarded region
@@ -70,6 +70,8 @@ export const LIBRARY_ONLY_MODULES = Object.freeze({
70
70
  // The read half of the checker-gates verb: the same step-3 `tier` item runs the verb that uses it.
71
71
  'checker-gates-read.mjs': '/agent-workflow-kit upgrade',
72
72
  'profile-gap-screen.mjs': '/agent-workflow-kit recommendations',
73
+ // Named by references/modes/upgrade.md as the list of the old flat names; the upgrade's scripts op removes them.
74
+ 'script-priors.mjs': '/agent-workflow-kit upgrade',
73
75
  });
74
76
 
75
77
  // The frozen refusal line. One line, names the module, names the command.
@@ -0,0 +1,99 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { lstatSync, readFileSync, readdirSync, unlinkSync } from 'node:fs';
3
+ import { join, posix } from 'node:path';
4
+ import { lstatNoFollow } from '../atomic-write.mjs';
5
+ import { stripGitLocationEnv } from '../git-env.mjs';
6
+ import { DEPLOYED_SCRIPTS, KIT_SCRIPTS_DIR, SCRIPTS_DIR } from '../node-evidence.mjs';
7
+ import { PRIOR_FILES, SCRIPT_PRIORS, digestOf } from '../script-priors.mjs';
8
+
9
+ const DEPLOYED_BY_NAME = new Map(DEPLOYED_SCRIPTS.map((entry) => [posix.basename(entry.path), entry]));
10
+ const COMMAND = DEPLOYED_SCRIPTS.find((entry) => !entry.module);
11
+ const normalizeBody = (bytes) => String(bytes).replaceAll('\r\n', '\n');
12
+ const flatPath = (name) => `${SCRIPTS_DIR}/${name}`;
13
+ const isRegular = (cwd, rel, lstat) => lstatNoFollow(join(cwd, rel), lstat)?.isFile() === true;
14
+ const errorCode = (error) => error.code ?? error.message;
15
+
16
+ export const isRetiredKitScript = (name, bytes, kitRoot, read = readFileSync) => {
17
+ const digest = digestOf(normalizeBody(bytes));
18
+ if (SCRIPT_PRIORS.some((row) => row.file === name && row.digest === digest)) return true;
19
+ const entry = DEPLOYED_BY_NAME.get(name);
20
+ return Boolean(entry && digest === digestOf(normalizeBody(read(join(kitRoot, entry.bundled)))));
21
+ };
22
+
23
+ const keptLine = (name, rel, dryRun) => `${flatPath(name)}: ${dryRun ? 'would be kept' : 'kept'} — ${rel} is not placed yet`;
24
+ const removedLine = (name, dryRun) => `${flatPath(name)}: ${dryRun ? 'would be removed' : 'removed'} — the kit's scripts live in ${KIT_SCRIPTS_DIR}/`;
25
+ const foreignLine = (name) => `${flatPath(name)}: differs from every body this kit knows it shipped — not the kit's, left as it stands; the kit's checks now run from ${KIT_SCRIPTS_DIR}/`;
26
+
27
+ export const suiteLines = (cwd, classified, deps = {}) => {
28
+ const lstat = deps.lstat ?? lstatSync;
29
+ return (deps.readdir ?? readdirSync)(join(cwd, SCRIPTS_DIR)).filter((name) => name.endsWith('.test.mjs'))
30
+ .filter((name) => (!PRIOR_FILES.includes(name) || classified.get(name) === 'foreign') && isRegular(cwd, flatPath(name), lstat))
31
+ .sort().map((name) => `${flatPath(name)}: a suite of your own — the kit's hook runs no suite; add node --test ${flatPath(name)} to scripts/pre-commit.local to keep it on every commit`);
32
+ };
33
+
34
+ const askGit = (cwd, args, deps) => {
35
+ const env = Object.fromEntries(Object.entries(stripGitLocationEnv(process.env)).filter(([key]) => key !== 'NODE_TEST_CONTEXT'));
36
+ return (deps.git ?? spawnSync)('git', args, { cwd, env, encoding: 'utf8' }) ?? {};
37
+ };
38
+ const answered = (result, status) => !result.error && !result.signal && result.status === status;
39
+
40
+ export const grepLines = (cwd, deps = {}) => {
41
+ const result = askGit(cwd, ['rev-parse', '--is-inside-work-tree'], deps);
42
+ if (answered(result, 0) && String(result.stdout).trim() === 'true') return [
43
+ `other files naming an old path: git grep -n -F --untracked ${PRIOR_FILES.map((name) => `-e ${name}`).join(' ')} -- . ':!${KIT_SCRIPTS_DIR}'`,
44
+ 'git grep lists tracked and untracked files git does not ignore; the hooks dir and ignored files are yours to check',
45
+ ];
46
+ if (answered(result, 128) || (answered(result, 0) && String(result.stdout).trim() === 'false')) return ['this project is outside a git work tree; check other files naming an old path by hand'];
47
+ return [`whether this project is in a git work tree could not be confirmed (${result.error ? errorCode(result.error) : result.signal ?? result.status ?? 'no result'}); check other files naming an old path by hand`];
48
+ };
49
+
50
+ export const commitLines = (cwd, removed, deps = {}) => {
51
+ if (!answered(askGit(cwd, ['check-ignore', '-q', KIT_SCRIPTS_DIR], deps), 1)) return [];
52
+ return [`commit ${KIT_SCRIPTS_DIR}/${removed.length ? `, the removed files ${removed.map(flatPath).join(', ')}` : ''} and, as this upgrade changed them, docs/ai/gates.json and package.json as one change; merge it into every branch still committed or installed on`];
53
+ };
54
+
55
+ export const retireScripts = ({ cwd, kitRoot, dryRun = false, deps = {}, placedScripts = [], placements = [] }) => {
56
+ const lstat = deps.lstat ?? lstatSync;
57
+ const read = deps.readFile ?? readFileSync;
58
+ const standing = (rel) => (dryRun && placedScripts.includes(rel)) || isRegular(cwd, rel, lstat);
59
+ const commandStands = standing(COMMAND.deployed);
60
+ const classified = new Map();
61
+ const removed = [];
62
+ const lines = [];
63
+ for (const name of PRIOR_FILES) {
64
+ const rel = flatPath(name);
65
+ const stat = lstatNoFollow(join(cwd, rel), lstat);
66
+ if (stat === null) continue;
67
+ if (!stat.isFile()) {
68
+ lines.push(`${rel}: ${stat.isSymbolicLink() ? 'a symlink' : stat.isDirectory() ? 'a directory' : 'not a regular file'} — left as it stands`);
69
+ continue;
70
+ }
71
+ const owned = (() => {
72
+ try {
73
+ return isRetiredKitScript(name, read(join(cwd, rel)), kitRoot, read);
74
+ } catch (error) {
75
+ lines.push(`${rel}: could not be read (${errorCode(error)}) — left as it stands`);
76
+ return null;
77
+ }
78
+ })();
79
+ if (owned === null) continue;
80
+ classified.set(name, owned ? 'kit' : 'foreign');
81
+ if (!owned) { lines.push(foreignLine(name)); continue; }
82
+ const replacement = DEPLOYED_BY_NAME.get(name);
83
+ const missing = !commandStands ? COMMAND.deployed : replacement && !standing(replacement.deployed) ? replacement.deployed : null;
84
+ if (missing) { lines.push(keptLine(name, missing, dryRun)); continue; }
85
+ if (!dryRun) {
86
+ try {
87
+ (deps.unlink ?? unlinkSync)(join(cwd, rel));
88
+ } catch (error) {
89
+ if (error.code !== 'ENOENT') lines.push(`${rel}: not removed (${errorCode(error)}) — left for the next run`);
90
+ continue;
91
+ }
92
+ }
93
+ removed.push(name);
94
+ lines.push(removedLine(name, dryRun));
95
+ }
96
+ if (removed.length) lines.push(...suiteLines(cwd, classified, deps), ...grepLines(cwd, deps));
97
+ if (removed.length || placements.length) lines.push(...commitLines(cwd, removed, deps));
98
+ return { removed, lines };
99
+ };
@@ -1,9 +1,14 @@
1
- // scripts.mjs — the upgrade's `scripts` op: every kit script of a deployment, the hook installer set
2
- // included, kept current by the one rule. Each family file is surveyed by proof before any write:
3
- // absent, current, prior (a body SCRIPT_PRIORS catalogs for its name) or edited. On every plain run a
4
- // prior is refreshed, an edited one replaced in place and an absent one placed create-only, with no
5
- // question and no copy kept; a current one is left. The installer set is written first; after the last
6
- // write the project's own rotator brings the ADR store current (`--ensure-current`). It never imports
1
+ // scripts.mjs — the upgrade's `scripts` op: every kit script of a deployment, the hook installer
2
+ // included, kept current by the one rule in the kit folder scripts/agent-workflow/. The family is the
3
+ // manifest's deployed entries (node-evidence.mjs) less the spec layer's modules, the test reporter's and the
4
+ // command run.mjs, which the specs op places. Each family file is
5
+ // surveyed by proof before any write: absent, current, prior (a body the catalog lists for its manifest
6
+ // path) or edited. On every plain run a prior is refreshed, an edited one replaced in place and an
7
+ // absent one placed create-only, with no question and no copy kept; a current one is left. A project
8
+ // that did not accept the enforcement scripts gets every seed entry, the rotator and what it loads. The
9
+ // installer is written first, then every file after the family files it imports; after the last write
10
+ // the project's own rotator brings the ADR store current (`--ensure-current`); last, retired.mjs removes
11
+ // the kit's old flat files from scripts/ (distribution-files, part flat-move). It never imports
7
12
  // ensure-specs.mjs or ensure-configs.mjs: the CLI composes this op from the module's index, and
8
13
  // ensure-specs.mjs takes its channel and its lines from there.
9
14
  //
@@ -11,68 +16,69 @@
11
16
 
12
17
  import { spawnSync } from 'node:child_process';
13
18
  import { lstatSync, readFileSync } from 'node:fs';
14
- import { join } from 'node:path';
19
+ import { join, posix } from 'node:path';
15
20
  import { lstatNoFollow, writeContainedFileAtomic, writeProjectFileCreateOnly } from '../atomic-write.mjs';
16
- import { composeFailure, composeOutcome, nodeEvidenceRefusal, probeSeedTarget, tmpNote } from '../ensure-ops.mjs';
17
- import { BUNDLED_SCRIPT_NAMES } from '../node-evidence.mjs';
18
- import { CHECKER_PAIR, INSTALLER_SET, READER_PAIR, SCRIPT_PRIORS, classifyDeployedScript } from '../script-priors.mjs';
21
+ import { bundledImportsOf, composeFailure, composeOutcome, dependenciesFirst, nodeEvidenceRefusal, probeSeedTarget, tmpNote } from '../ensure-ops.mjs';
22
+ import { DEPLOYED_SCRIPTS, INSTALLER_REL, KIT_SCRIPTS_DIR, SCRIPTS_DIR } from '../node-evidence.mjs';
23
+ import { SCRIPT_PRIORS, classifyDeployedScript } from '../script-priors.mjs';
19
24
  import { VEHICLES_REL } from '../vehicle-settings.mjs';
25
+ import { retireScripts } from './retired.mjs';
20
26
 
21
27
  const OP = 'scripts';
22
- const SCRIPTS_DIR = 'scripts';
23
- const BUNDLED = ['references', 'scripts'];
24
28
  // Where an edit meant to last goes: the installer's in the local hook file, every other file's beside it.
25
29
  export const SCRIPT_CHANNEL = 'a script or suite of your own under its own name in scripts/, or a config the script reads';
26
30
  export const LOCAL_HOOK_CHANNEL = 'the local hook file scripts/pre-commit.local, which the commit hook runs first';
27
31
  export const VEHICLE_CHANNEL = VEHICLES_REL;
28
32
  export const AGENT_CHANNEL = '.claude/agents/<name>.local.md with a name: of its own';
29
33
  export const HOOK_CHANNEL = '.claude/hooks/<name>.local.mjs';
30
- // The family files memory copies on Node evidence alone, accepted or not (the suite derives them).
31
- export const SEED_NAMES = Object.freeze(['_expect-shim.mjs', 'archive-decisions.mjs', 'archive-decisions.test.mjs', 'markdown-blocks.mjs']);
32
- const ROTATOR = 'archive-decisions.mjs';
33
- const PAIRS = new Set([...READER_PAIR, ...CHECKER_PAIR]);
34
- // The family in write order: the installer set, then every other bundled name in code-unit order.
35
- const FAMILY = Object.freeze([...INSTALLER_SET, ...BUNDLED_SCRIPT_NAMES.filter((name) => !PAIRS.has(name) && !INSTALLER_SET.includes(name)).sort()]);
36
- const LOCAL_IMPORT = /(?:from|import)\s*\(?\s*'\.\/([^']+)'/g;
34
+ const ROTATOR = 'archives/archive-decisions.mjs';
35
+ // The family: every deployed entry outside the specs op's files (its three modules and the command), in manifest order.
36
+ const SPECS_MODULES = ['spec-schema', 'docs-size', 'test-reporter'];
37
+ const FAMILY = DEPLOYED_SCRIPTS.filter((e) => e.module && !SPECS_MODULES.includes(e.module));
38
+ // The manifest paths a run of a component that is not accepted judges: the rotator and what it loads.
39
+ export const SEED_NAMES = Object.freeze(FAMILY.filter((e) => e.seed).map((e) => e.path));
40
+ const FOLDERS = [...new Set([SCRIPTS_DIR, KIT_SCRIPTS_DIR, ...FAMILY.map((e) => posix.dirname(e.deployed))])];
37
41
 
38
42
  const causeOf = (err) => String((err && err.message) || err);
39
- const relOf = (name) => `${SCRIPTS_DIR}/${name}`;
40
43
  const kindOfDir = (st) => (st.isSymbolicLink() ? 'a symlink' : st.isFile() ? 'a regular file' : 'not a directory');
41
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`);
42
45
 
43
46
  // ── the survey: the component first, then every family file by proof, nothing written ────────────
44
47
 
45
- // The seed files a run of a component that is not accepted judges: each standing one, and every seed
46
- // file reached from one through its bundled `./` imports, so every seed file the run leaves loads.
47
- const seedClosure = (standing, bundleOf) => {
48
- const reached = new Set(standing);
49
- for (const name of reached) for (const [, dep] of bundleOf(name).toString('utf8').matchAll(LOCAL_IMPORT)) if (SEED_NAMES.includes(dep)) reached.add(dep);
50
- return reached;
48
+ // The installer first (it imports nothing), then each file after every family file it imports.
49
+ const inWriteOrder = (files) => [...files.filter((f) => f.rel === INSTALLER_REL), ...dependenciesFirst(files.filter((f) => f.rel !== INSTALLER_REL))];
50
+
51
+ // Each folder on the way, lstat-ed without following a link: → { refusal } | {}.
52
+ const surveyFolders = (cwd, lstat) => {
53
+ for (const rel of FOLDERS) {
54
+ const st = lstatNoFollow(join(cwd, rel), lstat);
55
+ if (st !== null && (!st.isDirectory() || st.isSymbolicLink())) return { refusal: wrongKind(`${rel}/`, kindOfDir(st)) };
56
+ }
57
+ return {};
51
58
  };
52
59
 
53
- // → { refusal } | { notPlaced } | { files, accepted }. A family path of another node kind is judged
54
- // before the component, so a linked family file never reads as not-placed.
60
+ // → { refusal } | { files, accepted }. A family path of another node kind is judged before the
61
+ // component, so a linked family file is never placed over.
55
62
  const survey = ({ cwd, kitRoot, deps, read, lstat }) => {
56
- const dir = lstatNoFollow(join(cwd, SCRIPTS_DIR), lstat);
57
- if (dir === null) return { notPlaced: true };
58
- if (!dir.isDirectory() || dir.isSymbolicLink()) return { refusal: wrongKind(`${SCRIPTS_DIR}/`, kindOfDir(dir)) };
59
- const probes = FAMILY.map((name) => ({ name, rel: relOf(name), probe: probeSeedTarget(join(cwd, SCRIPTS_DIR, name), lstat) }));
63
+ const folders = surveyFolders(cwd, lstat);
64
+ if (folders.refusal) return folders;
65
+ const probes = FAMILY.map((e) => ({ path: e.path, rel: e.deployed, bundled: e.bundled, probe: probeSeedTarget(join(cwd, e.deployed), lstat) }));
60
66
  const wrong = probes.find((f) => f.probe.wrongKind);
61
67
  if (wrong) return { refusal: wrongKind(wrong.rel, wrong.probe.wrongKind) };
62
- if (!probes.some((f) => f.probe.present)) return { notPlaced: true };
63
- const accepted = probes.some((f) => f.probe.present && !SEED_NAMES.includes(f.name));
64
- const bundles = new Map();
65
- for (const { name, rel } of probes) {
68
+ const flatInstaller = probeSeedTarget(join(cwd, SCRIPTS_DIR, posix.basename(INSTALLER_REL)), lstat);
69
+ const accepted = probes.some((f) => f.probe.present && !SEED_NAMES.includes(f.path)) || (flatInstaller.present && !flatInstaller.wrongKind);
70
+ const byPath = new Map();
71
+ for (const f of probes) {
66
72
  try {
67
- bundles.set(name, read(join(kitRoot, ...BUNDLED, name)));
73
+ const bundle = read(join(kitRoot, f.bundled));
74
+ byPath.set(f.path, { ...f, bundle, imports: bundledImportsOf(f.path, bundle) });
68
75
  } catch (err) {
69
- return { refusal: composeFailure(OP, 'bundle-unreadable', `${rel}: the bundled script could not be read, so nothing was written — reinstall the kit. ${causeOf(err)}`) };
76
+ return { refusal: composeFailure(OP, 'bundle-unreadable', `${f.rel}: the bundled script could not be read, so nothing was written — reinstall the kit. ${causeOf(err)}`) };
70
77
  }
71
78
  }
72
- const judged = accepted ? new Set(FAMILY) : seedClosure(probes.filter((f) => f.probe.present).map((f) => f.name), (name) => bundles.get(name));
73
- const files = probes.filter((f) => judged.has(f.name)).map(({ name, rel, probe }) => {
79
+ const files = inWriteOrder([...byPath.values()]).filter((f) => accepted || SEED_NAMES.includes(f.path)).map(({ path, rel, bundle, probe }) => {
74
80
  const bytes = probe.present ? read(join(cwd, rel)) : undefined;
75
- return { name, rel, bundle: bundles.get(name), state: probe.present ? classifyDeployedScript(bytes, name, bundles.get(name), deps.priors ?? SCRIPT_PRIORS) : 'absent' };
81
+ return { path, rel, bundle, state: probe.present ? classifyDeployedScript(bytes, path, bundle, deps.priors ?? SCRIPT_PRIORS) : 'absent' };
76
82
  });
77
83
  return { files, accepted };
78
84
  };
@@ -87,14 +93,14 @@ const HEADS = { prior: 'matches a body an earlier release shipped', custom: 'dif
87
93
  const channelOf = (f) => (f.state === 'derived' ? `; its model and effort are set in ${VEHICLE_CHANNEL}`
88
94
  : f.state === 'agent' ? `; a vehicle of your own goes in ${AGENT_CHANNEL}`
89
95
  : f.state === 'hook' ? `; a hook of your own goes in ${HOOK_CHANNEL}`
90
- : f.state === 'custom' ? `; an edit meant to last goes in ${f.name === INSTALLER_SET[0] ? LOCAL_HOOK_CHANNEL : SCRIPT_CHANNEL}` : '');
96
+ : f.state === 'custom' ? `; an edit meant to last goes in ${f.rel === INSTALLER_REL ? LOCAL_HOOK_CHANNEL : SCRIPT_CHANNEL}` : '');
91
97
  export const fileLine = (f, fate, dryRun) => {
92
98
  if (fate === 'stood') return `${f.rel}: appeared while this run was placing it — the bundled body stands, nothing written`;
93
99
  const [verb, done] = VERBS[f.state];
94
100
  const tail = fate === 'written' ? done : dryRun ? `would be ${done}` : `not ${verb}; ${fate === 'refused' ? 'its write was refused (above)' : 'the run stopped before it'}`;
95
101
  return `${f.rel}: ${HEADS[f.state]} — ${tail}${channelOf(f)}`;
96
102
  };
97
- const NOT_ACCEPTED = `${SCRIPTS_DIR}/: the enforcement scripts were not accepted in this project, so no other kit script is placed`;
103
+ const NOT_ACCEPTED = `${KIT_SCRIPTS_DIR}/: the enforcement scripts were not accepted in this project, so no other kit script is placed`;
98
104
  // The hook-run line, once after the file lines of a run that wrote (or, dry, would write) a file.
99
105
  export const hookLine = (accepted, dryRun) => (accepted
100
106
  ? (dryRun ? 'the commit hook runs the files named above, so writing them may stop the next commit' : 'the commit hook runs the files written above, so they may stop the next commit')
@@ -120,7 +126,7 @@ const writeAll = ({ cwd, files, deps, read }) => {
120
126
  }
121
127
  notes.push(...tmpNote(f.rel, result.tmpLeftBehind));
122
128
  if (f.state === 'absent' && !result.created) {
123
- if (classifyDeployedScript(read(join(cwd, f.rel)), f.name, f.bundle) !== 'current') {
129
+ if (classifyDeployedScript(read(join(cwd, f.rel)), f.path, f.bundle) !== 'current') {
124
130
  fates.set(f.rel, 'refused');
125
131
  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`] };
126
132
  }
@@ -145,12 +151,21 @@ const writeRun = ({ cwd, files, accepted, dryRun, deps, read }) => {
145
151
  // The rotator the run just left on the bundled body brings the store current; its output is relayed
146
152
  // keyed on its contracted summary, the last standard output line.
147
153
  const STORE = 'ADR store: ';
148
- const ENSURE = `${SCRIPTS_DIR}/${ROTATOR} --ensure-current`;
154
+ const ROTATOR_REL = `${KIT_SCRIPTS_DIR}/${ROTATOR}`;
155
+ const ENSURE = `${ROTATOR_REL} --ensure-current`;
149
156
  const WOULD_STORE = `${STORE}${ENSURE} would run after the writes, bringing the store current or writing nothing when it already is`;
150
157
  const outputLines = (text) => String(text ?? '').split(/\r?\n/).filter((line) => line !== '');
158
+ // A runner that throws before it returns a result ended with that error, as a result carrying one.
159
+ const spawnOutcome = (spawn, args, opts) => {
160
+ try {
161
+ return spawn(process.execPath, args, opts) ?? { error: new Error('the spawn returned no result') };
162
+ } catch (error) {
163
+ return { error };
164
+ }
165
+ };
151
166
  // → { brought, lines, failure? }
152
167
  const runStore = (cwd, deps) => {
153
- const r = (deps.spawnSync ?? spawnSync)(process.execPath, [join(cwd, SCRIPTS_DIR, ROTATOR), '--ensure-current'], { cwd, encoding: 'utf8' });
168
+ const r = spawnOutcome(deps.spawnSync ?? spawnSync, [join(cwd, ROTATOR_REL), '--ensure-current'], { cwd, encoding: 'utf8' });
154
169
  const [out, err] = [outputLines(r.stdout), outputLines(r.stderr)];
155
170
  const ended = r.error ? `ended with an error (${causeOf(r.error)})` : r.signal ? `was killed by signal ${r.signal}` : r.status !== 0 ? `exited with code ${r.status}` : null;
156
171
  if (ended) return { failure: `${ENSURE} ${ended} — the ADR store was not confirmed current`, lines: [...err, ...out].map((line) => STORE + line) };
@@ -160,24 +175,25 @@ const runStore = (cwd, deps) => {
160
175
 
161
176
  // ── the op ────────────────────────────────────────────────────────────────────────────────────────
162
177
 
163
- export const ensureScripts = ({ cwd, kitRoot, dryRun = false, deps = {} }) => {
178
+ export const ensureScripts = ({ cwd, kitRoot, dryRun = false, deps = {}, placedScripts = [] }) => {
164
179
  const lstat = deps.lstat ?? lstatSync;
165
180
  const read = deps.readFile ?? readFileSync;
166
181
  const refusal = nodeEvidenceRefusal(OP, cwd, lstat);
167
182
  if (refusal) return refusal;
168
183
  const found = survey({ cwd, kitRoot, deps, read, lstat });
169
184
  if (found.refusal) return found.refusal;
170
- if (found.notPlaced) return composeOutcome(OP, 'not-placed', [`${SCRIPTS_DIR}/: no kit script stands in it, so none is placed`], false);
171
185
  const { files, accepted } = found;
172
186
  const current = files.filter((f) => f.state === 'current').length;
173
187
  const r = writeRun({ cwd, files, accepted, dryRun, deps, read });
174
- const body = [...r.lines, ...(current > 0 ? [`${SCRIPTS_DIR}/: ${current} other kit scripts are already the bundled body — nothing written`] : []), ...(accepted ? [] : [NOT_ACCEPTED])];
188
+ const body = [...r.lines, ...(current > 0 ? [`${KIT_SCRIPTS_DIR}/: ${current} other kit scripts are already the bundled body — nothing written`] : []), ...(accepted ? [] : [NOT_ACCEPTED])];
175
189
  if (r.failure) return composeFailure(OP, r.failure[0], r.failure[1], ...body, ...r.tail);
176
- const rotator = files.some((f) => f.name === ROTATOR);
190
+ const rotator = files.some((f) => f.path === ROTATOR);
177
191
  const store = !rotator ? { lines: [] } : dryRun ? { lines: [WOULD_STORE] } : runStore(cwd, deps);
178
192
  if (store.failure) return composeFailure(OP, 'adr-store-not-current', store.failure, ...body, ...r.tail, ...store.lines);
179
193
  const landed = (state) => (dryRun ? r.due : r.written).some((f) => f.state === state);
194
+ const placements = (dryRun ? r.due : r.written).filter((f) => f.state === 'absent').map((f) => f.rel);
195
+ const retired = retireScripts({ cwd, kitRoot, dryRun, deps, placedScripts: [...placedScripts, ...placements], placements });
180
196
  const token = landed('absent') ? (dryRun ? 'would-seed' : 'seeded')
181
- : landed('prior') || landed('custom') || store.brought ? (dryRun ? 'would-refresh' : 'refreshed') : 'already-present';
182
- return composeOutcome(OP, token, [...body, ...r.tail, ...store.lines], false);
197
+ : landed('prior') || landed('custom') || store.brought || retired.removed.length ? (dryRun ? 'would-refresh' : 'refreshed') : 'already-present';
198
+ return composeOutcome(OP, token, [...body, ...r.tail, ...store.lines, ...retired.lines], false);
183
199
  };
@@ -6,13 +6,13 @@
6
6
  // autonomy docs/ai/autonomy.json seed-if-missing (same)
7
7
  // vehicles docs/ai/vehicles.json seed-if-missing (same)
8
8
  // executor .claude/agents/executor.md judged against docs/ai/vehicles.json, never written: a differing body is pending
9
- // scripts scripts/<every kit script> once a kit script outside the seed names stands there, every file not current
10
- // + the installer set written with no question and no copy kept; installer set first; on a
11
- // declined offer only the standing seed files and the modules they import;
12
- // then the project's rotator brings the ADR store current (--ensure-current)
13
- // specs scripts/<spec layer> reader + checker pairs, with no question and no copy kept:
9
+ // specs scripts/<spec layer> reader + checker pairs, the test reporter and run.mjs, with no question and no copy kept:
14
10
  // + docs/ai/specs/index.md a shipped prior refreshed, an edited one replaced, an absent
15
11
  // one placed; then the store root seeded create-only
12
+ // scripts scripts/<every kit script> once a kit script outside the seed names, or the old flat installer, stands there, every file not current
13
+ // + the installer set written with no question and no copy kept; installer set first; on a
14
+ // declined offer every seed file, the rotator included, and no other;
15
+ // then the project's rotator brings the ADR store current (--ensure-current)
16
16
  // rules docs/ai/rules/<theme>.md the kit file seeded, refreshed on a shipped prior body, or any
17
17
  // + effective/ + sources.json other body replaced, with no question and no copy kept; with no
18
18
  // local file the effective copy and its record rebuilt; with one
@@ -21,10 +21,6 @@
21
21
  // a project hook module that is not the bundled one, a write
22
22
  // the project's own checker rejects is put back
23
23
  //
24
- // Each was prose in references/modes/upgrade.md that an agent performed by hand. One command instead
25
- // of one per ensure is deliberate: independent runs would be as many chances to skip one, and the mode
26
- // doc now has a single invocation point whose outcome lines it relays.
27
- //
28
24
  // The contract (pinned by this module's tests):
29
25
  // • --reconcile is REQUIRED. A bare run is a usage error, so nothing writes by accident.
30
26
  // • --dry-run reports `would-*` tokens and writes nothing — never a write token.
@@ -33,9 +29,7 @@
33
29
  // • The deployment gate runs ONCE, before any op: an absent/symlinked docs/ai stops the whole run
34
30
  // with the gate's own message rather than one copy of it per op.
35
31
  //
36
- // Output is ENGLISH/structured (repo-artifact Hard Constraint); the agent localizes when narrating.
37
32
  // Exit codes: 0 every op fine · 1 an op failed, or the deployment gate stopped the run · 2 usage.
38
- // main(argv, ctx) → { code, stdout, stderr }; cwd + fs are injectable for host-independent tests.
39
33
  //
40
34
  // Dependency-free, Node >= 22. No side effects on import (the isDirectRun idiom).
41
35
 
@@ -82,7 +76,7 @@ refreshed in place. Four ops refresh instead: the orchestration onboarding note,
82
76
  note with no question and no copy kept, every recipe kept (a differing note's line names where a note of your
83
77
  own goes); the spec-layer reader and checker pairs, with no question and no copy kept: a body a release shipped
84
78
  is refreshed, an edited one replaced (its line names where an edit meant to last goes) and an absent one placed,
85
- the reader pair, then the checker pair, then the spec store root seeded create-only; the project rules
79
+ the reader pair, then the checker pair, then the test reporter, then run.mjs, then the spec store root seeded create-only; the project rules
86
80
  kit file, refreshed while its bytes are a body a release shipped and any other body replaced by the template,
87
81
  with no question and no copy kept, the effective file rebuilt as its copy and recorded where no local file
88
82
  exists; and the navigator index — a GENERATED artifact, regenerated
@@ -91,13 +85,13 @@ the project's own checker judges the navigator and a write it rejects is put bac
91
85
  The executor ensure writes nothing: a placed .claude/agents/executor.md whose bytes differ from the
92
86
  body derived from docs/ai/vehicles.json is pending and an absent one is not placed here — the
93
87
  advisor's agents item writes the derived body.
94
- A fifth writes too: once a kit script outside the seed names stands in scripts/, the enforcement-script
95
- ensure writes every kit script that is not the bundled body, the hook installer and its two suites
96
- first, with no question and no copy kept: a body a release shipped is refreshed, an edited one replaced
97
- (its line names where an edit meant to last goes) and an absent one placed; on a project that
98
- declined the enforcement offer, its standing seed files are kept current the same way, with an
99
- absent module they import placed, and no other kit script is placed; after the writes the project's
100
- scripts/archive-decisions.mjs --ensure-current brings the ADR store current, an older layout moved.
88
+ A fifth writes too: once a kit script outside the seed names stands in scripts/agent-workflow/, or the hook installer under its old
89
+ flat name in scripts/, the enforcement-script ensure writes every kit script that is not the bundled body, the hook installer first,
90
+ with no question and no copy kept: a body a release shipped is refreshed, an edited one replaced (its line names where an edit meant
91
+ to last goes) and an absent one placed; on a project that declined the enforcement offer, every seed file, the rotator included,
92
+ is kept current the same way, an absent one placed, and no other kit script is placed; after the writes the project's
93
+ scripts/agent-workflow/archives/archive-decisions.mjs --ensure-current brings the ADR store current, an older layout moved; last, unless the run
94
+ failed, and only while scripts/agent-workflow/run.mjs stands, each of the kit's old flat files in scripts/ is removed when its replacement stands or it has none (a dry run removes nothing).
101
95
 
102
96
  Exit codes: 0 every op fine; 1 an op failed (its line says so) or there is no deployment here; 2 usage.`;
103
97
 
@@ -151,8 +145,14 @@ const runOne = (op, args) => {
151
145
  // Run every op in ENSURE_OPS order. A throw from one op becomes THAT op's failed outcome — the
152
146
  // remaining ops still run, because a project missing its gate declaration should not also be left
153
147
  // without its autonomy seed just because the first ensure hit an unreadable file. → the outcomes.
154
- export const runEnsures = ({ cwd, kitRoot, dryRun, deps, only }) =>
155
- (only ? [only] : ENSURE_OPS).map((op) => runOne(op, { cwd, kitRoot, dryRun, deps }));
148
+ export const runEnsures = ({ cwd, kitRoot, dryRun, deps, only }) => {
149
+ const outcomes = [];
150
+ for (const op of only ? [only] : ENSURE_OPS) {
151
+ const specs = outcomes.find((result) => result.op === 'specs' && !result.failed);
152
+ outcomes.push(runOne(op, { cwd, kitRoot, dryRun, deps, placedScripts: op === 'scripts' ? specs?.placedScripts ?? [] : [] }));
153
+ }
154
+ return outcomes;
155
+ };
156
156
 
157
157
  const render = (outcomes, { dryRun, only }) => {
158
158
  // The banner names the tool + the flag it ran under (both machine tokens the L2 rule exempts);