@sabaiway/agent-workflow-kit 14.45.0 → 14.46.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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,42 @@ Semantically versioned ([semver](https://semver.org)), newest first. The `versio
4
4
  is the current release. `upgrade` mode reads a project's `docs/ai/.workflow-version` and applies
5
5
  every `migrations/<version>-<slug>.md` newer than it, in semver order.
6
6
 
7
+ ## 14.46.0 — every upgrade keeps all the kit's scripts in your `scripts/` current, an edit kept aside and replaced on the one yes (AD-198)
8
+
9
+ **A kit script in `scripts/` no longer stays stale or missing forever.** Before, the upgrade's `scripts` step
10
+ refreshed only the hook installer and its two suites, seeded the four ADR files once and then never touched them, and
11
+ left every other kit script outside the spec layer as it was deployed. Now the upgrade's `scripts` step judges every kit script the bundle ships (all of
12
+ `references/scripts/*.mjs` but the spec-layer files, which the `specs` step keeps), each by proof:
13
+
14
+ - **A body an earlier release shipped is refreshed** to the bundled one with no question; the current body is left.
15
+ - **An edited or an absent file waits for the upgrade's one yes.** It is named in the one replace block, each line
16
+ adding that the commit hook runs it, so it may stop the next commit; on the yes an edit is first kept aside under
17
+ `.agent-workflow/kept-aside/`, then replaced, and an absent file is placed. On a no nothing edited is replaced and
18
+ nothing absent is placed; the next upgrade asks again. An edit to the hook installer belongs in
19
+ `scripts/pre-commit.local`; any other in a script or suite of your own under its own name in `scripts/`, or in a
20
+ config the script reads.
21
+ - **Only where you took the kit's scripts.** The step works once at least one kit script stands in `scripts/`;
22
+ otherwise it places nothing and reports `not-placed`. A project with only a `package.json` no longer gets the four
23
+ ADR files seeded.
24
+ - **No file waits on another.** An edited member of the installer set no longer holds back the other two; the
25
+ installer and its two suites are still written first.
26
+ - **On an older ADR layout** `archive-decisions.mjs`, `archive-decisions.test.mjs` and `archiver-structure.test.mjs`
27
+ are held back, with the opt-in `/agent-workflow-kit migrate-adr-store` named; a layout that cannot be read keeps the
28
+ installer set current and fails the step.
29
+ - **The step's outcomes:** `refreshed`, `pending` (a file waits for the yes), `already-present`, `not-placed`,
30
+ `old-adr-layout-migration-instructed`, `skipped-no-node-evidence`, and `seeded` on the replace run;
31
+ `customized-preserved` no longer comes from this step.
32
+ - **The replace run** (`ensure-configs --reconcile --replace-custom <digest>`) keeps every edit aside, then runs the
33
+ kit scripts, then the spec layer, then the navigator when nothing failed. A step whose survey was refused takes no
34
+ part, and each step runs under the replace even when nothing was edited, so a file edited after the block printed is
35
+ reported, not replaced. An `--only scripts` or `--only specs` run also surveys the other step, without a write, so
36
+ its block names every file waiting for the yes.
37
+ - `references/modes/upgrade.md` says where a refresh or a placement may grow a recorded size and that the size check
38
+ names its own reasoned `--write-baseline`.
39
+ - Stated limit: an older body of a script the kit has no record of reads as edited, so it costs one kept-aside copy.
40
+ - Contracts: distribution-files revision 2 (parts scripts and replace-set), init-project revision 17 (git-hooks 14),
41
+ vehicle-settings revision 4, node-evidence revision 6, docs-navigator revision 3.
42
+
7
43
  ## 14.45.0 — the kit's search and plan checks no longer walk into the folder of kept-aside copies (AD-197)
8
44
 
9
45
  **A kept-aside copy no longer shows up beside the live file.** Since 14.44.0 the upgrade keeps a replaced edit at
package/SKILL.md CHANGED
@@ -3,7 +3,7 @@ name: agent-workflow-kit
3
3
  description: Deploy or upgrade a portable AI-agent memory-and-workflow system in any project. Use when the user wants to bootstrap `docs/ai/` + an entry-point `AGENTS.md` (+ `CLAUDE.md` alias) + cap/archive/index enforcement in a new or existing repo, set up the Memory Map and session protocols, install the docs-rotation pre-commit hook, or run `/agent-workflow-kit` / `/agent-workflow-kit upgrade`. Triggers on phrases like "set up the memory system", "deploy the AI workflow here", "bootstrap docs/ai", "upgrade the workflow". New to the epic, story and task tier? Run `/agent-workflow-kit tier`. A typed decision with a confidence from Jev? Run `/agent-workflow-kit jev`.
4
4
  disable-model-invocation: true
5
5
  metadata:
6
- version: '14.45.0'
6
+ version: '14.46.0'
7
7
  ---
8
8
 
9
9
  # agent-workflow-kit
package/capability.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schema": 1,
4
4
  "name": "agent-workflow-kit",
5
5
  "kind": "composition-root",
6
- "version": "14.45.0",
6
+ "version": "14.46.0",
7
7
  "provides": [],
8
8
  "roles": {},
9
9
  "detect": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sabaiway/agent-workflow-kit",
3
- "version": "14.45.0",
3
+ "version": "14.46.0",
4
4
  "description": "Portable, cross-agent memory & workflow for AI coding agents — Claude Code, Codex, Cursor, Devin Desktop. One command deploys an AGENTS.md entry point + docs/ai context with cap/archive/index enforcement into any repo.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -33,7 +33,7 @@ Requires: ${CLAUDE_SKILL_DIR}/references/shared/report-footer.md · ${CLAUDE_SKI
33
33
 
34
34
  **`footprint` — hidden-mode footprint reconcile (D9 / AD-014).** A deployment does not record whether it chose `hidden`, so first **infer visibility** — the dry-run writes **zero bytes** and reports one of — **visible** (the entry point is tracked) → nothing to do; **ambiguous** (untracked but not ignored — could be a fresh uncommitted repo, or a hide that broke) → **ASK** the user which it is, never guess; **hidden** → re-run without `--dry-run` to migrate any older **machine-global** hide to the **project-local** `.git/info/exclude` (one managed block; folds in the legacy `.claude/skills/` line), idempotently (a clean re-run is zero-diff). Handle its surfaced paths exactly as bootstrap step 9 (`${CLAUDE_SKILL_DIR}/references/modes/bootstrap.md`) (already-committed → show `git rm --cached`, ask before `--include`; generic-name present file → ask; **a leftover machine-wide ignore block is kept + reported — the advisor's `footprint-global` item removes it**). This runs on **every** hidden upgrade, like the methodology slot — no lineage-head bump, no migration file.
35
35
 
36
- **`configs` — the project-configuration ensures, ONE run.** The ONE command performs **all nine** ensures — orchestration config · gate declaration · autonomy declaration · vehicles declaration · executor check · enforcement scripts · spec layer · project rules · navigator index — in a fixed order, and prints **one outcome line per ensure**: paste those lines into the step 4 / step 8 success report. Every SEED is **create-only** (an existing file is preserved byte-for-byte); a refresh-class op rewrites only what it owns — the outcome tokens by ensure, below, name each arm. One ensure failing **never** skips the others: each reports its own outcome and the run exits non-zero when any of them `failed`. The outcome tokens, by ensure: orchestration → `seeded` / `note-refreshed` / `already-current` / `customized-preserved` / `malformed-preserved`; gates, autonomy and vehicles → `seeded` / `already-present`; executor → `not-placed` / `already-current` / `pending`; scripts → `seeded` / `refreshed` / `already-present` / `customized-preserved` / `old-adr-layout-migration-instructed` / `skipped-no-node-evidence`; specs → `seeded` / `refreshed` / `already-present` / `customized-preserved` / `skipped-no-node-evidence`; rules → `seeded` / `refreshed` / `regenerated` / `pending` / `customized-preserved` / `already-current`; index → `regenerated` / `already-current` / `customized-preserved`; and any ensure may report `failed`, whose line OPENS with the cause (relay it with that cause — never soften it into a skip; an op that copies file by file also states when it stopped partway). The cause vocabulary is CLOSED — one of `race-unresolved`, `template-unreadable`, `bundle-unreadable`, `adr-layout-unverifiable`, `node-evidence-unverifiable`, `wrong-node-kind`, `vehicle-settings-unreadable`, `write-refused`, `unexpected-error`, `generator-unlaunchable`, `generator-failed`, `index-probe-failed`, `index-stale-after-write` — and every cause that can only arise AFTER the generator ran (`generator-failed`, and `index-probe-failed` / `index-stale-after-write` when they follow a reported regeneration) DISCLOSES in its own line that a write may already have landed. **A non-zero exit STOPs this upgrade — once row 3's replace ask is answered when a replace line printed, then as that ask says** — before the equal-head exit, the migrations and the re-stamp. Add `--dry-run` to preview without writing a byte. Like the pointer slots + the footprint reconcile, all nine reach an equal-head deployment **without a lineage-head bump or a migration file**.
36
+ **`configs` — the project-configuration ensures, ONE run.** The ONE command performs **all nine** ensures — orchestration config · gate declaration · autonomy declaration · vehicles declaration · executor check · enforcement scripts · spec layer · project rules · navigator index — in a fixed order, and prints **one outcome line per ensure**: paste those lines into the step 4 / step 8 success report. Every SEED is **create-only** (an existing file is preserved byte-for-byte); a refresh-class op rewrites only what it owns — the outcome tokens by ensure, below, name each arm. One ensure failing **never** skips the others: each reports its own outcome and the run exits non-zero when any of them `failed`. The outcome tokens, by ensure: orchestration → `seeded` / `note-refreshed` / `already-current` / `customized-preserved` / `malformed-preserved`; gates, autonomy and vehicles → `seeded` / `already-present`; executor → `not-placed` / `already-current` / `pending`; scripts → `refreshed` / `pending` / `already-present` / `not-placed` / `old-adr-layout-migration-instructed` / `skipped-no-node-evidence`, with `seeded` on the replace run; specs → `seeded` / `refreshed` / `already-present` / `customized-preserved` / `skipped-no-node-evidence`; rules → `seeded` / `refreshed` / `regenerated` / `pending` / `customized-preserved` / `already-current`; index → `regenerated` / `already-current` / `customized-preserved`; and any ensure may report `failed`, whose line OPENS with the cause (relay it with that cause — never soften it into a skip; an op that copies file by file also states when it stopped partway). The cause vocabulary is CLOSED — one of `race-unresolved`, `template-unreadable`, `bundle-unreadable`, `adr-layout-unverifiable`, `node-evidence-unverifiable`, `wrong-node-kind`, `vehicle-settings-unreadable`, `write-refused`, `unexpected-error`, `generator-unlaunchable`, `generator-failed`, `index-probe-failed`, `index-stale-after-write` — and every cause that can only arise AFTER the generator ran (`generator-failed`, and `index-probe-failed` / `index-stale-after-write` when they follow a reported regeneration) DISCLOSES in its own line that a write may already have landed. **A non-zero exit STOPs this upgrade — once row 3's replace ask is answered when a replace line printed, then as that ask says** — before the equal-head exit, the migrations and the re-stamp. Add `--dry-run` to preview without writing a byte. Like the pointer slots + the footprint reconcile, all nine reach an equal-head deployment **without a lineage-head bump or a migration file**.
37
37
 
38
38
  **What the orchestration-config ensure does.** `docs/ai/orchestration.json` must exist **and its onboarding note must be current**: created from the canonical seed if missing; if it already exists, **every activity/slot the user set is preserved** and ONLY the `_README` note is refreshed, and only when the existing one still matches a known prior canonical — `refreshIfCanonical` / `refreshReadme` in `tools/orchestration-config.mjs` decide it (CRLF/whitespace normalized first; a *customized* `_README` is preserved verbatim → `customized-preserved`; a *malformed* existing config is **preserved untouched + LOUD** → `malformed-preserved`, never clobbered and never silently skipped). The current note points at `/agent-workflow-kit set-recipe`. **Kit-owned:** in the **delegated** path memory only seeds/preserves the file (memory upgrade step 2) and this ensure applies the `_README` refresh; in the **fallback** path it does both. (Memory stays standalone.)
39
39
 
@@ -43,7 +43,7 @@ Requires: ${CLAUDE_SKILL_DIR}/references/shared/report-footer.md · ${CLAUDE_SKI
43
43
 
44
44
  **What the executor ensure does.** It never writes: a placed `.claude/agents/executor.md` whose bytes differ from the body derived from `docs/ai/vehicles.json` is `pending` — the advisor's `executor-vehicle.differing` item re-derives it on the user's yes — and an absent one is `not-placed` (the agents mode places it on consent).
45
45
 
46
- **What the enforcement-script ensure does.** First, on every Node deployment whatever its ADR layout, the hook installer and its two suites are refreshed together: a member on a body a release shipped becomes the bundled one, an edited member keeps all three as they stand, an absent one is never seeded. The pairs must exist in the project's `scripts/`: `archive-decisions.mjs` + `archive-decisions.test.mjs` and `markdown-blocks.mjs` + `markdown-blocks.test.mjs`, copied from `${CLAUDE_SKILL_DIR}/references/scripts/` if missing; **an existing file is preserved, never overwritten**. Nothing else is seeded — the other tokenizer-era tests red beside OLD archivers. **OLD ADR-store layout — DETECTED before the seed, never auto-migrated (AD-051, Decision 13):** on a `docs/ai/history/decisions-archive*.md` monolith (`old`), or no monolith but a deployed rotator predating the store (`old-unrotated`), the project is on the RETIRED 3-tier cascade, so no ADR file is seeded and the ensure reports `old-adr-layout-migration-instructed` (the new `archive-decisions.mjs` beside un-migrated monoliths would red their ADR gate). Relay it as the LOUD instruct it is: the fix is the opt-in **`/agent-workflow-kit migrate-adr-store`** (consent-gated; previews first, never commits), and the seed lands on the next upgrade. A layout the ensure cannot READ is `failed`, no ADR file seeded; under either, the set's refresh lines stand. The seed applies ONLY to a clean layout (neither signal). **Whether Node runs here is PROVEN, never proxied:** the ensure seeds on a regular `package.json` at the root OR on any kit-seeded `scripts/*.mjs` already deployed; only when every probe answers absent does it report `skipped-no-node-evidence`, a line naming every probe it checked, while the config ensures still run; a probe that cannot be read is `failed` with the cause `node-evidence-unverifiable`, nothing written. **A `skipped-*` outcome whose stated reason this tool could itself disprove may not exist**. The deployed pre-commit hook gains the `archive-decisions.mjs --check` line only when the hook is next refreshed (the `enforcement` check line and apply, by the consent route, copy nothing and re-run the installer, which refuses a non-marker hook as always); an OLD hook without the line is safe — the decisions gate is simply not enforced yet.
46
+ **What the enforcement-script ensure does.** It judges every kit script — each `*.mjs` of `${CLAUDE_SKILL_DIR}/references/scripts/` but the spec-layer pairs — once the component is accepted: one of them stands in `scripts/` as a regular file (else `not-placed`, nothing written). Each file by proof: a body a release shipped is refreshed to the bundled one with no yes; the current body is left; an edited body and an absent file are named in the replace block, kept aside and replaced or placed only on row 3's one yes, each line adding that the commit hook runs it, so it may stop the next commit. The hook installer and its two suites are written first. **OLD ADR-store layout — DETECTED, never auto-migrated (AD-051, Decision 13):** on a `docs/ai/history/decisions-archive*.md` monolith (`old`), or no monolith but a deployed rotator predating the store (`old-unrotated`), the decisions group (`archive-decisions.mjs`, `archive-decisions.test.mjs`, `archiver-structure.test.mjs`) is held back and the ensure reports `old-adr-layout-migration-instructed`. Relay it as the LOUD instruct it is: the fix is the opt-in **`/agent-workflow-kit migrate-adr-store`** (consent-gated; previews first, never commits); the next upgrade judges the group. A layout the ensure cannot READ is `failed`: the installer set alone is kept current, every other kit script waits. Where the size practice measures `scripts/`, a refresh or a placement may grow a root past its record: the size check names its own reasoned `--write-baseline`. **Whether Node runs here is PROVEN, never proxied:** the ensure runs on a regular `package.json` at the root OR on any kit-seeded `scripts/*.mjs` already deployed; only when every probe answers absent does it report `skipped-no-node-evidence`, a line naming every probe it checked, while the config ensures still run; a probe that cannot be read is `failed` with the cause `node-evidence-unverifiable`, nothing written. **A `skipped-*` outcome whose stated reason this tool could itself disprove may not exist**. A deployed pre-commit hook takes a new installer body only when the installer next runs: the `enforcement` check line and apply, by the consent route, re-run it (it refuses a non-marker hook as always); until then `scripts/pre-commit.local` does not run.
47
47
 
48
48
  **What the navigator ensure does.** `docs/ai/index.md` is the always-loaded navigator the entry point declares, and it is GENERATED — no template ships it, so a deployment that never ran the generator boots from a broken entry point (and a Node project's hook fails its index check). The ensure runs the bundled generator's finalizer and reports `regenerated` (it was missing or stale — it was written) or `already-current` (nothing written); under a hook module that is not the bundled one, a write the project's own checker rejects is put back → `customized-preserved`. It never skips a No-Node project: the generator runs from `${CLAUDE_SKILL_DIR}/references/scripts/` on the agent host, not from the project's `scripts/`. **Its position in the run-list is EARLY and therefore NOT authoritative** — `lens` (and, on the migrated path, steps 6–7) still change `docs/ai` afterwards — so the authoritative run is the LATE `--only index` rung documented at both exits; the early one is idempotent: an untouched tree changes nothing.
49
49
 
@@ -3,3 +3,4 @@
3
3
  // imports a leaf directly.
4
4
 
5
5
  export { keptAsidePath, replaceBlock, runReplace } from './replace-set.mjs';
6
+ export { SCRIPT_CHANNEL, ensureScripts } from './scripts.mjs';
@@ -1,9 +1,9 @@
1
1
  // replace-set.mjs — the ONE replace block an upgrade prints over every file whose write waits for the
2
- // user's yes, and the replace run that yes starts. An op that owns such writes reports entries on its
3
- // outcome: { rel, sha256, bytes, channel } for an edited file, { rel, absent: true, channel } for an
4
- // absent one. This module binds their union into one digest, prints one block over it, and on the yes
5
- // keeps every edit aside (kept-aside.mjs) before any owning op replaces a byte. It never imports
6
- // ensure-configs.mjs: the CLI hands it the ops it runs.
2
+ // user's yes, and the replace run that yes starts. An owning op reports entries on its outcome: { rel,
3
+ // sha256, bytes, channel } for an edited file, { rel, absent: true, channel } for an absent one, either
4
+ // marked `hookRun: true` when the commit hook runs it. One digest binds their union, one block prints
5
+ // over it, and the yes keeps every edit aside (kept-aside.mjs) before any op replaces a byte. It never
6
+ // imports ensure-configs.mjs: the CLI hands it the ops it runs.
7
7
  //
8
8
  // Dependency-free, Node >= 22. No side effects on import.
9
9
 
@@ -15,8 +15,9 @@ import { keepAside, keptAsidePath } from './kept-aside.mjs';
15
15
 
16
16
  export { keptAsidePath };
17
17
 
18
- const INDEX_NOT_RUN = 'the navigator step did not run: a replace run runs it only after the spec layer succeeds';
18
+ const INDEX_NOT_RUN = 'the navigator step did not run: a replace run runs it only after every step it re-runs succeeds';
19
19
  const RACE_LINE = 'the files to replace changed since the replace line was printed (another set or other bytes), so nothing was written — ask the user again over the fresh block below';
20
+ const HOOK_RUN = '; the commit hook runs it, so it may stop the next commit';
20
21
 
21
22
  // The digest binds the set AND the bytes: `<rel> <sha256>` or `<rel> absent`, sorted by rel in
22
23
  // code-unit order, LF-joined. Over an all-edited set it is the digest the specs op printed before.
@@ -24,9 +25,9 @@ const byRel = (a, b) => (a.rel < b.rel ? -1 : 1);
24
25
  const digestLine = (entry) => `${entry.rel} ${entry.absent ? 'absent' : entry.sha256}`;
25
26
  export const replaceSetDigest = (entries) => createHash('sha256').update([...entries].sort(byRel).map(digestLine).join('\n')).digest('hex');
26
27
 
27
- const entryLine = (entry, digest) => (entry.absent
28
+ const entryLine = (entry, digest) => `${entry.absent
28
29
  ? `${entry.rel}: absent — the user's yes places the bundled body`
29
- : `${entry.rel}: carries an edit — on the user's yes it is kept aside at ${keptAsidePath(digest, entry.rel)}, then the bundled body replaces it; an edit meant to last goes in ${entry.channel}`);
30
+ : `${entry.rel}: carries an edit — on the user's yes it is kept aside at ${keptAsidePath(digest, entry.rel)}, then the bundled body replaces it; an edit meant to last goes in ${entry.channel}`}${entry.hookRun ? HOOK_RUN : ''}`;
30
31
 
31
32
  // One line per entry in rel order, then the ONE command line, its condition first and both paths
32
33
  // shell-quoted; no line at all for an empty set.
@@ -39,31 +40,36 @@ export const replaceBlock = (entries, { kitRoot, cwd }) => {
39
40
  ];
40
41
  };
41
42
 
43
+ // A refused survey is a failed outcome that carries no entries field: that op takes no part.
44
+ const refused = (outcome) => outcome.failed && outcome.entries === undefined;
45
+
42
46
  // runReplace({ cwd, kitRoot, digest, owning, index, deps }) → { outcomes, block }. `owning` is
43
47
  // [{ op, run }] in ENSURE_OPS order and `index` the navigator's run; each run(args) returns an
44
48
  // outcome and never throws (the CLI wraps it). `block` carries the recomputed union only when the
45
49
  // digest differs — every other outcome of a replace run prints no block.
46
50
  export const runReplace = ({ cwd, kitRoot, digest, owning, index, deps = {} }) => {
47
- const notRun = (outcome) => ({ ...outcome, lines: [...outcome.lines, INDEX_NOT_RUN] });
48
- const surveys = [];
49
- for (const { op, run } of owning) {
50
- const survey = run({ cwd, kitRoot, dryRun: true, deps });
51
- if (survey.failed) return { outcomes: [notRun(survey)], block: [] };
52
- surveys.push({ run, entries: survey.entries ?? [] });
53
- }
54
- const union = surveys.flatMap((survey) => survey.entries);
55
- const first = owning[0].op;
56
- if (union.length > 0 && replaceSetDigest(union) !== digest) {
57
- return { outcomes: [notRun(composeFailure(first, 'race-unresolved', RACE_LINE))], block: union };
58
- }
51
+ const surveys = owning.map(({ op, run }) => ({ op, run, survey: run({ cwd, kitRoot, dryRun: true, deps }) })).map((s) => ({ ...s, entries: s.survey.entries ?? [] }));
52
+ // Outcomes in owning order; index only when none failed, else the last failed one ends with the navigator line.
53
+ const finish = (results, block = []) => {
54
+ const outcomes = results.filter(Boolean);
55
+ const last = outcomes.findLastIndex((o) => o.failed);
56
+ if (last === -1) return { outcomes: [...outcomes, index({ cwd, kitRoot, dryRun: false, deps })], block };
57
+ return { outcomes: outcomes.map((o, i) => (i === last ? { ...o, lines: [...o.lines, INDEX_NOT_RUN] } : o)), block };
58
+ };
59
+ const results = surveys.map((s) => (refused(s.survey) ? s.survey : null));
60
+ const stopped = surveys.findIndex((s) => s.survey.failed && !refused(s.survey));
61
+ if (stopped !== -1) return finish(results.map((o, i) => (i === stopped ? surveys[i].survey : o)));
62
+ const taking = surveys.filter((s) => !refused(s.survey));
63
+ if (taking.length === 0) return finish(results);
64
+ const union = taking.flatMap((s) => s.entries);
65
+ const atFirst = (outcome) => results.map((o, i) => (surveys[i] === taking[0] ? outcome : o));
66
+ if (union.length > 0 && replaceSetDigest(union) !== digest) return finish(atFirst(composeFailure(taking[0].op, 'race-unresolved', RACE_LINE)), union);
59
67
  const kept = keepAside({ cwd, digest, entries: union, deps });
60
- if (kept.failed) return { outcomes: [notRun(composeFailure(first, kept.cause, ...kept.lines))], block: [] };
61
- const outcomes = [];
62
- for (const survey of surveys) {
63
- const replace = union.length > 0 ? { digest, entries: survey.entries } : undefined;
64
- const outcome = survey.run({ cwd, kitRoot, dryRun: false, deps, replace });
65
- if (outcome.failed) return { outcomes: [...outcomes, notRun(outcome)], block: [] };
66
- outcomes.push(outcome);
68
+ if (kept.failed) return finish(atFirst(composeFailure(taking[0].op, kept.cause, ...kept.lines)));
69
+ for (const [i, s] of surveys.entries()) {
70
+ if (refused(s.survey)) continue;
71
+ results[i] = s.run({ cwd, kitRoot, dryRun: false, deps, replace: { digest, entries: s.entries } });
72
+ if (results[i].failed) break;
67
73
  }
68
- return { outcomes: [...outcomes, index({ cwd, kitRoot, dryRun: false, deps })], block: [] };
74
+ return finish(results);
69
75
  };
@@ -0,0 +1,185 @@
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. A prior is refreshed
4
+ // with no yes and a current one left; an absent or an edited one is a replace entry the one block names
5
+ // (replace-set.mjs), placed, or kept aside and replaced, only under the replace the user's yes starts.
6
+ // The installer set is written first; on an older ADR layout the decisions group is held back, the
7
+ // migration named. It never imports ensure-specs.mjs or ensure-configs.mjs: the CLI composes this op
8
+ // from the module's index, and ensure-specs.mjs takes its channel from there.
9
+ //
10
+ // Dependency-free, Node >= 22. Every fs primitive is injectable (deps.*). No side effects on import.
11
+
12
+ import { lstatSync, readFileSync } from 'node:fs';
13
+ import { join } from 'node:path';
14
+ import { lstatNoFollow, writeContainedFileAtomic, writeProjectFileCreateOnly } from '../atomic-write.mjs';
15
+ import { composeFailure, composeOutcome, nodeEvidenceRefusal, probeSeedTarget, tmpNote } from '../ensure-ops.mjs';
16
+ import { surveyAdrLayoutStrict } from '../family-registry.mjs';
17
+ import { BUNDLED_SCRIPT_NAMES } from '../node-evidence.mjs';
18
+ import { CHECKER_PAIR, INSTALLER_SET, READER_PAIR, SCRIPT_PRIORS, classifyDeployedScript, digestOf } from '../script-priors.mjs';
19
+ import { keptAsidePath } from './kept-aside.mjs';
20
+
21
+ const OP = 'scripts';
22
+ const SCRIPTS_DIR = 'scripts';
23
+ const BUNDLED = ['references', 'scripts'];
24
+ // Where an edit meant to last goes: the installer's in the local hook file, every other file's beside it.
25
+ export const SCRIPT_CHANNEL = 'a script or suite of your own under its own name in scripts/, or a config the script reads';
26
+ export const LOCAL_HOOK_CHANNEL = 'the local hook file scripts/pre-commit.local, which the commit hook runs first';
27
+ // The family files whose bytes import or read archive-decisions.mjs, plus that file (the suite derives it).
28
+ export const DECISIONS_GROUP = Object.freeze(['archive-decisions.mjs', 'archive-decisions.test.mjs', 'archiver-structure.test.mjs']);
29
+ const OLD_ADR_LAYOUTS = new Set(['old', 'old-unrotated']);
30
+ const PAIRS = new Set([...READER_PAIR, ...CHECKER_PAIR]);
31
+ // The family in write order: the installer set, then every other bundled name in code-unit order.
32
+ const FAMILY = Object.freeze([...INSTALLER_SET, ...BUNDLED_SCRIPT_NAMES.filter((name) => !PAIRS.has(name) && !INSTALLER_SET.includes(name)).sort()]);
33
+
34
+ const causeOf = (err) => String((err && err.message) || err);
35
+ const relOf = (name) => `${SCRIPTS_DIR}/${name}`;
36
+ const kindOfDir = (st) => (st.isSymbolicLink() ? 'a symlink' : st.isFile() ? 'a regular file' : 'not a directory');
37
+ 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`);
38
+
39
+ // ── the survey: the component first, then every family file by proof, nothing written ────────────
40
+
41
+ // → { refusal } | { notPlaced } | { files, layout, layoutError }. A family path of another node kind is
42
+ // judged before the component, so a linked family file never reads as not-placed.
43
+ const survey = ({ cwd, kitRoot, deps, read, lstat }) => {
44
+ const dir = lstatNoFollow(join(cwd, SCRIPTS_DIR), lstat);
45
+ if (dir === null) return { notPlaced: true };
46
+ if (!dir.isDirectory() || dir.isSymbolicLink()) return { refusal: wrongKind(`${SCRIPTS_DIR}/`, kindOfDir(dir)) };
47
+ const probes = FAMILY.map((name) => ({ name, rel: relOf(name), probe: probeSeedTarget(join(cwd, SCRIPTS_DIR, name), lstat) }));
48
+ const wrong = probes.find((f) => f.probe.wrongKind);
49
+ if (wrong) return { refusal: wrongKind(wrong.rel, wrong.probe.wrongKind) };
50
+ if (!probes.some((f) => f.probe.present)) return { notPlaced: true };
51
+ const files = [];
52
+ for (const { name, rel, probe } of probes) {
53
+ let bundle;
54
+ try {
55
+ bundle = read(join(kitRoot, ...BUNDLED, name));
56
+ } catch (err) {
57
+ return { refusal: composeFailure(OP, 'bundle-unreadable', `${rel}: the bundled script could not be read, so nothing was written — reinstall the kit. ${causeOf(err)}`) };
58
+ }
59
+ const bytes = probe.present ? read(join(cwd, rel)) : undefined;
60
+ files.push({ name, rel, bundle, bytes, state: probe.present ? classifyDeployedScript(bytes, name, bundle, deps.priors ?? SCRIPT_PRIORS) : 'absent' });
61
+ }
62
+ try {
63
+ return { files, layout: surveyAdrLayoutStrict(cwd, deps) };
64
+ } catch (err) {
65
+ return { files, layoutError: causeOf(err) };
66
+ }
67
+ };
68
+
69
+ const entryOf = (f) => ({
70
+ rel: f.rel,
71
+ ...(f.state === 'absent' ? { absent: true } : { sha256: digestOf(f.bytes), bytes: f.bytes }),
72
+ channel: f.name === INSTALLER_SET[0] ? LOCAL_HOOK_CHANNEL : SCRIPT_CHANNEL,
73
+ hookRun: true,
74
+ });
75
+
76
+ // ── the lines (composed from what HAPPENED: each file's state and the fate of its write) ─────────
77
+
78
+ // A fate is `written`, `stood` (a bound absent file that appeared with the bundled body), `refused`
79
+ // (its write failed), or none: the run stopped before it, or, dry, would write it.
80
+ const PRIOR_FATES = { written: 'refreshed to the bundled one', refused: 'not refreshed; its write was refused (above)' };
81
+ const EDITED = "differs from every body this kit knows it shipped — left as it stands until the user's yes keeps it aside and replaces it (the block below)";
82
+ const ABSENT = "absent — the user's yes places the bundled body (the block below)";
83
+ const WAITS = "left as it stands; the user's yes is asked once the ADR-store layout reads";
84
+ const fileLine = (f, fate, { dryRun, keptOf }) => {
85
+ if (f.state === 'prior') return `${f.rel}: matches a body an earlier release shipped — ${PRIOR_FATES[fate] ?? (dryRun ? 'would be refreshed to the bundled one' : 'not refreshed; the run stopped before it')}`;
86
+ if (!keptOf) return `${f.rel}: ${f.state === 'absent' ? ABSENT : EDITED}`;
87
+ if (f.state === 'absent') return `${f.rel}: ${{ written: "placed from the bundled scripts on the user's yes", stood: 'appeared while this run was placing it — the bundled body stands, nothing written' }[fate] ?? 'absent — not placed'}`;
88
+ const kept = keptOf(f.rel);
89
+ return `${f.rel}: ${fate === 'written' ? `carried an edit — kept aside at ${kept}, then replaced by the bundled body on the user's yes` : `carries an edit — not replaced${kept ? `; its copy kept aside at ${kept} stays` : ''}`}`;
90
+ };
91
+ const heldLine = (layout) => `${SCRIPTS_DIR}/: ${DECISIONS_GROUP.slice(0, -1).join(', ')} and ${DECISIONS_GROUP.at(-1)} are held back while this project is on the older ADR layout (${layout}) — run the opt-in /agent-workflow-kit migrate-adr-store (it previews, and never commits); the next upgrade judges them`;
92
+ const partialNote = (count) => (count > 0 ? [`the writes stopped PARTWAY — the ${count} file(s) named above were already written and are NOT rolled back`] : []);
93
+
94
+ // ── the writes ────────────────────────────────────────────────────────────────────────────────────
95
+
96
+ // One write per file in write order: a prior refreshed, a bound edit rewritten after its bytes are
97
+ // re-proven, a bound absent file written create-only. → { fates, notes, failure? }
98
+ const writeAll = ({ cwd, files, deps, read, bound }) => {
99
+ const fates = new Map();
100
+ const notes = [];
101
+ for (const f of files) {
102
+ if (f.state === 'custom' && digestOf(read(join(cwd, f.rel))) !== bound.get(f.rel)) {
103
+ return { fates, notes, failure: ['race-unresolved', `${f.rel}: changed after this run read it — left as it stands and nothing further written`] };
104
+ }
105
+ let result;
106
+ try {
107
+ result = f.state === 'absent'
108
+ ? writeProjectFileCreateOnly(cwd, f.rel, f.bundle, deps, { noun: 'a kit script' })
109
+ : writeContainedFileAtomic(cwd, join(cwd, f.rel), f.bundle, deps, { label: f.rel });
110
+ } catch (err) {
111
+ fates.set(f.rel, 'refused');
112
+ return { fates, notes, failure: ['write-refused', `${f.rel}: ${causeOf(err)}`] };
113
+ }
114
+ notes.push(...tmpNote(f.rel, result.tmpLeftBehind));
115
+ if (f.state === 'absent' && !result.created) {
116
+ if (classifyDeployedScript(read(join(cwd, f.rel)), f.name, f.bundle) !== 'current') {
117
+ 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`] };
118
+ }
119
+ fates.set(f.rel, 'stood');
120
+ } else fates.set(f.rel, 'written');
121
+ }
122
+ return { fates, notes };
123
+ };
124
+
125
+ // Under the replace the op's own survey must yield exactly the entries the yes bound.
126
+ const sameEntries = (own, bound) =>
127
+ own.length === bound.length && own.every((e) => bound.some((b) => b.rel === e.rel && Boolean(b.absent) === Boolean(e.absent) && (e.absent || b.sha256 === e.sha256)));
128
+
129
+ // ── the unreadable layout: the installer set alone kept current, the op failed with no entry ─────
130
+
131
+ const layoutRefusal = ({ cwd, files, layoutError, dryRun, deps, read }) => {
132
+ const set = files.filter((f) => INSTALLER_SET.includes(f.name) && f.state !== 'current');
133
+ const priors = set.filter((f) => f.state === 'prior');
134
+ const { fates, notes, failure } = dryRun ? { fates: new Map(), notes: [] } : writeAll({ cwd, files: priors, deps, read });
135
+ const lines = set.map((f) => (f.state === 'prior' ? fileLine(f, fates.get(f.rel), { dryRun }) : `${f.rel}: ${WAITS}`));
136
+ const written = [...fates.values()].filter((fate) => fate === 'written').length;
137
+ if (failure) return composeFailure(OP, failure[0], failure[1], ...lines, ...notes, ...partialNote(written));
138
+ return composeFailure(OP, 'adr-layout-unverifiable', `${SCRIPTS_DIR}/: the ADR-store layout could not be read (${layoutError}), so the other kit scripts wait for the layout`, ...lines, ...notes);
139
+ };
140
+
141
+ // ── the op ────────────────────────────────────────────────────────────────────────────────────────
142
+
143
+ export const ensureScripts = ({ cwd, kitRoot, dryRun = false, deps = {}, replace }) => {
144
+ const lstat = deps.lstat ?? lstatSync;
145
+ const read = deps.readFile ?? readFileSync;
146
+ const refusal = nodeEvidenceRefusal(OP, cwd, lstat);
147
+ if (refusal) return refusal;
148
+ const found = survey({ cwd, kitRoot, deps, read, lstat });
149
+ if (found.refusal) return found.refusal;
150
+ if (found.notPlaced) return composeOutcome(OP, 'not-placed', [`${SCRIPTS_DIR}/: no kit script stands in it, so none is placed`], false);
151
+ if (found.layoutError !== undefined) return layoutRefusal({ cwd, ...found, dryRun, deps, read });
152
+
153
+ // The survey completed: its entries ride every outcome from here on, a failed one included.
154
+ const held = OLD_ADR_LAYOUTS.has(found.layout);
155
+ const live = found.files.filter((f) => !(held && DECISIONS_GROUP.includes(f.name)));
156
+ const entries = live.filter((f) => f.state === 'absent' || f.state === 'custom').map(entryOf);
157
+ const bound = replace ? new Map(replace.entries.map((e) => [e.rel, e.sha256])) : null;
158
+ const keptOf = bound && ((rel) => (bound.get(rel) ? keptAsidePath(replace.digest, rel) : ''));
159
+ const linesOf = (fates) => [
160
+ ...live.filter((f) => f.state !== 'current').map((f) => fileLine(f, fates.get(f.rel), { dryRun, keptOf })),
161
+ ...(live.some((f) => f.state === 'current') ? [`${SCRIPTS_DIR}/: ${live.filter((f) => f.state === 'current').length} other kit scripts are already the bundled body — nothing written`] : []),
162
+ ...(held ? [heldLine(found.layout)] : []),
163
+ ];
164
+ const ok = (token, lines) => ({ ...composeOutcome(OP, token, lines, false), entries });
165
+ const loud = (cause, ...lines) => ({ ...composeFailure(OP, cause, ...lines), entries });
166
+ if (bound && !sameEntries(entries, replace.entries)) {
167
+ return loud('race-unresolved', 'the kit scripts to place or replace are not the set the yes was given for (another set or other bytes), so nothing was written', ...linesOf(new Map()));
168
+ }
169
+ const due = live.filter((f) => f.state === 'prior' || (bound && (f.state === 'custom' || f.state === 'absent')));
170
+ const tokenOf = (fates) => {
171
+ const landed = (state) => due.some((f) => f.state === state && fates.get(f.rel) === 'written');
172
+ if (held) return 'old-adr-layout-migration-instructed';
173
+ if (!bound && entries.length > 0) return 'pending';
174
+ if (landed('absent')) return 'seeded';
175
+ if (dryRun ? due.length > 0 : landed('prior') || landed('custom')) return dryRun ? 'would-refresh' : 'refreshed';
176
+ return 'already-present';
177
+ };
178
+ if (dryRun) return ok(tokenOf(new Map()), linesOf(new Map()));
179
+ const { fates, notes, failure } = writeAll({ cwd, files: due, deps, read, bound });
180
+ if (failure) {
181
+ const written = [...fates.values()].filter((fate) => fate === 'written').length;
182
+ return loud(failure[0], failure[1], ...linesOf(fates), ...notes, ...partialNote(written));
183
+ }
184
+ return ok(tokenOf(fates), [...linesOf(fates), ...notes]);
185
+ };
@@ -6,8 +6,8 @@
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/<ADR enforcement> the hook installer and its two suites refreshed as one set on a shipped
10
- // + the installer set prior body (an edited member keeps all three); ADR seeds seed-if-missing, layout detect first
9
+ // scripts scripts/<every kit script> one rule per file once a kit script stands there: a shipped prior refreshed,
10
+ // + the installer set an absent or edited one placed or replaced on the user's yes; installer set first
11
11
  // specs scripts/<spec layer> reader + checker pairs seeded when absent, refreshed only on
12
12
  // + docs/ai/specs/index.md a shipped prior body, an edited one replaced only on the
13
13
  // user's yes; store root seeded behind a current checker
@@ -28,9 +28,10 @@
28
28
  // • The ops run in a FIXED order and one op's failure NEVER skips the rest: every op reports its own
29
29
  // token, and the exit is non-zero when any of them failed. The one exception is the replace run
30
30
  // (--replace-custom <digest>), which distribution-files/ runs: each edit kept aside, then the
31
- // owning ops (specs), then index only when none failed.
32
- // • ONE replace block, after every op's lines and before the failure footer, over the entries of
33
- // every op that ran: the files whose write waits for the user's yes, and the one command for it.
31
+ // owning ops (scripts, then specs), then index only when none failed.
32
+ // • ONE replace block, after every op's lines and before the failure footer, over the union the
33
+ // replace run recomputes: the files whose write waits for the user's yes, and the one command for
34
+ // it. An --only run of an owning op surveys the other owning op without a write for it.
34
35
  // • The deployment gate runs ONCE, before any op: an absent/symlinked docs/ai stops the whole run
35
36
  // with the gate's own message rather than one copy of it per op.
36
37
  //
@@ -48,15 +49,15 @@ import { ensureExecutor } from './ensure-executor.mjs';
48
49
  import { ENSURE_OPS, OWN_IMPLEMENTATIONS, failedOutcome } from './ensure-ops.mjs';
49
50
  import { ensureSpecs } from './ensure-specs.mjs';
50
51
  import { ensureRules } from './project-rules/index.mjs';
51
- import { replaceBlock, runReplace } from './distribution-files/index.mjs';
52
+ import { ensureScripts, replaceBlock, runReplace } from './distribution-files/index.mjs';
52
53
 
53
54
  const KIT_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
54
55
 
55
56
  // The op table this CLI walks — name → implementation, in ENSURE_OPS order. Composed HERE (the one
56
- // consumer) because the executor, spec-layer and rules ensures import ensure-ops.mjs for their outcome door and probes.
57
- export const ENSURE_IMPLEMENTATIONS = Object.freeze({ ...OWN_IMPLEMENTATIONS, executor: ensureExecutor, specs: ensureSpecs, rules: ensureRules });
57
+ // consumer) because the executor, scripts, spec-layer and rules ensures import ensure-ops.mjs for their outcome door and probes.
58
+ export const ENSURE_IMPLEMENTATIONS = Object.freeze({ ...OWN_IMPLEMENTATIONS, executor: ensureExecutor, scripts: ensureScripts, specs: ensureSpecs, rules: ensureRules });
58
59
  // The ops whose writes wait for the user's yes and so own the replace run, in ENSURE_OPS order.
59
- const OWNING_OPS = ['specs'];
60
+ const OWNING_OPS = ['scripts', 'specs'];
60
61
 
61
62
  const EXIT_OK = 0;
62
63
  const EXIT_FAILED = 1;
@@ -70,7 +71,7 @@ const REPEATED_ONLY = '--only was passed more than once — this selector names
70
71
  const unknownOp = (value) => `--only ${value}: no such operation (${ENSURE_OPS.join(' | ')}) — nothing was run`;
71
72
  const EMPTY_REPLACE = '--replace-custom needs the digest its replace line printed — an empty value names no file to replace';
72
73
  const REPEATED_REPLACE = '--replace-custom was passed more than once — a replace run carries exactly ONE digest';
73
- const REPLACE_WITH_ONLY = '--replace-custom runs the spec layer and then the navigator, so it cannot be combined with --only — nothing was run';
74
+ const REPLACE_WITH_ONLY = '--replace-custom runs the kit scripts, then the spec layer, then the navigator, so it cannot be combined with --only — nothing was run';
74
75
  const REPLACE_WITH_DRY_RUN = "--replace-custom writes on the user's yes, so it cannot be combined with --dry-run — nothing was run";
75
76
 
76
77
  const HELP = `ensure-configs — the nine stamp-independent upgrade ensures, as ONE command.
@@ -81,11 +82,13 @@ Usage:
81
82
 
82
83
  --reconcile required — run the nine ensures (${ENSURE_OPS.join(', ')})
83
84
  --dry-run report what each ensure WOULD do; write nothing
84
- --only <op> run EXACTLY ONE of them (an unknown, missing or repeated value is a usage error)
85
+ --only <op> run EXACTLY ONE of them (an unknown, missing or repeated value is a usage error); for
86
+ scripts or specs, a write-free survey of the other owning op feeds the replace block
85
87
  --replace-custom <digest>
86
88
  the replace run the replace block prints, run only on the user's yes: every edit its
87
- digest names is kept aside under .agent-workflow/kept-aside/, then replaced, then index
88
- runs when nothing failed (not with --only or --dry-run; an empty value is a usage error)
89
+ digest names is kept aside under .agent-workflow/kept-aside/, then the kit scripts and the
90
+ spec layer replace and place their files, then index runs when nothing failed (not with
91
+ --only or --dry-run; an empty value is a usage error)
89
92
  --cwd <dir> the target project (default: the current directory)
90
93
  --help, -h this help
91
94
 
@@ -102,10 +105,10 @@ the project's own checker judges the navigator and a write it rejects is put bac
102
105
  The executor ensure writes nothing: a placed .claude/agents/executor.md whose bytes differ from the
103
106
  body derived from docs/ai/vehicles.json is pending — the advisor's executor-vehicle.differing item
104
107
  changes it on your yes; an absent file is never placed here.
105
- A fifth refreshes too: the enforcement-script ensure refreshes the hook installer with its two suites
106
- as one set on every Node deployment, whatever its ADR layout, only while each refreshed file is a body a
107
- release shipped (an edited member keeps all three; an absent one is never placed); then it detects an
108
- older ADR-store layout and instructs the opt-in migration instead of seeding the ADR files.
108
+ A fifth refreshes too: once a kit script stands in scripts/, the enforcement-script ensure judges every
109
+ kit script, the hook installer and its two suites first: a body a release shipped is refreshed, an edited
110
+ or absent one is named in the replace block, kept aside and replaced or placed only on the user's yes;
111
+ on an older ADR-store layout the decisions files are held back and the opt-in migration is named.
109
112
 
110
113
  Exit codes: 0 every op fine; 1 an op failed (its line says so) or there is no deployment here; 2 usage.`;
111
114
 
@@ -168,16 +171,19 @@ const runOne = (op, args) => {
168
171
  // Run every op in ENSURE_OPS order. A throw from one op becomes THAT op's failed outcome — the
169
172
  // remaining ops still run, because a project missing its gate declaration should not also be left
170
173
  // without its autonomy seed just because the first ensure hit an unreadable file. → { outcomes, block }:
171
- // the block is the union of the entries of the ops that ran. The replace run is the one exception,
172
- // handed to runReplace: it keeps every edit aside, runs the owning ops, then index only when none
173
- // failed, and its block is non-empty only when the digest no longer matches.
174
+ // the block is the union the replace run recomputes — an --only run of an owning op adds the entries of
175
+ // a write-free survey of every other owning op, printing that survey only when it failed. The replace
176
+ // run is the one exception, handed to runReplace: it keeps every edit aside, runs the owning ops, then
177
+ // index only when none failed, and its block is non-empty only when the digest no longer matches.
174
178
  export const runEnsures = ({ cwd, kitRoot, dryRun, deps, only, replaceCustom }) => {
175
179
  if (replaceCustom !== undefined) {
176
180
  const owning = OWNING_OPS.map((op) => ({ op, run: (args) => runOne(op, args) }));
177
181
  return runReplace({ cwd, kitRoot, digest: replaceCustom, owning, index: (args) => runOne('index', args), deps });
178
182
  }
179
183
  const outcomes = (only ? [only] : ENSURE_OPS).map((op) => runOne(op, { cwd, kitRoot, dryRun, deps }));
180
- return { outcomes, block: outcomes.flatMap((o) => o.entries ?? []) };
184
+ const surveys = OWNING_OPS.includes(only) ? OWNING_OPS.filter((op) => op !== only).map((op) => runOne(op, { cwd, kitRoot, dryRun: true, deps })) : [];
185
+ const shown = [...outcomes, ...surveys.filter((o) => o.failed)].sort((a, b) => ENSURE_OPS.indexOf(a.op) - ENSURE_OPS.indexOf(b.op));
186
+ return { outcomes: shown, block: [...outcomes, ...surveys].flatMap((o) => o.entries ?? []) };
181
187
  };
182
188
 
183
189
  const render = ({ outcomes, block }, { dryRun, only, replace, kitRoot, cwd }) => {
@@ -17,10 +17,9 @@
17
17
  // orchestration-config.mjs (refreshReadme / the known-prior canonical set) and writes through
18
18
  // orchestration-write.mjs — the file's one writer. Nothing here re-derives either.
19
19
  // • Every token names a state this run PROVED. `already-present` follows a probe; `skipped-no-node-evidence`
20
- // names every Node probe that answered absent; an ADR-layout read that fails is `adr-layout-unverifiable` and
21
- // seeds no ADR file (the STRICT survey, fail-closed — the lenient status wrapper reads an unreadable
22
- // tree as `none`, which here would mean seeding a rotator beside a store nobody could inspect); the
23
- // installer set's refresh runs before and independent of that read, and its lines stand either way.
20
+ // names every Node probe that answered absent (the refusal the kit-script and spec-layer ensures
21
+ // share, below; the kit scripts' rule — refresh a shipped prior, place or replace on the user's
22
+ // yes — lives in distribution-files/scripts.mjs).
24
23
  // • A failed op is a non-zero signal, never a line that reads like success.
25
24
  //
26
25
  // Dependency-free, Node >= 22. Every fs primitive is injectable (deps.*). No side effects on import.
@@ -30,14 +29,13 @@ import { spawnSync } from 'node:child_process';
30
29
  import { join } from 'node:path';
31
30
  import { CANON_README, CONFIG_REL, SEED_CONFIG, loadConfig, normalizeCanonical, refreshReadme } from './orchestration-config.mjs';
32
31
  import { seedConfig, writeConfig } from './orchestration-write.mjs';
33
- import { lstatNoFollow, writeContainedFileAtomic, writeDocsAiFileAtomic, writeProjectFileCreateOnly } from './atomic-write.mjs';
32
+ import { lstatNoFollow, writeDocsAiFileAtomic } from './atomic-write.mjs';
34
33
  import { GATES_REL } from './gates-declaration.mjs';
35
34
  import { AUTONOMY_REL } from './autonomy-config.mjs';
36
35
  import { VEHICLES_REL } from './vehicle-settings.mjs';
37
- import { surveyAdrLayoutStrict } from './family-registry.mjs';
38
- import { ENSURE_TOKENS, FAILURE_CAUSES, SEED_SCRIPTS } from './ensure-vocabulary.mjs';
36
+ import { ENSURE_TOKENS, FAILURE_CAUSES } from './ensure-vocabulary.mjs';
39
37
  import { NODE_EVIDENCE, describeNodeProbes, probeNodeEvidence } from './node-evidence.mjs';
40
- import { INSTALLER_SET, classifyDeployedScript } from './script-priors.mjs';
38
+ import { classifyDeployedScript } from './script-priors.mjs';
41
39
  import { parseFrontmatter } from '../references/scripts/check-docs-size.mjs';
42
40
 
43
41
  // The closed vocabulary lives in its own PURE leaf so the read-only doc-parity lint can bind the
@@ -50,7 +48,6 @@ export {
50
48
  FAILURE_CAUSES,
51
49
  RELAYED_ENSURE_TOKENS,
52
50
  RELAYED_FAILURE_CAUSES,
53
- SEED_SCRIPTS,
54
51
  WRITE_TOKENS,
55
52
  } from './ensure-vocabulary.mjs';
56
53
 
@@ -212,7 +209,7 @@ export const ensureAutonomy = ({ cwd, kitRoot, dryRun = false, deps = {} }) =>
212
209
  export const ensureVehicles = ({ cwd, kitRoot, dryRun = false, deps = {} }) =>
213
210
  seedFromTemplate({ op: VEHICLES_OP, rel: VEHICLES_REL, template: VEHICLES_TEMPLATE, noun: VEHICLES_NOUN, cwd, kitRoot, dryRun, deps });
214
211
 
215
- // ── scripts/ — the ADR-cascade enforcement pairs, detect-first ──────────────────────────────────
212
+ // ── scripts/ — the Node-evidence refusal the script-placing ensures share ─────────────────────────
216
213
 
217
214
  // The Node-evidence refusal every ensure that places Node scripts shares (contract: kit/node-evidence):
218
215
  // null when Node provably runs here, else the ONE outcome the caller returns — a stated skip naming the
@@ -228,123 +225,6 @@ export const nodeEvidenceRefusal = (op, cwd, lstat) => {
228
225
  return null;
229
226
  };
230
227
 
231
- const OLD_ADR_LAYOUTS = new Set(['old', 'old-unrotated']);
232
-
233
- // The scripts ensure writes file by file, so a failure PARTWAY leaves earlier writes (refreshed set members,
234
- // copied seeds) in place. Saying so is the difference between a failure the reader can act on and one they
235
- // read as "nothing happened" — the CLI's summary claims nothing about writes; this line states the truth.
236
- const REFRESHED = ' — refreshed to the bundled one';
237
- const partialNote = (lines) => {
238
- const copied = lines.filter((line) => line.includes(': copied from the bundled scripts') || line.endsWith(REFRESHED)).length;
239
- return copied > 0 ? [`the copying stopped PARTWAY — the ${copied} file(s) named above were already copied and are NOT rolled back`] : [];
240
- };
241
-
242
- // ── the installer set: refreshed as ONE, before and independent of the ADR-layout read ──────────
243
-
244
- // The deployed suites test the installer beside them, so the three move together: an edited member withholds
245
- // all three, a prior one is replaced in INSTALLER_SET order (installer first), an absent one stays absent, and
246
- // with none present nothing is read. → { refusal } or { lines, refreshed, withheld }, each line what this run did.
247
- const WITHHELD = 'left as it stands because an edited member withholds the set';
248
- const PRIOR_FATES = { written: REFRESHED, would: ' — would be refreshed to the bundled one', stopped: ' — not refreshed; the run stopped before it', refused: ' — not refreshed; its write was refused (above)' };
249
- const SET_LINES = {
250
- absent: () => 'absent — not placed by this op',
251
- current: (withheld) => (withheld ? WITHHELD : 'already the bundled body — nothing written'),
252
- custom: () => 'carries an edited body — preserved verbatim; an edited member withholds the set, so none of the three is refreshed',
253
- prior: (withheld, fate) => (withheld ? WITHHELD : `matches a body an earlier release shipped${PRIOR_FATES[fate]}`),
254
- };
255
- const refreshInstallerSet = ({ cwd, kitRoot, dryRun, deps, read, lstat }) => {
256
- const members = INSTALLER_SET.map((name) => ({ name, rel: `${SCRIPTS_DIR}/${name}`, state: 'absent', probe: probeSeedTarget(join(cwd, SCRIPTS_DIR, name), lstat) }));
257
- if (!members.some((m) => m.probe.present)) return { lines: [], refreshed: false, withheld: false };
258
- const wrong = members.find((m) => m.probe.wrongKind);
259
- if (wrong) return { refusal: loud('scripts', 'wrong-node-kind', `${wrong.rel}: exists but is ${wrong.probe.wrongKind} — nothing was read or written; resolve it by hand, then re-run`) };
260
- for (const m of members.filter((f) => f.probe.present)) {
261
- try {
262
- m.bundle = read(join(kitRoot, 'references', 'scripts', m.name));
263
- } catch (err) {
264
- return { refusal: loud('scripts', 'bundle-unreadable', `${m.rel}: the bundled script could not be read, so nothing was written — reinstall the kit. ${causeOf(err)}`) };
265
- }
266
- m.state = classifyDeployedScript(read(join(cwd, m.rel)), m.name, m.bundle);
267
- }
268
- const withheld = members.some((m) => m.state === 'custom');
269
- const priors = withheld ? [] : members.filter((m) => m.state === 'prior');
270
- const fates = new Map();
271
- const notes = [];
272
- const linesNow = () => [...members.map((m) => `${m.rel}: ${SET_LINES[m.state](withheld, fates.get(m.rel) ?? (dryRun ? 'would' : 'stopped'))}`), ...notes];
273
- for (const m of dryRun ? [] : priors) {
274
- try {
275
- notes.push(...tmpNote(m.rel, writeContainedFileAtomic(cwd, join(cwd, m.rel), m.bundle, deps, { label: m.rel }).tmpLeftBehind));
276
- } catch (err) {
277
- fates.set(m.rel, 'refused');
278
- const lines = linesNow();
279
- return { refusal: loud('scripts', 'write-refused', `${m.rel}: ${causeOf(err)}`, ...lines, ...partialNote(lines)) };
280
- }
281
- fates.set(m.rel, 'written');
282
- }
283
- return { lines: linesNow(), refreshed: priors.length > 0, withheld };
284
- };
285
-
286
- // The op's ONE token after the instructed migration: a seed, then the set's refresh, then an edited set kept.
287
- const scriptsToken = (seeded, set, dryRun) => {
288
- if (seeded) return dryRun ? 'would-seed' : 'seeded';
289
- if (set.refreshed) return dryRun ? 'would-refresh' : 'refreshed';
290
- return set.withheld ? 'customized-preserved' : 'already-present';
291
- };
292
-
293
- export const ensureScripts = ({ cwd, kitRoot, dryRun = false, deps = {} }) => {
294
- const lstat = deps.lstat ?? lstatSync;
295
- const read = deps.readFile ?? readFileSync;
296
- const refusal = nodeEvidenceRefusal('scripts', cwd, lstat);
297
- if (refusal) return refusal;
298
- const set = refreshInstallerSet({ cwd, kitRoot, dryRun, deps, read, lstat });
299
- if (set.refusal) return set.refusal;
300
- let layout;
301
- try {
302
- layout = surveyAdrLayoutStrict(cwd, deps);
303
- } catch (err) {
304
- return loud('scripts', 'adr-layout-unverifiable', `${SCRIPTS_DIR}/: the ADR-store layout could not be read, so the ADR files were not seeded — a rotator seeded beside an un-migrated store reds the ADR gate. ${causeOf(err)}`, ...set.lines, ...partialNote(set.lines));
305
- }
306
- if (OLD_ADR_LAYOUTS.has(layout)) {
307
- return ok('scripts', 'old-adr-layout-migration-instructed', ...set.lines, `${SCRIPTS_DIR}/: this project is still on the older ADR layout (${layout}) — the ADR files were not seeded. Run the opt-in /agent-workflow-kit migrate-adr-store (it previews, and never commits); the seed lands on the next upgrade.`);
308
- }
309
- const lines = [...set.lines];
310
- let anyCreated = false;
311
- for (const name of SEED_SCRIPTS) {
312
- const rel = `${SCRIPTS_DIR}/${name}`;
313
- const probe = probeSeedTarget(join(cwd, SCRIPTS_DIR, name), lstat);
314
- if (probe.wrongKind) {
315
- return loud('scripts', 'wrong-node-kind', `${rel}: exists but is ${probe.wrongKind} — that is not the enforcement script this run places`, ...lines, ...partialNote(lines));
316
- }
317
- if (probe.present) {
318
- lines.push(`${rel}: already present — preserved, never overwritten`);
319
- continue;
320
- }
321
- if (dryRun) {
322
- lines.push(`${rel}: absent — would be copied from the bundled scripts`);
323
- continue;
324
- }
325
- let body;
326
- try {
327
- body = String(read(join(kitRoot, 'references', 'scripts', name), 'utf8'));
328
- } catch (err) {
329
- return loud('scripts', 'bundle-unreadable', `${rel}: the bundled script could not be read — reinstall the kit. ${causeOf(err)}`, ...lines, ...partialNote(lines));
330
- }
331
- // The WRITE is caught here, not by the CLI's catch-all: a throw that escapes this loop would take
332
- // the accumulated lines with it, and the run would report a failure without saying which files it
333
- // had already copied.
334
- let result;
335
- try {
336
- result = writeProjectFileCreateOnly(cwd, rel, body, deps, { noun: 'a seeded enforcement script' });
337
- } catch (err) {
338
- return loud('scripts', 'write-refused', `${rel}: ${causeOf(err)}`, ...lines, ...partialNote(lines));
339
- }
340
- anyCreated = anyCreated || result.created;
341
- lines.push(result.created ? `${rel}: copied from the bundled scripts` : `${rel}: appeared while this run was seeding it — the existing file stands`);
342
- lines.push(...tmpNote(rel, result.tmpLeftBehind));
343
- }
344
- const seeded = dryRun ? lines.some((line) => line.includes('would be copied')) : anyCreated;
345
- return outcome('scripts', scriptsToken(seeded, set, dryRun), lines, false);
346
- };
347
-
348
228
  // ── docs/ai/index.md — the GENERATED navigator, regenerated when missing or stale ───────────────
349
229
 
350
230
  // The only ensure whose target is generated rather than authored: nothing to seed from, and on the
@@ -516,6 +396,5 @@ export const OWN_IMPLEMENTATIONS = Object.freeze({
516
396
  gates: ensureGates,
517
397
  autonomy: ensureAutonomy,
518
398
  vehicles: ensureVehicles,
519
- scripts: ensureScripts,
520
399
  index: ensureIndex,
521
400
  });
@@ -1,6 +1,7 @@
1
1
  // ensure-specs.mjs — the SIXTH upgrade ensure: the spec layer (memory 4.6.0, AD-112) delivered to an
2
- // EXISTING deployment on an equal-head upgrade. Four deployed scripts and one store root, written in
3
- // a FIXED order the measured coupling dictates:
2
+ // EXISTING deployment on an equal-head upgrade. Four deployed scripts (the pairs script-priors.mjs
3
+ // names; every other kit script is the scripts ensure's) and one store root, written in a FIXED order
4
+ // the measured coupling dictates:
4
5
  // 1. the reader pair scripts/spec-schema.mjs + .test.mjs — created when absent; since 2a
5
6
  // also REFRESHED when the deployed bytes are a body a release shipped (script-priors.mjs), a
6
7
  // custom body preserved verbatim and reported as a replace entry (distribution-files/): the
@@ -26,9 +27,9 @@
26
27
  import { readFileSync, lstatSync } from 'node:fs';
27
28
  import { join } from 'node:path';
28
29
  import { writeContainedFileAtomic, writeProjectFileCreateOnly } from './atomic-write.mjs';
29
- import { classifyDeployedScript, digestOf } from './script-priors.mjs';
30
+ import { CHECKER_PAIR, READER_PAIR, classifyDeployedScript, digestOf } from './script-priors.mjs';
30
31
  import { composeFailure, composeOutcome, nodeEvidenceRefusal, probeSeedTarget, tmpNote } from './ensure-ops.mjs';
31
- import { keptAsidePath } from './distribution-files/index.mjs';
32
+ import { SCRIPT_CHANNEL, keptAsidePath } from './distribution-files/index.mjs';
32
33
 
33
34
  const OP = 'specs';
34
35
  const SCRIPTS_DIR = 'scripts';
@@ -36,11 +37,6 @@ const BUNDLED_SCRIPTS = ['references', 'scripts'];
36
37
  const STORE_ROOT_REL = 'docs/ai/specs/index.md';
37
38
  const STORE_ROOT_TEMPLATE = ['references', 'templates', 'specs', 'index.md'];
38
39
  const DATE_PLACEHOLDER = '{{DATE}}';
39
- const CHANNEL = 'a script or suite of your own under its own name in scripts/, or a config the script reads';
40
- // Explicit pairs, deliberately NOT aliased to the catalog's PRIOR_FILES (which spans both): each
41
- // file is surveyed exactly once. Exported so the suite pins pairs-union === catalog domain.
42
- export const READER_PAIR = Object.freeze(['spec-schema.mjs', 'spec-schema.test.mjs']);
43
- export const CHECKER_PAIR = Object.freeze(['check-docs-size.mjs', 'check-docs-size.test.mjs']);
44
40
 
45
41
  const causeOf = (err) => String((err && err.message) || err);
46
42
  const todayIso = () => new Date().toISOString().slice(0, 10);
@@ -191,7 +187,7 @@ export const ensureSpecs = ({ cwd, kitRoot, dryRun = false, deps = {}, replace }
191
187
 
192
188
  // The survey completed: its entries ride every outcome from here on, a failed one included.
193
189
  const custom = [...reader, ...checker].filter((f) => f.state === 'custom');
194
- const entries = custom.map((f) => ({ rel: f.rel, sha256: digestOf(f.bytes), bytes: f.bytes, channel: CHANNEL }));
190
+ const entries = custom.map((f) => ({ rel: f.rel, sha256: digestOf(f.bytes), bytes: f.bytes, channel: SCRIPT_CHANNEL }));
195
191
  const ok = (token, lines) => ({ ...composeOutcome(OP, token, lines, false), entries });
196
192
  const loud = (cause, ...lines) => ({ ...composeFailure(OP, cause, ...lines), entries });
197
193
  const bound = replace ? new Map(replace.entries.map((e) => [e.rel, e.sha256])) : null;
@@ -9,16 +9,19 @@
9
9
 
10
10
  // The FIXED order the CLI runs them in — the order references/modes/upgrade.md already prescribed.
11
11
  // `specs` sits after `scripts` (its reader pair is a scripts/ seed too) and BEFORE `index`: the store
12
- // root it seeds is a docs/ai file the navigator must count.
12
+ // root it seeds is a docs/ai file the navigator must count. `scripts` and `specs` own the replace run,
13
+ // in this order: each keeps its files current by the one rule, an edited or absent one written only
14
+ // on the user's yes.
13
15
  // `executor` follows `vehicles`: its body is derived from the settings file that op seeds.
14
16
  // `rules` follows `specs` and precedes `index`: the rules files it lays are docs/ai files the navigator counts.
15
17
  export const ENSURE_OPS = Object.freeze(['orchestration', 'gates', 'autonomy', 'vehicles', 'executor', 'scripts', 'specs', 'rules', 'index']);
16
18
 
17
19
  // Tokens that assert a WRITE happened. --dry-run may never emit one of these (the CLI's contract test
18
20
  // walks this set), and each has exactly one `would-` counterpart below. `refreshed` is the spec-layer
19
- // ensure's pair refresh (reader or checker) or the scripts ensure's installer-set refresh — a deployed
20
- // script on a body a release shipped, rewritten to the bundled one; a custom body is rewritten only by
21
- // the replace run the user's yes starts (--replace-custom, the spec layer's), never by a plain run.
21
+ // ensure's pair refresh (reader or checker) or the scripts ensure's refresh of a kit script — a deployed
22
+ // script on a body a release shipped, rewritten to the bundled one; an edited body is replaced, and an
23
+ // absent kit script placed, only by the replace run the user's yes starts (--replace-custom, over the
24
+ // kit scripts and then the spec layer), never by a plain run.
22
25
  export const WRITE_TOKENS = Object.freeze(['seeded', 'note-refreshed', 'refreshed', 'regenerated']);
23
26
  export const DRY_RUN_TOKENS = Object.freeze(['would-seed', 'would-refresh-note', 'would-refresh', 'would-regenerate']);
24
27
 
@@ -91,12 +94,3 @@ export const RELAYED_ENSURE_TOKENS = Object.freeze([
91
94
  'old-adr-layout-migration-instructed',
92
95
  'failed',
93
96
  ]);
94
-
95
- // The four files the enforcement-script ensure seeds (AD-051's ADR cascade + the tokenizer it needs).
96
- // Seed nothing else: the other tokenizer-era tests red beside an OLD archiver.
97
- export const SEED_SCRIPTS = Object.freeze([
98
- 'archive-decisions.mjs',
99
- 'archive-decisions.test.mjs',
100
- 'markdown-blocks.mjs',
101
- 'markdown-blocks.test.mjs',
102
- ]);
@@ -1,9 +1,10 @@
1
1
  // script-priors.mjs — the APPEND-ONLY catalog of every enforcement-script body this family has shipped
2
2
  // into a project's `scripts/`, as sha256 digests, and the ONE classifier a refresh asks before it
3
3
  // replaces a deployed script — the spec-layer ensure for its pairs, the `hook-checks` writer for the
4
- // hook installer alone and the upgrade's `scripts` ensure for the installer set: `current` (byte-equal to the bundled copy) · `prior` (a body a release shipped, never
5
- // edited since) · `custom` (anything else — preserved verbatim, replaced only by the replace run the
6
- // user's yes starts). The lens-region idiom (AD-041) over whole script bodies.
4
+ // hook installer alone and the upgrade's `scripts` ensure for every other kit script: `current`
5
+ // (byte-equal to the bundled copy) · `prior` (a body a release shipped, never edited since) · `custom`
6
+ // (anything else — kept aside and replaced only by the replace run the user's yes starts). The
7
+ // lens-region idiom (AD-041) over whole script bodies.
7
8
  //
8
9
  // Append discipline: when a release changes one of PRIOR_FILES, append the OUTGOING body's row here
9
10
  // in the same release and copy its bytes to test/fixtures/script-priors/<firstShipped>/<file>.txt —
@@ -14,17 +15,24 @@
14
15
 
15
16
  import { createHash } from 'node:crypto';
16
17
 
17
- // The deployed scripts a refresh may REPLACE — the FULL refreshable catalog: the checker pair that
18
- // imports the reader and (since 2a) the reader pair itself, which the spec-layer ensure refreshes, and
19
- // the installer set: the `hook-checks` writer refreshes the installer alone, the upgrade's `scripts`
20
- // ensure the installer with its two suites. Every other deployed script is outside the refresh lane by design.
18
+ // The deployed scripts a refresh may REPLACE: every bundled name (the suite pins it equal to the
19
+ // bundle). A name with no row here classifies `custom` on any body but the bundled one.
21
20
  export const PRIOR_FILES = Object.freeze([
22
- 'check-docs-size.mjs', 'check-docs-size.test.mjs', 'spec-schema.mjs', 'spec-schema.test.mjs', 'install-git-hooks.mjs',
23
- 'install-git-hooks.test.mjs', 'install-git-hooks-repo-exec.test.mjs',
21
+ '_expect-shim.mjs', 'archive-caps.mjs', 'archive-caps.test.mjs', 'archive-changelog.mjs', 'archive-changelog.test.mjs',
22
+ 'archive-conservation.test.mjs', 'archive-decisions.mjs', 'archive-decisions.test.mjs', 'archive-issues.mjs',
23
+ 'archive-issues.test.mjs', 'archiver-structure.test.mjs', 'check-docs-size-cli.test.mjs', 'check-docs-size-ensure.test.mjs',
24
+ 'check-docs-size.mjs', 'check-docs-size.test.mjs', 'install-git-hooks-repo-exec.test.mjs', 'install-git-hooks.mjs',
25
+ 'install-git-hooks.test.mjs', 'markdown-blocks.mjs', 'markdown-blocks.test.mjs', 'migrate-gates-branches.test.mjs',
26
+ 'migrate-gates.mjs', 'migrate-gates.test.mjs', 'spec-schema.mjs', 'spec-schema.test.mjs',
24
27
  ]);
25
28
 
26
- // The hook installer and the two suites that test it beside it — refreshed as ONE set, installer first,
27
- // so a stop partway never leaves a bundled suite beside a prior installer.
29
+ // The spec-layer pairs the specs ensure owns — the reader and the checker that imports it; every other
30
+ // name is the scripts ensure's. Here, in the pure leaf, so both ops import them and neither imports the other.
31
+ export const READER_PAIR = Object.freeze(['spec-schema.mjs', 'spec-schema.test.mjs']);
32
+ export const CHECKER_PAIR = Object.freeze(['check-docs-size.mjs', 'check-docs-size.test.mjs']);
33
+
34
+ // The hook installer and the two suites that test it beside it — written first, installer first, so a
35
+ // stop partway never leaves a bundled suite beside a prior installer.
28
36
  export const INSTALLER_SET = Object.freeze(['install-git-hooks.mjs', 'install-git-hooks.test.mjs', 'install-git-hooks-repo-exec.test.mjs']);
29
37
 
30
38
  const prior = (file, firstShipped, lastShipped, digest) => Object.freeze({ file, firstShipped, lastShipped, digest });