@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
@@ -4,12 +4,12 @@ The non-obvious traps — scan these before bootstrapping or upgrading. Each is
4
4
 
5
5
  - **Source vs target directory.** Templates and scripts are read from the skill's own dir (`${CLAUDE_SKILL_DIR}/` in Claude Code, the `SKILL.md` folder elsewhere). The **working directory is the target project** — never write kernel files back into the skill.
6
6
  - **The `Co-Authored-By` trailer is added by the harness, not by prose.** When attribution is `off`, a doc directive alone won't stop it — for Claude Code the advisor's `attribution` item sets the harness setting in the project's `.claude/settings.json`, on the user's yes after its check. Other tools: disable their equivalent co-author/footer setting.
7
- - **Hidden mode must never touch `package.json`.** Editing it is a *tracked* change and leaks the whole system. Hidden mode wires nothing into `package.json`; the pre-commit hook (untracked in `.git/hooks/`) calls `node scripts/<x>.mjs` directly. After hiding, **verify `git status` shows the artifacts as ignored**.
7
+ - **Hidden mode must never touch `package.json`.** Editing it is a *tracked* change and leaks the whole system. Hidden mode wires nothing into `package.json`; the pre-commit hook (untracked in `.git/hooks/`) calls `node scripts/agent-workflow/run.mjs <name>` directly. After hiding, **verify `git status` shows the artifacts as ignored**.
8
8
  - **Hidden mode is project-local, and the hide tool owns the known footprint.** `tools/hide-footprint.mjs` writes **one managed block** in the **project-local `.git/info/exclude`** — never the machine-global `core.excludesFile` (which would silently affect every repo on the host; **AD-014** amends **AD-006**; only its `--remove-global` mode, the `footprint-global` item, edits that file). It hides the kit's own artifacts **and** the known external AI/agent footprint (the `KNOWN_FOOTPRINT` table in [contracts](${CLAUDE_SKILL_DIR}/references/contracts.md#visibility-contract)). A **tracked** file is **never silently un-tracked** — the tool prints the `git rm --cached` it will not run. Never leak its internal marker / asks terms to the user; translate every outcome to plain language.
9
9
  - **`CLAUDE.md` is a symlink, not a copy.** `ln -s AGENTS.md CLAUDE.md` — single source, no duplication. A copy drifts; a symlink can't.
10
10
  - **Never overwrite an existing entry point or hook.** If `AGENTS.md` / `CLAUDE.md` already exist, **stop and ask** the user to merge vs replace — don't clobber. A non-marker hook stays; moving it aside is the user's step.
11
11
  - **Unrecognized invocations are read-only.** Only a **known** subcommand reaches its mode; the **bare** invocation bootstraps (and an existing `docs/ai/` makes it ask upgrade-vs-bootstrap first, never overwrite); **any other / ambiguous** token routes to `help` (read-only). A garbage invocation never writes. The mapping is pinned by `tools/commands.mjs` `routeInvocation` (unit-tested) — don't hand-route around it.
