@sabaiway/agent-workflow-kit 20.1.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 (94) hide show
  1. package/CHANGELOG.md +62 -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/gates.md +1 -1
  12. package/references/modes/recommendations.md +2 -2
  13. package/references/modes/upgrade.md +4 -4
  14. package/references/scripts/{archive-caps.mjs → archives/archive-caps.mjs} +1 -1
  15. package/references/scripts/{archive-changelog.mjs → archives/archive-changelog.mjs} +7 -9
  16. package/references/scripts/{archive-decisions.mjs → archives/archive-decisions.mjs} +13 -10
  17. package/references/scripts/{archive-issues.mjs → archives/archive-issues.mjs} +7 -8
  18. package/references/scripts/{check-docs-size.mjs → docs-size/check-docs-size.mjs} +3 -4
  19. package/references/scripts/docs-size/index.mjs +2 -0
  20. package/references/scripts/family.json +43 -0
  21. package/references/scripts/family.mjs +90 -0
  22. package/references/scripts/gates/kit-command-gates.mjs +117 -0
  23. package/references/scripts/{migrate-gates.mjs → gates/migrate-gates.mjs} +30 -13
  24. package/references/scripts/{install-git-hooks.mjs → git-hooks/install-git-hooks.mjs} +50 -38
  25. package/references/scripts/run.mjs +74 -0
  26. package/references/scripts/shared/index.mjs +3 -0
  27. package/references/scripts/shared/project-root.mjs +11 -0
  28. package/references/scripts/spec-schema/index.mjs +2 -0
  29. package/references/shared/composition-handoff.md +1 -1
  30. package/references/shared/deploy-tail.md +2 -2
  31. package/references/templates/SPEC_TEMPLATE.md +1 -1
  32. package/references/templates/adr-record.md +3 -3
  33. package/tools/apply-danger-check.mjs +9 -5
  34. package/tools/atomic-write.mjs +3 -1
  35. package/tools/checker-gates-read.mjs +4 -1
  36. package/tools/direct-run.mjs +2 -0
  37. package/tools/distribution-files/retired.mjs +99 -0
  38. package/tools/distribution-files/scripts.mjs +67 -52
  39. package/tools/ensure-configs.mjs +21 -21
  40. package/tools/ensure-ops.mjs +60 -18
  41. package/tools/ensure-specs.mjs +82 -47
  42. package/tools/ensure-vocabulary.mjs +4 -4
  43. package/tools/epic-shape-cli.mjs +1 -1
  44. package/tools/epic-shape-ledger.mjs +1 -1
  45. package/tools/epic-shape.mjs +1 -1
  46. package/tools/family-registry.mjs +3 -1
  47. package/tools/feedback-record-cli.mjs +1 -1
  48. package/tools/fold-scope.mjs +2 -2
  49. package/tools/gates-declaration.mjs +8 -4
  50. package/tools/git-hooks.mjs +90 -65
  51. package/tools/jev-connect.mjs +1 -1
  52. package/tools/jev-guide.mjs +1 -1
  53. package/tools/jev-skill.mjs +1 -1
  54. package/tools/known-footprint.mjs +7 -29
  55. package/tools/node-evidence.mjs +29 -15
  56. package/tools/now-cli.mjs +1 -1
  57. package/tools/payload-prune.mjs +53 -58
  58. package/tools/plan-shape-cli.mjs +1 -1
  59. package/tools/plan-shape.mjs +1 -1
  60. package/tools/project-rules/rules-record.mjs +1 -1
  61. package/tools/queue-audit-cli.mjs +1 -1
  62. package/tools/queue-audit.mjs +2 -2
  63. package/tools/queue-purge-archive.mjs +1 -1
  64. package/tools/queue-purge-cli.mjs +1 -1
  65. package/tools/queue-purge.mjs +1 -1
  66. package/tools/recommendations.mjs +22 -19
  67. package/tools/script-priors.mjs +31 -3
  68. package/tools/source-size/piles.mjs +1 -1
  69. package/tools/spec-adoption.mjs +1 -1
  70. package/tools/spec-check-ops.mjs +2 -2
  71. package/tools/spec-check.mjs +2 -2
  72. package/tools/spec-coverage.mjs +1 -1
  73. package/tools/tier-guide.mjs +1 -1
  74. package/tools/transition/index.mjs +1 -1
  75. package/tools/upgrade-runlist.mjs +1 -1
  76. package/tools/write-lanes.mjs +2 -2
  77. package/references/scripts/_expect-shim.mjs +0 -41
  78. package/references/scripts/archive-caps.test.mjs +0 -321
  79. package/references/scripts/archive-changelog.test.mjs +0 -560
  80. package/references/scripts/archive-conservation.test.mjs +0 -466
  81. package/references/scripts/archive-decisions.test.mjs +0 -1503
  82. package/references/scripts/archive-issues.test.mjs +0 -825
  83. package/references/scripts/archiver-structure.test.mjs +0 -84
  84. package/references/scripts/check-docs-size-cli.test.mjs +0 -325
  85. package/references/scripts/check-docs-size-ensure.test.mjs +0 -360
  86. package/references/scripts/check-docs-size.test.mjs +0 -395
  87. package/references/scripts/install-git-hooks-repo-exec.test.mjs +0 -185
  88. package/references/scripts/install-git-hooks.test.mjs +0 -241
  89. package/references/scripts/markdown-blocks.test.mjs +0 -310
  90. package/references/scripts/migrate-gates-branches.test.mjs +0 -302
  91. package/references/scripts/migrate-gates.test.mjs +0 -517
  92. package/references/scripts/spec-schema.test.mjs +0 -352
  93. /package/references/scripts/{markdown-blocks.mjs → shared/markdown-blocks.mjs} +0 -0
  94. /package/references/scripts/{spec-schema.mjs → spec-schema/spec-schema.mjs} +0 -0
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ // run.mjs — the stable kit command (spec kit-command): `node scripts/agent-workflow/run.mjs <name> [arguments...]`
3
+ // runs the named kit check with every argument unchanged. The names are frozen; the files behind them are the kit's.
4
+ // Dependency-free, Node >= 22. No side effects on import.
5
+
6
+ import { realpathSync, statSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { spawnSync } from 'node:child_process';
10
+
11
+ const __filename = fileURLToPath(import.meta.url);
12
+ const HERE = dirname(__filename);
13
+
14
+ export const KIT_COMMAND_PATH = 'scripts/agent-workflow/run.mjs';
15
+ export const KIT_COMMANDS = Object.freeze({
16
+ 'docs-size': 'docs-size/check-docs-size.mjs',
17
+ 'archive-changelog': 'archives/archive-changelog.mjs',
18
+ 'archive-issues': 'archives/archive-issues.mjs',
19
+ 'archive-decisions': 'archives/archive-decisions.mjs',
20
+ 'install-git-hooks': 'git-hooks/install-git-hooks.mjs',
21
+ });
22
+
23
+ const NAMES = Object.keys(KIT_COMMANDS);
24
+ const PREFIX = '[run]';
25
+ const USAGE = `Usage: node ${KIT_COMMAND_PATH} <name> [arguments...]
26
+ Runs the named kit check with every argument after the name, unchanged. Names: ${NAMES.join(', ')}.
27
+ `;
28
+
29
+ const isRegularFile = (path) => statSync(path, { throwIfNoEntry: false })?.isFile() === true;
30
+
31
+ export const main = (argv = process.argv.slice(2), deps = {}) => {
32
+ const { spawn = spawnSync, isFile = isRegularFile, stdout = process.stdout, stderr = process.stderr } = deps;
33
+ const [name, ...args] = argv;
34
+ if (name === undefined) {
35
+ stderr.write(USAGE);
36
+ return 2;
37
+ }
38
+ if (name === '--help' || name === '-h') {
39
+ stdout.write(USAGE);
40
+ return 0;
41
+ }
42
+ if (!Object.hasOwn(KIT_COMMANDS, name)) {
43
+ stderr.write(`${PREFIX} unknown name ${JSON.stringify(name)} — the known names are ${NAMES.join(', ')}\n`);
44
+ return 2;
45
+ }
46
+ const target = KIT_COMMANDS[name];
47
+ const file = join(HERE, ...target.split('/'));
48
+ if (!isFile(file)) {
49
+ stderr.write(`${PREFIX} ${name}: scripts/agent-workflow/${target} is not a file of this deployment\n`);
50
+ return 1;
51
+ }
52
+ const result = spawn(process.execPath, [file, ...args], { stdio: 'inherit' });
53
+ if (result.error) {
54
+ stderr.write(`${PREFIX} ${name}: cannot run the check (${result.error.message})\n`);
55
+ return 1;
56
+ }
57
+ if (result.signal) {
58
+ stderr.write(`${PREFIX} ${name}: the check was killed by ${result.signal}\n`);
59
+ return 1;
60
+ }
61
+ return result.status ?? 1;
62
+ };
63
+
64
+ // Run main() only when executed directly, never on import; compare by REAL path so a symlinked entry still runs.
65
+ const isDirectRun = (() => {
66
+ const invoked = process.argv[1];
67
+ if (!invoked) return false;
68
+ try {
69
+ return realpathSync(invoked) === realpathSync(__filename);
70
+ } catch {
71
+ return false;
72
+ }
73
+ })();
74
+ if (isDirectRun) process.exitCode = main();
@@ -0,0 +1,3 @@
1
+ // The shared module's one door (spec script-family): the block model and the project-root finder.
2
+ export { tokenizeMarkdown, findParagraphBreak, fail } from './markdown-blocks.mjs';
3
+ export { findProjectRoot } from './project-root.mjs';
@@ -0,0 +1,11 @@
1
+ // project-root.mjs — the one project-root finder of the script family (spec script-family).
2
+ //
3
+ // A module file sits in <root>/scripts/agent-workflow/<module>/ in a deployment and in
4
+ // <pkg>/references/scripts/<module>/ in the canon, so the root is the directory three levels above the
5
+ // module file's own directory in both. Dependency-free, Node >= 22. No side effects on import.
6
+
7
+ import { dirname, resolve } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+
10
+ // `moduleUrl` is a module's import.meta.url (a URL or its href).
11
+ export const findProjectRoot = (moduleUrl) => resolve(dirname(fileURLToPath(moduleUrl)), '..', '..', '..');
@@ -0,0 +1,2 @@
1
+ // The spec-schema module's one door (spec script-family): the spec reader and its frozen schema.
2
+ export { SPEC_SCHEMA, SPECS_COLLAPSE, classifyPath, readSpecDocument } from './spec-schema.mjs';
@@ -35,7 +35,7 @@ refused with their line numbers, nothing written: the upgrade STOPs.
35
35
  a GENERATED artifact the entry point declares always-loaded, and the deploy may have just
36
36
  written a `docs/ai` file — so the finalizer runs at the LAST `docs/ai` mutation of the deploy,
37
37
  before the stamp and the report. ONE command:
38
- `node ${CLAUDE_SKILL_DIR}/references/scripts/check-docs-size.mjs --ensure-index --root=<project>`.
38
+ `node ${CLAUDE_SKILL_DIR}/references/scripts/docs-size/check-docs-size.mjs --ensure-index --root=<project>`.
39
39
  Relay its one outcome line (*regenerated* / *already current*); a `write-refused` (the write) or
40
40
  `probe-failed` (the tree could not be read) line names the offending path and is a loud STOP,
41
41
  never a note. It is idempotent, so an earlier run in the
@@ -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 };
@@ -4,12 +4,14 @@
4
4
  // (part checker-gates-read). No CLI (refuseDirectRun); nothing here writes.