12
- - **Enforcement is offered on every project.** The dependency-free scripts are available because the agent host already runs the navigator; for the offer, the only skip condition is that the agent host cannot run them. The hook calls `node scripts/<x>.mjs`, so a committer without `node` on PATH gets the hook's own loud failure. **A skip names a PROVEN fact, never a proxy:** upgrade ensures judge Node by EVIDENCE — a root `package.json` OR any kit-seeded `scripts/*.mjs` already deployed — and the `skipped-no-node-evidence` line lists every probe that answered absent; a reason the tool could disprove is a tool defect. **A skip line that contradicts the observed tree is raised as a finding in the report, never pasted as neutral** — report the contradiction with the proven fact and do not build on the skip.
12
+ - **Enforcement is offered on every project.** The dependency-free scripts are available because the agent host already runs the navigator; for the offer, the only skip condition is that the agent host cannot run them. The hook calls `node scripts/agent-workflow/run.mjs <name>`, so a committer without `node` on PATH gets the hook's own loud failure. **A skip names a PROVEN fact, never a proxy:** upgrade ensures judge Node by EVIDENCE — Node evidence is a regular root `package.json`, or a regular file, every folder above it a plain directory, at one of the kit's flat script names in `scripts/` or at a deployed path in `scripts/agent-workflow/`; `skipped-no-node-evidence` only when the probe finds none, its line listing every probe that answered absent; a reason the tool could disprove is a tool defect. **A skip line that contradicts the observed tree is raised as a finding in the report, never pasted as neutral** — report the contradiction with the proven fact and do not build on the skip.
13
13
  - **Conversational language never translates artifacts.** It governs *dialogue only*. Code, identifiers, paths, commands, log output, abbreviations, and every deployed `docs/ai/` / `AGENTS.md` file stay in their source language. See [Communication contract](${CLAUDE_SKILL_DIR}/references/contracts.md#communication-contract).
14
14
  - **Never auto-commit.** Report quality-gate results and wait for explicit approval — in both modes.
15
15
  - **Never leak kit internals to the user — and a tool-COMPOSED user-facing line holds the same bar at the source.** No ADR ids, tool / function / operation names (`reconcile`, `inject`, `ensureSlot`), marker / slot / fragment / anchor terminology, or verbatim tool stderr **inside the human sentence** of anything the user reads. Translate every tool outcome into plain language a third-party user — who has never read this `SKILL.md` — can understand and act on (e.g. the kit-block refusal report in `${CLAUDE_SKILL_DIR}/references/modes/upgrade.md` step 3). The composed lines themselves are **user-grade** language: machine tokens and tool self-labels belong to the **machine-line channel** — the `[run-gates] status=…` grammar (`${CLAUDE_SKILL_DIR}/references/modes/gates.md`), a line's leading self-label/prefix, or a runnable command/path the user can act on — never mid-sentence; alarm words (`PARTIALLY`, `incomplete`, `failed`, `broken`, `persists`) render only in outcomes gated on a **detected abnormal condition**. ONE designed exception, stated not implied: the configuration ensures' LEADING outcome token — one closed-vocabulary token, a failure's closed cause word opening its detail line — is that contract's own machine slot, not a leak. The **verbatim**-paste contract stays: the agent pastes tool-composed outcome lines as written and never re-composes their facts — the lines are user-grade at the source, so pasting them verbatim IS the plain language.
@@ -16,7 +16,7 @@ revision: 1
16
16
  > (the slug mirrors the feature-slice or module name, `^[a-z0-9]+(-[a-z0-9]+)*$`) and replace every
17
17
  > section. NOT deployed on bootstrap — it stays in the skill home like `adr-record.md`. The full
18
18
  > schema (kinds, statuses, transitions, promotion, precedence) is the engine canon `references/specs.md`;
19
- > the deployed reader `scripts/spec-schema.mjs` is what decides well-formed.
19
+ > the deployed reader `scripts/agent-workflow/spec-schema/spec-schema.mjs` is what decides well-formed.
20
20
 
21
21
  ## Contract
22
22
 
@@ -65,8 +65,8 @@ the **new** ADR; governance is then computed automatically (no predecessor-file
65
65
 
66
66
  ## Commands
67
67
 
68
- - `node scripts/archive-decisions.mjs` — rotate: explode the oldest HOT entries beyond the cap into
68
+ - `node scripts/agent-workflow/run.mjs archive-decisions` — rotate: explode the oldest HOT entries beyond the cap into
69
69
  `adr/` records, then regenerate the navigator + `docs/ai/index.md`.
70
- - `node scripts/archive-decisions.mjs --write-navigator` — regenerate `docs/ai/adr/log.md` (and the
70
+ - `node scripts/agent-workflow/run.mjs archive-decisions --write-navigator` — regenerate `docs/ai/adr/log.md` (and the
71
71
  index) after authoring an ADR or editing a supersession, so `--check` stays green.
72
- - `node scripts/archive-decisions.mjs --check` — verify HOT cap + store integrity + navigator freshness.
72
+ - `node scripts/agent-workflow/run.mjs archive-decisions --check` — verify HOT cap + store integrity + navigator freshness.
@@ -24,7 +24,7 @@ import { planFor } from './jev-skill.mjs';
24
24
  import { SKILL_FILES, claudeDirOf, skillAccepted, skillState, skillTargets } from './jev-facts.mjs';
25
25
  import { findOnPath } from './detect-backends.mjs';
26
26
  import { consoleArgv } from './write-lanes.mjs';
27
- import { BUNDLED_SCRIPT_NAMES, INSTALLER_REL, SCRIPTS_REL, formatPlan, planGitHooks } from './git-hooks.mjs';
27
+ import { DEPLOYED_SCRIPTS, INSTALLER_REL, formatPlan, planGitHooks } from './git-hooks.mjs';
28
28
  import { ATTRIBUTION_HIDDEN, ATTRIBUTION_KEY, writeAttribution } from './attribution.mjs';
29
29
  import { globalRemovalOf, planGlobalRemoval } from './hide-footprint.mjs';
30
30
  import { isDirectRun } from './direct-run.mjs';
@@ -232,14 +232,18 @@ export const scopeOf = (variant, facts, deps = {}) => {
232
232
  for (let at = target.root; at !== target.base && covers(target.base, at); at = dirname(at)) directories.push(at);
233
233
  filePaths.push(target.path);
234
234
  }
235
- const scripts = join(facts.root, SCRIPTS_REL);
236
235
  if (GIT_VARIANTS.includes(variant)) {
237
- directories.splice(0, directories.length, ...(variant === 'hook-checks' ? [] : [scripts]));
238
- if (variant !== 'hook-checks') filePaths.push(...BUNDLED_SCRIPT_NAMES.map((name) => join(scripts, name)));
236
+ // Each deployed path under the kit folder, and each folder on its way below the root.
237
+ const copies = variant === 'hook-checks' ? [] : DEPLOYED_SCRIPTS.map(({ deployed }) => join(facts.root, deployed));
238
+ directories.splice(0);
239
+ for (const path of copies) {
240
+ for (let at = dirname(path); at !== facts.root && covers(facts.root, at) && !directories.includes(at); at = dirname(at)) directories.push(at);
241
+ }
242
+ filePaths.push(...copies);
239
243
  }
240
244
  const rules = ['--rules-check', join(facts.toolsDir, 'project-rules', 'rules-cli.mjs')];
241
245
  const layout = ['--layout-check', join(facts.toolsDir, 'source-size-check.mjs')];
242
- const flagSets = variant === 'hook-checks' ? [rules, layout, [...rules, ...layout]]
246
+ const flagSets = variant === 'hook-checks' ? [[], rules, layout, [...rules, ...layout]]
243
247
  : variant === 'commit-guard' ? [['--commit-guard', join(facts.toolsDir, 'commit-guard.mjs')]] : [[]];
244
248
  const runs = GIT_VARIANTS.includes(variant) ? flagSets.map((flags) => ['node', INSTALLER_REL, ...flags]) : [];
245
249
  return {
@@ -201,9 +201,11 @@ export const writeHostConfigFileAtomic = (dir, filename, body, deps = {}, opts =
201
201
  // writeProjectFileCreateOnly(root, rel, body, deps, opts) → { writtenPath: rel, created }. Gate =
202
202
  // create+verify the target's PARENT dir inside the project (a symlinked `scripts/` is a STOP, not a
203
203
  // write through it); root = the project dir; the write is create-only, so an existing file is left
204
- // exactly as it is and `created` says so.
204
+ // exactly as it is and `created` says so. The folders above the parent are walked for a link first, so
205
+ // the parent's `mkdir -p` never makes a folder through one.
205
206
  export const writeProjectFileCreateOnly = (root, rel, body, deps = {}, opts = {}) => {
206
207
  const dst = join(root, rel);
208
+ if (dirname(dst) !== root) assertContainedRealPath(root, dirname(dirname(dst)), { lstat: deps.lstat ?? lstatSync });
207
209
  assertCreatableDirSafe(dirname(dst), deps, opts);
208
210
  const { created, tmpLeftBehind } = writeContainedFileAtomic(root, dst, body, deps, { ...opts, createOnly: true, label: rel });
209
211
  return { writtenPath: rel, created, tmpLeftBehind };
@@ -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 and the command run.mjs,
4
+ // 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,68 @@
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 two modules and the command), in manifest order.
36
+ const FAMILY = DEPLOYED_SCRIPTS.filter((e) => e.module && e.module !== 'spec-schema' && e.module !== 'docs-size');
37
+ // The manifest paths a run of a component that is not accepted judges: the rotator and what it loads.
38
+ export const SEED_NAMES = Object.freeze(FAMILY.filter((e) => e.seed).map((e) => e.path));
39
+ const FOLDERS = [...new Set([SCRIPTS_DIR, KIT_SCRIPTS_DIR, ...FAMILY.map((e) => posix.dirname(e.deployed))])];
37
40
 
38
41
  const causeOf = (err) => String((err && err.message) || err);
39
- const relOf = (name) => `${SCRIPTS_DIR}/${name}`;
40
42
  const kindOfDir = (st) => (st.isSymbolicLink() ? 'a symlink' : st.isFile() ? 'a regular file' : 'not a directory');
41
43
  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
44
 
43
45
  // ── the survey: the component first, then every family file by proof, nothing written ────────────
44
46
 
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;
47
+ // The installer first (it imports nothing), then each file after every family file it imports.
48
+ const inWriteOrder = (files) => [...files.filter((f) => f.rel === INSTALLER_REL), ...dependenciesFirst(files.filter((f) => f.rel !== INSTALLER_REL))];
49
+
50
+ // Each folder on the way, lstat-ed without following a link: → { refusal } | {}.
51
+ const surveyFolders = (cwd, lstat) => {
52
+ for (const rel of FOLDERS) {
53
+ const st = lstatNoFollow(join(cwd, rel), lstat);
54
+ if (st !== null && (!st.isDirectory() || st.isSymbolicLink())) return { refusal: wrongKind(`${rel}/`, kindOfDir(st)) };
55
+ }
56
+ return {};
51
57
  };
52
58
 
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.
59
+ // → { refusal } | { files, accepted }. A family path of another node kind is judged before the
60
+ // component, so a linked family file is never placed over.
55
61
  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) }));
62
+ const folders = surveyFolders(cwd, lstat);
63
+ if (folders.refusal) return folders;
64
+ const probes = FAMILY.map((e) => ({ path: e.path, rel: e.deployed, bundled: e.bundled, probe: probeSeedTarget(join(cwd, e.deployed), lstat) }));
60
65
  const wrong = probes.find((f) => f.probe.wrongKind);
61
66
  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) {
67
+ const flatInstaller = probeSeedTarget(join(cwd, SCRIPTS_DIR, posix.basename(INSTALLER_REL)), lstat);
68
+ const accepted = probes.some((f) => f.probe.present && !SEED_NAMES.includes(f.path)) || (flatInstaller.present && !flatInstaller.wrongKind);
69
+ const byPath = new Map();
70
+ for (const f of probes) {
66
71
  try {
67
- bundles.set(name, read(join(kitRoot, ...BUNDLED, name)));
72
+ const bundle = read(join(kitRoot, f.bundled));
73
+ byPath.set(f.path, { ...f, bundle, imports: bundledImportsOf(f.path, bundle) });
68
74
  } 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)}`) };
75
+ 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
76
  }
71
77
  }
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 }) => {
78
+ const files = inWriteOrder([...byPath.values()]).filter((f) => accepted || SEED_NAMES.includes(f.path)).map(({ path, rel, bundle, probe }) => {
74
79
  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' };
80
+ return { path, rel, bundle, state: probe.present ? classifyDeployedScript(bytes, path, bundle, deps.priors ?? SCRIPT_PRIORS) : 'absent' };
76
81
  });
77
82
  return { files, accepted };
78
83
  };
@@ -87,14 +92,14 @@ const HEADS = { prior: 'matches a body an earlier release shipped', custom: 'dif
87
92
  const channelOf = (f) => (f.state === 'derived' ? `; its model and effort are set in ${VEHICLE_CHANNEL}`
88
93
  : f.state === 'agent' ? `; a vehicle of your own goes in ${AGENT_CHANNEL}`
89
94
  : 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}` : '');
95
+ : f.state === 'custom' ? `; an edit meant to last goes in ${f.rel === INSTALLER_REL ? LOCAL_HOOK_CHANNEL : SCRIPT_CHANNEL}` : '');
91
96
  export const fileLine = (f, fate, dryRun) => {
92
97
  if (fate === 'stood') return `${f.rel}: appeared while this run was placing it — the bundled body stands, nothing written`;
93
98
  const [verb, done] = VERBS[f.state];
94
99
  const tail = fate === 'written' ? done : dryRun ? `would be ${done}` : `not ${verb}; ${fate === 'refused' ? 'its write was refused (above)' : 'the run stopped before it'}`;
95
100
  return `${f.rel}: ${HEADS[f.state]} — ${tail}${channelOf(f)}`;
96
101
  };
97
- const NOT_ACCEPTED = `${SCRIPTS_DIR}/: the enforcement scripts were not accepted in this project, so no other kit script is placed`;
102
+ const NOT_ACCEPTED = `${KIT_SCRIPTS_DIR}/: the enforcement scripts were not accepted in this project, so no other kit script is placed`;
98
103
  // The hook-run line, once after the file lines of a run that wrote (or, dry, would write) a file.
99
104
  export const hookLine = (accepted, dryRun) => (accepted
100
105
  ? (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 +125,7 @@ const writeAll = ({ cwd, files, deps, read }) => {
120
125
  }
121
126
  notes.push(...tmpNote(f.rel, result.tmpLeftBehind));
122
127
  if (f.state === 'absent' && !result.created) {
123
- if (classifyDeployedScript(read(join(cwd, f.rel)), f.name, f.bundle) !== 'current') {
128
+ if (classifyDeployedScript(read(join(cwd, f.rel)), f.path, f.bundle) !== 'current') {
124
129
  fates.set(f.rel, 'refused');
125
130
  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
131
  }
@@ -145,12 +150,21 @@ const writeRun = ({ cwd, files, accepted, dryRun, deps, read }) => {
145
150
  // The rotator the run just left on the bundled body brings the store current; its output is relayed
146
151
  // keyed on its contracted summary, the last standard output line.
147
152
  const STORE = 'ADR store: ';
148
- const ENSURE = `${SCRIPTS_DIR}/${ROTATOR} --ensure-current`;
153
+ const ROTATOR_REL = `${KIT_SCRIPTS_DIR}/${ROTATOR}`;
154
+ const ENSURE = `${ROTATOR_REL} --ensure-current`;
149
155
  const WOULD_STORE = `${STORE}${ENSURE} would run after the writes, bringing the store current or writing nothing when it already is`;
150
156
  const outputLines = (text) => String(text ?? '').split(/\r?\n/).filter((line) => line !== '');
157
+ // A runner that throws before it returns a result ended with that error, as a result carrying one.
158
+ const spawnOutcome = (spawn, args, opts) => {
159
+ try {
160
+ return spawn(process.execPath, args, opts) ?? { error: new Error('the spawn returned no result') };
161
+ } catch (error) {
162
+ return { error };
163
+ }
164
+ };
151
165
  // → { brought, lines, failure? }
152
166
  const runStore = (cwd, deps) => {
153
- const r = (deps.spawnSync ?? spawnSync)(process.execPath, [join(cwd, SCRIPTS_DIR, ROTATOR), '--ensure-current'], { cwd, encoding: 'utf8' });
167
+ const r = spawnOutcome(deps.spawnSync ?? spawnSync, [join(cwd, ROTATOR_REL), '--ensure-current'], { cwd, encoding: 'utf8' });
154
168
  const [out, err] = [outputLines(r.stdout), outputLines(r.stderr)];
155
169
  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
170
  if (ended) return { failure: `${ENSURE} ${ended} — the ADR store was not confirmed current`, lines: [...err, ...out].map((line) => STORE + line) };
@@ -160,24 +174,25 @@ const runStore = (cwd, deps) => {
160
174
 
161
175
  // ── the op ────────────────────────────────────────────────────────────────────────────────────────
162
176
 
163
- export const ensureScripts = ({ cwd, kitRoot, dryRun = false, deps = {} }) => {
177
+ export const ensureScripts = ({ cwd, kitRoot, dryRun = false, deps = {}, placedScripts = [] }) => {
164
178
  const lstat = deps.lstat ?? lstatSync;
165
179
  const read = deps.readFile ?? readFileSync;
166
180
  const refusal = nodeEvidenceRefusal(OP, cwd, lstat);
167
181
  if (refusal) return refusal;
168
182
  const found = survey({ cwd, kitRoot, deps, read, lstat });
169
183
  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
184
  const { files, accepted } = found;
172
185
  const current = files.filter((f) => f.state === 'current').length;
173
186
  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])];
187
+ const body = [...r.lines, ...(current > 0 ? [`${KIT_SCRIPTS_DIR}/: ${current} other kit scripts are already the bundled body — nothing written`] : []), ...(accepted ? [] : [NOT_ACCEPTED])];
175
188
  if (r.failure) return composeFailure(OP, r.failure[0], r.failure[1], ...body, ...r.tail);
176
- const rotator = files.some((f) => f.name === ROTATOR);
189
+ const rotator = files.some((f) => f.path === ROTATOR);
177
190
  const store = !rotator ? { lines: [] } : dryRun ? { lines: [WOULD_STORE] } : runStore(cwd, deps);
178
191
  if (store.failure) return composeFailure(OP, 'adr-store-not-current', store.failure, ...body, ...r.tail, ...store.lines);
179
192
  const landed = (state) => (dryRun ? r.due : r.written).some((f) => f.state === state);
193
+ const placements = (dryRun ? r.due : r.written).filter((f) => f.state === 'absent').map((f) => f.rel);
194
+ const retired = retireScripts({ cwd, kitRoot, dryRun, deps, placedScripts: [...placedScripts, ...placements], placements });
180
195
  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);
196
+ : landed('prior') || landed('custom') || store.brought || retired.removed.length ? (dryRun ? 'would-refresh' : 'refreshed') : 'already-present';
197
+ return composeOutcome(OP, token, [...body, ...r.tail, ...store.lines, ...retired.lines], false);
183
198
  };
@@ -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 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 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);