5
5
  import { lstatSync } from 'node:fs';
6
6
  import { dirname, join, resolve } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
7
8
  import { CHECKER_CLAIM, classifyCheckerClaim, dqUnsafePath } from './checker-claim.mjs';
8
9
  import { refuseDirectRun } from './direct-run.mjs';
9
10
  import { readRegularFileNoFollow } from './fs-read-nofollow.mjs';
10
11
  import { GATES_REL, KIT_CHECKER_CLAIMS, coverageDeclarationDefects, validateDeclaration } from './gates-declaration.mjs';
11
12
  import { escapeForLine, isLineUnsafe } from './source-size-core.mjs';
12
13
 
14
+ const KIT_TOOLS_DIR = dirname(fileURLToPath(import.meta.url));
13
15
  const DEPLOYMENT_CHAIN = ['.', 'docs', 'docs/ai'];
14
16
  const NOT_APPLICABLE_CODES = new Set(['ENOENT', 'ENOTDIR']);
15
17
  const OK = 'ok';
@@ -78,6 +80,7 @@ export const CHECKER_GATE_CANDIDATES = Object.freeze([
78
80
  'No work without a specification — every in-scope tool is governed by a contract, or named in the shrink-only debt',
79
81
  requiring(COVERAGE_SCOPE, STORE_ROOT),
80
82
  ),
83
+ candidate('project-rules', 'Project rules — each theme\'s effective file matches the record of what it was built from', requiring()),
81
84
  ]);
82
85
 
83
86
  const claimOf = (id) => KIT_CHECKER_CLAIMS.find((claim) => claim.id === id);
@@ -119,7 +122,7 @@ const claimState = ({ id, screen }, gates, root) => {
119
122
  return taken ? { state: CANDIDATE_STATES.idTaken, detail: taken.cmd } : {};
120
123
  };
121
124
 
122
- const toolPathOf = ({ basename, screen }, deps) => join(deps.kitToolsDir ?? dirname(screen.canonical), basename);
125
+ const toolPathOf = ({ path }, deps) => join(deps.kitToolsDir ?? KIT_TOOLS_DIR, path);
123
126
  const isUnrenderable = (path) => dqUnsafePath(path) || isLineUnsafe(path);
124
127
 
125
128
  const judgeCandidate = ({ id, title, probe }, rendered, gates, root, deps) => {
@@ -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
  };