@sabaiway/agent-workflow-kit 14.50.0 → 15.1.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,47 @@ 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
+ ## 15.1.0 — the upgrade writes the kit rules file current with no question; the rules mode no longer moves an edit (AD-205)
8
+
9
+ **`/agent-workflow-kit upgrade` now puts the kit's rules file back to the kit's template, whatever it holds.** Before,
10
+ a `docs/ai/rules/<theme>.md` that differed from every body a release shipped was kept byte for byte and the kit's
11
+ updates to that file waited; a file with no frontmatter was kept and nothing else was written for its theme. Now any
12
+ such body (an edit, a body this kit does not know, a file with no frontmatter) is replaced by the bundled template
13
+ with no question and no copy kept, and the step reports `refreshed`.
14
+ Its line reads `differs from every body this kit knows it shipped — replaced by the bundled template; a rule meant to
15
+ last goes in docs/ai/rules/local/<theme>.md, where it wins`.
16
+
17
+ - **Your own rules live in the local file.** `docs/ai/rules/local/<theme>.md` is never written by the upgrade, and its
18
+ rules win over the kit's. If you edited the kit file, move the edit there before you upgrade.
19
+ - **With a local file, the record is judged against the template.** When the record already holds the merge built
20
+ from the template, replacing an edited kit file writes only that file; otherwise the step reports `pending`, and the
21
+ record command it prints carries the template's digest.
22
+ - **`/agent-workflow-kit rules` offers three routes:** change a rule, drop your local rules, or change a number. The
23
+ route that moved an edit of the kit file into the local file is gone, with the README row's clause about it.
24
+ - **The texts say the same.** The upgrade mode's project-rules paragraph and its `rules` token list (no
25
+ `customized-preserved`), the header and `--help` of `tools/ensure-configs.mjs`, and the guide's *Reserved names and
26
+ channels*, which now names the kit rules files among the files the next upgrade writes over.
27
+
28
+ ## 15.0.0 — the opt-in ADR migration mode retires; status names the upgrade for an older ADR layout (AD-204)
29
+
30
+ **MAJOR: `/agent-workflow-kit migrate-adr-store` is gone, with no alias.** Since 14.50.0 the upgrade moves an older
31
+ ADR layout itself wherever `scripts/` holds the kit's decisions script, so the opt-in mode had nothing left to do
32
+ there. The mode, `tools/migrate-adr-store.mjs` and its suite are deleted, with the mode's catalog entry and its
33
+ `SKILL.md` section; the invocation now falls to `help`, like any unknown mode. No migration note is owed.
34
+
35
+ - **The advisor stops offering `adr-store-migration`.** The item is retired with no replacement, with its lane, its
36
+ row in `references/advisor-writers.md` and its posture note in `references/modes/recommendations.md`. The writers
37
+ table holds sixteen chat variants.
38
+ - **Status names the upgrade.** For a project on an older ADR layout (a retired archive file on disk, or a decisions
39
+ script older than the store), the `ADR store` line now reads `old layout — /agent-workflow-kit upgrade moves it where
40
+ scripts/ holds the kit's decisions rotator, or prints the rotator's refusal`, and the status mode's note carries the
41
+ same text.
42
+ - **The store run's failure says what it knows.** When the upgrade's run of `scripts/archive-decisions.mjs
43
+ --ensure-current` fails, its detail now ends `— the ADR store was not confirmed current` instead of `— the ADR store
44
+ is not current`; the cause `adr-store-not-current` is unchanged.
45
+
46
+ Where `scripts/` holds no kit script, nothing in the kit moves an older layout any more.
47
+
7
48
  ## 14.50.0 — the upgrade moves an older ADR layout itself, with no question (AD-203)
8
49
 
9
50
  **`/agent-workflow-kit upgrade` now brings your ADR store current in the same run.** Before, on a project still on the
package/README.md CHANGED
@@ -252,7 +252,7 @@ file), or run the guarded `/agent-workflow-kit uninstall`.
252
252
  | `/agent-workflow-kit review-state` | any time | **read-only review-receipt checker** — makes "reviewed ≠ shipped" detectable: the bridge review wrappers append a receipt per successful review (into a file inside the git dir — never committable); this checks that every backend your configured `plan-execution.review` recipe names holds a **fresh, grounded receipt for the current uncommitted tree** (any later edit the payload can see moves the fingerprint and stales the receipt; a review continuation never re-attests a folded tree). `--check` gives a gate exit code to declare in `docs/ai/gates.json` **by hand or via the consent-gated seeder** (preview → your explicit yes; never without consent). `--await [--timeout <s>]` (AD-049) BLOCKS until every recipe-named backend has receipted the current tree — the durable completion signal is the receipt, never a process event — so you wait for the bridges instead of hand-polling. Never writes, never commits, never runs a subscription CLI; it spawns read-only `git` queries to fingerprint the tree — and `git commit --no-verify` stays possible (discipline, not a sandbox). |
253
253
  | `/agent-workflow-kit sandbox-masks` | any time | **exclude lane for sandbox masks** — an OS sandbox (Claude Code) masks work-tree paths with a device or, on Linux, a foreign bind mount, as untracked `git status` noise; the review domain already ignores a **device mask** **by construction** (never-committable untracked classes — char/block devices, FIFOs, sockets — are excluded from the fingerprint, the assembled review payload, and the clean checks), while a **mount-only mask** rides the fingerprint and `git add -A` while git does not ignore it (load-bearing there). This mode hides them from `git status` too: flagless = read-only probe (derives the CURRENT mask set from the unfiltered walk + lstat + `/proc/self/mountinfo` — never a frozen list; off Linux the mount signal is not read and it says so, an unreadable or malformed table refuses — and revalidates fenced entries, loudly flagging one that became a real path); `--apply` = consent-gated FULL-BLOCK replace of its own fenced block in `git rev-parse --git-path info/exclude` (stale masks drop by construction; `--clear` always means REMOVE the block — it takes precedence over the derivation). Writes ONLY its fence — never `.gitignore`, never global config; symlinked/non-regular exclude paths and malformed fences fail closed. Watch note: a real file at an excluded path is silently skipped by bulk staging (`git add -A`/`git add .`) — delete the stale line first; the probe flags exactly this case. |
254
254
  | `/agent-workflow-kit mcp` | Claude Code · opt-in | **typed-channel registration** — the kit ships a read-only stdio **MCP server** exposing its two promptless readers as TYPED tools (`path_inventory`: exists / type / size / line count / listing / a small file's text, many paths in ONE call; `repo_search`: literal search, the pattern a JSON string). Their arguments are named JSON fields rather than a string handed to a shell, so a pipe, a redirect or a quote inside a pattern or a path stays DATA and is never interpreted — legal bytes to search for, with no shell to read them as operators. Shipping the server does nothing on its own — a client sees it only once the project declares it, and this mode is that declaration: the `agent-workflow` entry in **`.mcp.json`** (command `node`, args = the absolute path of the RUNNING kit's server) plus `enabledMcpjsonServers` and the two derived tool allow rules in **`.claude/settings.json`**. Preview by default and the **exact entry is printed before consent** (registering a server means your client will run that command); `--apply` writes `.mcp.json` FIRST, then settings, merge-don't-clobber with each file's EOL kept, and a re-apply adds nothing twice. An existing `agent-workflow` entry that **structurally differs** from what this kit copy would write is refused unwritten unless `--replace` is given (the comparison ignores key order, so re-serialized identical bytes are the same registration) — silently changing what an MCP server launches is what consent must not slide past. `--replace` prints the entry standing in `.mcp.json` and the entry it would write, and replaces it only with `--apply`. An existing `.mcp.json` or `.claude/settings.json` is written in place: it keeps its inode, never removed or renamed over; an absent file is created. Where an OS sandbox masks `.mcp.json` with a device node, it writes nothing, exits 0 and names the advisor's `mcp-channel` item, which applies the registration by the consent route. The server is a read-only child of your client (no write, no exec API) running outside the Bash sandbox as the client does. Never writes `settings.local.json`; never commits. |
255
- | `/agent-workflow-kit rules` | any time | **your project rules** — the kit lays down default rules per theme (the first is project layout: where code, tests and specs live) in `docs/ai/rules/<theme>.md`; your own rules go into `docs/ai/rules/local/<theme>.md` and win where they differ. Tell the agent in plain words what to change: it shows the exact text first and writes your local file only on your yes, then rebuilds the effective file `docs/ai/rules/effective/<theme>.md` that agents read (merging your rules over the kit’s by meaning) and checks it is current. It also moves an edit you made to the kit file into your local file, or drops your local rules on request. Never commits. |
255
+ | `/agent-workflow-kit rules` | any time | **your project rules** — the kit lays down default rules per theme (the first is project layout: where code, tests and specs live) in `docs/ai/rules/<theme>.md`; your own rules go into `docs/ai/rules/local/<theme>.md` and win where they differ. Tell the agent in plain words what to change: it shows the exact text first and writes your local file only on your yes, then rebuilds the effective file `docs/ai/rules/effective/<theme>.md` that agents read (merging your rules over the kit’s by meaning) and checks it is current. It also drops your local rules on request. Never commits. |
256
256
  | `/agent-workflow-kit grounding` | any time | **grounded-review facts assembler** — mechanizes populating `agy-review --facts @f`: slices your entry-point's **Hard Constraints** section verbatim (exactly one match, else a loud stop) and/or a plan's three canon sections (`## Goal and boundary` + `## Module ledger` + `## Verification`, each required; duplicates stop), under the same byte budget the agy wrapper enforces (minus `--reserve-bytes` for the artifact share), with a loud tail-trim on overflow. `--autonomy` (AD-044) appends the COMPUTED effective autonomy policy from the git-top `docs/ai/autonomy.json` (every red-line + per-activity level, stated source line; absent file → the computed defaults ARE the policy, exit 0; a malformed policy fails CLOSED, exit 1). `--extra <text|@file>` (repeatable) appends your own facts **byte-verbatim** after the mechanical sections, so the merge is a tool input rather than a shell append — an `@file` must sit inside the proven git work tree (never the git dir) or the system temp surface, and is read through a no-follow descriptor (a FIFO cannot block it, a symlink leaf cannot substitute its target). Prints to stdout; `--out` writes **one scratch file only** — system-temp outside the repo ($TMPDIR / /tmp, rewritable) or a **fresh** gitignored in-repo path (create-only, exclusive write; an existing in-repo file, even gitignored, is refused — the `.env` clobber class); tracked, not-ignored-in-repo, other outside-repo, and symlink/non-regular destinations are all refused. Never commits, never runs a subscription CLI. |
257
257
  | `/agent-workflow-kit core-evidence` | any time | **the ONE loop-evidence writer** (strip-the-kit) — every core evidence record lands in a single append-only JSONL store inside the git dir (never committable; versioned schema, latest-per-key supersession, byte-identical duplicates refused, malformed lines fail every reader closed). `red-proof "<file>#<pattern>"` declares an observed-red **BEFORE a bugfix** (N/N red runs + content custody + base + the pre-fix fingerprint; green/mixed/timeout are DISTINGUISHED refusals — nothing written); `degrade --backend --reason` is the ONLY escape for an unavailable review backend (per-tree, never all backends); `summary` renders the whole loop state statelessly (gate result · per-backend verdicts · red-proofs · degrades) — no ledger, no rounds, nothing remembered. Honest residual: records are forgeable — self-discipline, not a security boundary. Never commits, never runs a subscription CLI. |
258
258
  | `/agent-workflow-kit coverage-check` | any time | **the final-run checker** (D3(c)+(d)) — **certifies coverage ONLY inside the `--final` run that owns the lcov** (ownership is exclusive by CONVENTION over the fixed path, not enforced — a concurrent writer to it is a stated residual, queued as LCOV-EXCLUSIVE-OWNERSHIP): an artifact on disk proves nothing about the tree it came from, so a standalone run prints its findings and states `attested=no` / `NO VERDICT` rather than a PASS (an lcov that predates an edit would otherwise certify a line the suite never executed). `attested=` claims a verdict was ISSUED, pass or fail — a run over uncovered lines still reads `attested=yes` and still exits 1, and a run whose coverage arm never executed (no lcov) reads `attested=no` even inside `--final`, because nothing was read and nothing is certified. The runner passes a nonce whose one-way commitment over `{nonce, fingerprint, base}` is the `final-start.attempt` it recorded; a context describing another tree, or matching no recorded attempt, is a REFUSAL, never a verdict. Findings are unchanged — reads the lcov the declared `unit-tests` gate produced at the FIXED git-dir path and fails on any uncovered CHANGED executable Node line (listed `file:line`; a changed file absent from the map is a file-level red; out-of-domain/unsupported files are LISTED — the claim narrowed honestly); VERIFIES every current-base red-proof declaration (bound test exists · custody hash unchanged · green N/N now · pre-fix fingerprint differs); prints `lcov-sha256=<hex|none>` of the exact bytes it consumed — the sha the `--final` receipt binds and re-hashes. An absent lcov is a LOUD `skipped-no-lcov`; a symlinked path is a refusal. `--check` is the gate exit code — declare it as the LAST gate (`run-gates --final` refuses otherwise). Read-only. |
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.50.0'
6
+ version: '15.1.0'
7
7
  ---
8
8
 
9
9
  # agent-workflow-kit
@@ -171,10 +171,6 @@ writer — read `${CLAUDE_SKILL_DIR}/references/modes/rules.md` before acting.
171
171
 
172
172
  guarded — read `${CLAUDE_SKILL_DIR}/references/modes/uninstall.md` before acting.
173
173
 
174
- ### Mode: migrate-adr-store
175
-
176
- guarded — read `${CLAUDE_SKILL_DIR}/references/modes/migrate-adr-store.md` before acting.
177
-
178
174
  ### Mode: velocity
179
175
 
180
176
  writer — read `${CLAUDE_SKILL_DIR}/references/modes/velocity.md` before acting.
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.50.0",
6
+ "version": "15.1.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.50.0",
3
+ "version": "15.1.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",
@@ -41,7 +41,6 @@
41
41
  | attribution | harness | attribution.mjs |
42
42
  | footprint-global | harness | hide-footprint.mjs |
43
43
  | family-freshness | user | user step |
44
- | adr-store-migration | chat | migrate-adr-store.mjs |
45
44
  | sandbox-masks | chat | sandbox-masks.mjs |
46
45
  | sandbox-masks.unfenced-mount | chat | sandbox-masks.mjs |
47
46
  | worktrees-dir | harness | velocity-profile.mjs |
@@ -94,8 +94,9 @@ On `upgrade`, a pre-1.2.0 deployment with no block gets one (the agent asks, def
94
94
  ## Reserved names and channels
95
95
 
96
96
  Every name the kit bundles and writes over on an upgrade is the kit's, and an edit there is never a
97
- customization: the kit's scripts outside the spec layer and the hook installer set are written over
98
- by the next upgrade with no question and no copy kept. The spec layer's pair files are replaced on
97
+ customization: the kit's scripts outside the spec layer, the hook installer set and the kit rules
98
+ files `docs/ai/rules/<theme>.md` are written over by the next upgrade with no question and no copy
99
+ kept. The spec layer's pair files are replaced on
99
100
  the upgrade's one yes, the edit kept aside first. A declaration seeded once from a template and never
100
101
  replaced by the upgrade's ensures (a migration rewrites one only on the user's explicit yes) is the
101
102
  user's own file. A customization goes into one of five channels instead:
@@ -17,7 +17,7 @@ Run `node ${CLAUDE_SKILL_DIR}/tools/recommendations.mjs --cwd <project-root> [--
17
17
 
18
18
  1. **`--cwd` is REQUIRED** — the target project is explicit, never inferred from the shell's current directory (a subdirectory invocation still advises on the named root).
19
19
  2. **Verdict first (present-even-when-empty, opening at the `## Recommendations (agent-workflow)` header).** With everything optimal the body is exactly `no recommendations — flow optimal.` — the empty-state line ALONE is the verdict, zero added lines. Every other state opens the body with ONE verdict line composed from the frozen templates: `{K} item(s) need attention` leads when any item's severity is `attention` (a CONFIGURED declaration that is broken, drifted, degrading or invalid — the deployment needs review); `{N} optional recommendation(s), apply any you want` covers the `optional` class (offers to enable an unconfigured capability), led by `nothing is broken` ONLY when no item needs attention AND no probe check was skipped (a skipped probe could hide an attention-class problem — the claim never overreaches); `optimality NOT attested — {M} probe check(s) skipped` is appended last whenever probe checks were skipped. (The `(s)` invariant form IS the pinned pluralization — no singular/plural branching.) Items render attention-first, each tagged `needs attention:` / `optional:`. A failed probe renders as a stated `⚠ skipped item …` line — never a crash, never a fabricated item.
20
- 3. **The apply-through-agent lane — an explicit informed-consent checkpoint:** the agent applies chat and harness items on the chat yes, harness items by the consent route below. A chat item is never retried outside the sandbox and every failure of a chat step is a STOP. A user item is the user's own step, handed over as worded with its posture note (e.g. `source-size.id-squatter`). After presenting, OFFER to apply; the user selects items in plain language; for each selected item you **surface its posture note inline** where one exists (the per-item notes below cover exactly the risk-marked keys). For a chat item: the user **explicitly confirms**, and **only then** — **no command runs before confirmation** — do you run the rendered command. Do NOT infer safety from the presence or absence of an `--apply` flag: most chat items' rendered command IS the mutation and completes on that one run, **including a no-`--apply` mutation** such as `spec-adoption`'s `ensure-configs --reconcile --only specs` (behind an edited file it prints a replace line that takes its own yes). Some items instead render a **dry-run preview** that changes nothing and prints an explicit follow-up `--apply`/mutating command to run NEXT (e.g. the `gates-declaration` seeder): after the SAME confirmation you run that printed follow-up command — no second ask, no improvisation (each writer keeps its own consent semantics: previews, `--apply` flags, refusals) — except profile-gap and adr-store-migration, whose apply line runs with --apply (appended, or in place of --dry-run) only on a second yes over the relayed preview. For `worktrees-dir` you apply the grant on the chat yes after its check, like every harness item, with no hand step to wait for; its `recipe:` line's `ack-write` preview is the ack fallback, run only on the user's word that the host ignores the settings key, instead of the grant, and against a trusted host NO no ack renders.
20
+ 3. **The apply-through-agent lane — an explicit informed-consent checkpoint:** the agent applies chat and harness items on the chat yes, harness items by the consent route below. A chat item is never retried outside the sandbox and every failure of a chat step is a STOP. A user item is the user's own step, handed over as worded with its posture note (e.g. `source-size.id-squatter`). After presenting, OFFER to apply; the user selects items in plain language; for each selected item you **surface its posture note inline** where one exists (the per-item notes below cover exactly the risk-marked keys). For a chat item: the user **explicitly confirms**, and **only then** — **no command runs before confirmation** — do you run the rendered command. Do NOT infer safety from the presence or absence of an `--apply` flag: most chat items' rendered command IS the mutation and completes on that one run, **including a no-`--apply` mutation** such as `spec-adoption`'s `ensure-configs --reconcile --only specs` (behind an edited file it prints a replace line that takes its own yes). Some items instead render a **dry-run preview** that changes nothing and prints an explicit follow-up `--apply`/mutating command to run NEXT (e.g. the `gates-declaration` seeder): after the SAME confirmation you run that printed follow-up command — no second ask, no improvisation (each writer keeps its own consent semantics: previews, `--apply` flags, refusals) — except profile-gap, whose apply line runs with --apply appended only on a second yes over the relayed preview. For `worktrees-dir` you apply the grant on the chat yes after its check, like every harness item, with no hand step to wait for; its `recipe:` line's `ack-write` preview is the ack fallback, run only on the user's word that the host ignores the settings key, instead of the grant, and against a trusted host NO no ack renders.
21
21
  4. Registry strings (benefits + item texts) are frozen tool data, fact-true, ONE line under the pinned shape cap — posture/risk detail lives in the notes below at the consent moment, never inline in the overview. The dual velocity+security wording (`safer — blast radius bounded by the OS sandbox, not human attention`) rides ONLY the items with a real security delta (the autonomy render, the sandbox provisioning); the bridge-wrappers item claims **velocity only**.
22
22
 
23
23
  The **consent route** for a harness item: run its `check:` line in the sandbox and show its result. On the check's `masked:` line, say so and run that same check line once more outside the sandbox, so it re-judges in the apply's own environment; the yes is taken on the outside result. Take the user's yes on that result and run its `apply:` line with that result's digest once, outside the sandbox at once, so the harness asks at the point of action (with the apply ask rule seeded, its own dialog); never another line, never unseen. When velocity-core, kit-tools-tier or bridge-tier is among the user's picks (velocity-core preferred), check, confirm and apply it, or leave it pending, before any other pick's check runs, so its apply seeds the ask rule before the other harness applies. When the harness's auto mode refuses the check or the apply, say so and give the one plain step: leave auto mode for this one action (Shift+Tab in the terminal, the mode indicator in an editor) and say yes, or run `npx @sabaiway/agent-workflow-kit@latest init` in a terminal of your own. On the user's word, run the same line once more when they left auto mode, never another, never unseen; when they ran `init` instead, run the advisor again and offer only what is still pending, each through this route from its check (after a restart `init` asked for, the next session's upgrade does it). When that refusal hits the velocity-core, kit-tools-tier or bridge-tier pick taken first, run no other pick's check until the user answers the plain step. A check that refuses (exit 1) leaves the item unapplied and pending, its result shown; a changed digest (exit 5) applies nothing, shows the new result and asks a new yes. A no, a harness refusal and any other failure of a harness apply leave the item pending with its output shown, and the agent continues. `init`, run in a console from the project's folder, is the route the user may take instead.
@@ -47,7 +47,6 @@ A variant's posture note, where its key has one, is printed by `init` from this
47
47
  - `profile-gap` — each item's apply is a PREVIEW that writes nothing, and consent takes two steps: the confirmed pick runs the preview and you relay every line it prints (the environment-resolved slot values, each checker `entry:` line with its trust-chain disclosure, a Communication region the insert plans in the same run); the same line with ` --apply` appended runs only on a SECOND yes over those lines, never carried by the first. Items whose apply lines are byte-equal are one writer and take one answer: the tier preview's `--apply` writes the absent slots, the store seed and the queue seed together; the checker verb writes only its own entries; the insert writes every region it plans, all or nothing, so a `communication-absent` skip beside a declined `story-sessions-section` gets its own ask after the insert's full preview. A no records nothing and the item stays on the screen. A DECLINE is asked apart from later, before anything runs, and runs `node ${CLAUDE_SKILL_DIR}/tools/tier-preview.mjs --decline --cwd <project-root>` only when the user refuses EVERY item the tier preview then reports offered: it records each of them at the shipped lineage, and a declined item leaves the screen until a lineage step changes the profile. An undecidable entry is a stated skip naming its reason, the remedy by reason: a prior → the upgrade's `lens` reconcile; an absent region → the insert; a customized region → a hand edit only (the lens preserves it), so that skip stands and withholds `flow optimal`. Risk profile: the tier preview's `--apply` rewrites `docs/ai/orchestration.json` in canonical form with the `_README` note and creates `docs/ai/epics/.gitkeep` and `docs/plans/queue.md` create-only; the insert adds regions to `docs/ai/agent_rules.md`; the checker verb adds entries to the PRIVILEGED `docs/ai/gates.json`; the decline writes `docs/ai/profile-declines.json`; nothing here commits.
48
48
  - `jev-connect` — the lane is user and env-dependent: the connect command is the user's own step in a terminal of their own, where it asks for the key; the key never reaches the agent or the chat (the command refuses without a terminal, and a terminal is not consent). When the recipe line opens with `run the apply in <place>`, that place is the terminal to run it in; `init`, run there, offers the command on its own consent line. The command reads the key with no echo, makes one network call to api.typesafe.ai with the vendor's sample text only on the user's own run, and writes the key in plain text — as managed export lines in the shell's startup files (bash: ~/.bashrc and the login file, created as ~/.bash_profile when none exists; zsh: ~/.zshrc), as the kit's own file ~/.config/fish/conf.d/typesafe-api-key.fish for fish, or on Windows as the user environment variable TYPESAFE_API_KEY, stored in the Windows user environment; a process already running at the save can keep its old environment and hand it to what it starts — the guide's key mark confirms the agent sees it (a file is readable by any process running as that user, and by other local accounts when one is world-readable in a traversable home); the vendor keeps data under its processing agreement and offers zero retention only to enterprise accounts. The item reads the environment the agent's commands run in: a host setting that filters it shows the item while the key is set in the user's shell. The decline alternative rides the recipe line, asked apart BEFORE the confirmation (the `spec-adoption` order): on "connect" hand over the apply line; on "decline" the agent records it — the recipe line's preview, then its printed `--apply` — per project as `jevConnectAck` in `docs/ai/acks.json`. Risk profile: a plain-text key in the user's startup files or the Windows user environment, written by a command the user runs; one network call from that run.
49
49
  - `jev-skill` — the lane is harness; both `jev-skill` and `jev-skill.earlier` are env-dependent: the agent applies the item on the chat yes after the check, showing the files it would write; it changes no harness setting. `init` applies it on the batch terminal yes as the route the user may take instead. When the recipe line opens with `run the apply in <place>`, that place is where a user who prefers their own terminal runs it. The skill is third-party text — the vendor's, MIT — that the kit ships pinned and installs as a verified copy into three agent skill roots: `~/.agents/skills`, the Claude Code skills dir (`CLAUDE_CONFIG_DIR` or `~/.claude`) and `~/.gemini/config/skills`. It is never updated silently: a copy at an earlier pin is replaced only by that command, and a foreign copy is left untouched and named on the recipe line. A copy the vendor's `skills` CLI wrote with the same bytes reads current, and a later pin move replaces it like a kit copy; a vendor plugin install is invisible to the file check, so the Claude Code root may read absent while the plugin serves it. Only when the user asks to see the plan does the agent run the command without `--apply` (a read-only dry run). The decline alternative rides the recipe line, asked apart BEFORE the confirmation: on "install" run the check line and, on the yes given on its result, the apply line by the consent route; on "decline" the agent records it — the recipe line's preview, then its printed `--apply` — per project as `jevSkillAck` in `docs/ai/acks.json`. Risk profile: third-party text written into the user's agent skill roots by the kit's skill command; no network.
50
- - `adr-store-migration` — the crossing **overwrites and deletes files the project already has**: it replaces the deployed enforcement scripts in `scripts/` (the directional subset — only basenames the project already has; a locally-edited copy is snapshotted first, never silently clobbered) and, where a retired archive file exists, DELETES it once conservation has been proven. That is why the apply slot is a **`--dry-run`** — it writes nothing and prints the whole plan — and consent takes two steps: the first yes runs the dry run and you relay its whole plan (every line, the closing `--apply` line included); the same line with `--apply` in place of `--dry-run` runs only on a SECOND yes given over that plan. Every write is idempotent and the run is re-runnable to completion after any interruption, so a re-run repairs rather than double-applies. It never commits. Risk profile: overwrite + delete of existing project files, gated on a preview you have actually read.
51
50
 
52
51
  **Sandbox lanes (what to DO with the bridge surfaces, per host class):**
53
52
 
@@ -8,17 +8,16 @@ Requires: ${CLAUDE_SKILL_DIR}/references/shared/command-shapes.md
8
8
 
9
9
  **1. Start with the ensure.** Run `node ${CLAUDE_SKILL_DIR}/tools/ensure-configs.mjs --reconcile --only rules --cwd <project>` and relay its line in plain words. The effective file is built, never written by hand: this mode moves no edit out of it, and the ensure's rebuild or the next merge replaces one.
10
10
 
11
- **2. Do what the user asks — one of four.**
11
+ **2. Do what the user asks — one of three.**
12
12
 
13
13
  - **Change a rule.** The user says in plain words what to change. Show the exact text you will write to `docs/ai/rules/local/<theme>.md`, its frontmatter included, holding only the user's own rules and never a copy of the kit's, and write it on the user's yes. That request and that yes are the consent for the write of the local file.
14
- - **Move an edit of the kit file.** When an ensure line for the kit file says it `carries your edit`, whatever token the run printed (`pending` and `regenerated` included), offer the move: compare `docs/ai/rules/<theme>.md` with the bundled `${CLAUDE_SKILL_DIR}/references/rules/<theme>.md`, write the user's changes, by meaning, into the local file (shown first, written on the yes), then delete the kit file. The next ensure seeds it again from the template, so the kit file keeps its one writer.
15
14
  - **Drop the local rules.** On the user's request, delete the local file; the next ensure rebuilds the effective file from the kit file and records it.
16
15
  - **Change a number.** A request to change a number, a limit's value or its tolerance, is never written into a rules file: the rules are prose and carry no numbers; the kit keeps its numbers in its code, and a project's own number is a reasoned override in the size check's config. Show the exact `node ${CLAUDE_SKILL_DIR}/tools/source-size-check.mjs --override <id> [--value <n>] [--tolerance <p>] --reason "<text>" --cwd <project>` command, passing only the numbers the user named (an option left out keeps the limit's current value or tolerance; `files-per-root` takes `--tolerance` only), with `--kit-default` in their place to return to the kit's numbers; run it on the user's yes and relay its lines. This route ends there: it runs no ensure, merge, record or closing check.
17
16
 
18
- **3. After each of the three rules routes, run the ensure again.** On `pending`, do the merge its line states, show the user what changed in the final rules, then run the record command the line prints with the sha256 of the merged file (one plain command for the digest, per the shared command-shapes contract).
17
+ **3. After each of the two rules routes, run the ensure again.** On `pending`, do the merge its line states, show the user what changed in the final rules, then run the record command the line prints with the sha256 of the merged file (one plain command for the digest, per the shared command-shapes contract).
19
18
 
20
19
  **It stops on a refusal.** When an ensure run answers `failed`, the record command exits non-zero, or the `--override` command exits non-zero, relay the line and stop: write, delete and record nothing further, and run no closing check as if the change held.
21
20
 
22
21
  **4. End with the checks.** Run `node ${CLAUDE_SKILL_DIR}/tools/ensure-configs.mjs --reconcile --only index --cwd <project>`, then `node ${CLAUDE_SKILL_DIR}/tools/project-rules/rules-cli.mjs --check --cwd <project>`, which answers `current` for every theme; relay both in plain words.
23
22
 
24
- **What it never does.** It never writes the effective file except with the merge a `pending` line states, never changes the kit file's text (the move deletes the file whole and the ensure seeds it again), and never writes a local file without the user's request.
23
+ **What it never does.** It never writes the effective file except with the merge a `pending` line states, never changes the kit file's text, and never writes a local file without the user's request.
@@ -11,7 +11,7 @@ Run `node ${CLAUDE_SKILL_DIR}/tools/family-registry.mjs --json [--dir <project>]
11
11
  1. **Versions — a status-only render from `installed[]` + `deploymentHead`** (this is **NOT** the shared notes-based version block — see the separation note below): the **`docs/ai` structure version** (named as such, never "lineage head"), then each member by its `display` showing its `version` (or, when there is no version, the plain phrase for its `state`, mapped above), plus the two-axes disambiguation. **Freshness comes from `installed[].refresh`, not from `notes`:** for each member whose **`refresh.behind`** is `true`, show a **localized "needs refresh"** label and the **verbatim `refresh.recommend`** command **exactly once** (the command/package name stays source-language; **do not also paste the English `notes` caveats** — `refresh.recommend` is the single source of the recovery step, so the command is never duplicated on this surface). A member whose **`refresh.freshness`** is **`unknown`** is surfaced too — a localized *"couldn't be checked"* label; it is **never counted as current and never as behind** (its `notes` caveat carries the detail on the notes-based surfaces; here the label is enough). Lead with a one-line **headline count** derived from `installed[].state` + `refresh.behind` + `refresh.freshness` (e.g. *"5 members installed · 1 needs a refresh · 1 couldn't be checked"* — omit a zero count).
12
12
 
13
13
  > **Status reads `refresh`; the shared version block + the bootstrap/upgrade footers stay `notes`-based (unchanged this release).** `${CLAUDE_SKILL_DIR}/references/modes/status.md` has its OWN status-only render (above), keyed on `installed[].refresh.behind` / `refresh.recommend`. The shared **version block** (under *The version block + welcome mat* in `${CLAUDE_SKILL_DIR}/references/shared/report-footer.md`) and the bootstrap (step 11) + every upgrade (steps 4 / 8) report footer still consume `installed[].notes` verbatim — that wiring is deliberately **untouched** here (their migration onto `refresh` is deferred). Do not rewrite those footers onto `refresh`.
14
- 2. **Deployment (`--dir`)** (from `project`): whether `docs/ai/` is deployed + the deploy stamps by `display`; and **visibility** — render `project.visibility.state` in **user-safe words only**: *visible (tracked)* / *hidden (git-ignored, local-only)* / *unclear (uncommitted or partially set up)* — **never** the words "hidden fence" or any marker term. A `visibility.error` → surface it plainly. When `project.adrLayout` is **`old`** or **`old-unrotated`**, add a plain-language note that the project still uses an **older ADR layout** and should run the opt-in **`/agent-workflow-kit migrate-adr-store`** to move to the one-file-per-ADR store (preview first; it never commits) — the note is the SAME for both, they differ only in how the older layout was detected (`old` = a retired archive file is still on disk; `old-unrotated` = the project's deployed rotation script predates the store); `migrated` / `none` need no note. Then **one `specs` line, always** (from `project.specs` — the feature-spec layer's adoption state, judged from the store alone): `not adopted` (no `docs/ai/specs/` — the layer was never seeded), `adopting (N draft)` (a store with no live contract yet), `adopted (N live, M draft)`, or `could not be read — <reason>` (the store or a document in it could not be observed; never counted as any of the other three). A recorded decline (`project.specs.declined`) appends ` — declined` to the first two. The internal tokens are `not-adopted` / `adopting` / `adopted` / `unreadable`; render the plain phrases above, never the tokens. An envelope without the field says the installed kit predates it — say so rather than inventing a state.
14
+ 2. **Deployment (`--dir`)** (from `project`): whether `docs/ai/` is deployed + the deploy stamps by `display`; and **visibility** — render `project.visibility.state` in **user-safe words only**: *visible (tracked)* / *hidden (git-ignored, local-only)* / *unclear (uncommitted or partially set up)* — **never** the words "hidden fence" or any marker term. A `visibility.error` → surface it plainly. When `project.adrLayout` is **`old`** or **`old-unrotated`**, add a plain-language note that the project still uses an **older ADR layout**, with the line's own text: /agent-workflow-kit upgrade moves it where scripts/ holds the kit's decisions rotator, or prints the rotator's refusal. The note is the SAME for both, they differ only in how the older layout was detected (`old` = a retired archive file is still on disk; `old-unrotated` = the project's deployed rotation script predates the store); `migrated` / `none` need no note. Then **one `specs` line, always** (from `project.specs` — the feature-spec layer's adoption state, judged from the store alone): `not adopted` (no `docs/ai/specs/` — the layer was never seeded), `adopting (N draft)` (a store with no live contract yet), `adopted (N live, M draft)`, or `could not be read — <reason>` (the store or a document in it could not be observed; never counted as any of the other three). A recorded decline (`project.specs.declined`) appends ` — declined` to the first two. The internal tokens are `not-adopted` / `adopting` / `adopted` / `unreadable`; render the plain phrases above, never the tokens. An envelope without the field says the installed kit predates it — say so rather than inventing a state.
15
15
  3. **Settings (`--dir`, one line each)** (from `project.settings`):
16
16
  - **recipes** — the effective recipe per slot, **one line per slot** over the six activities (`plan-authoring.author` / `.fold` / `.review`, `plan-execution.execute` / `.review`, `routine.carrier` / `.parallel`, `feedback-triage.review`, `epic.author` / `.review`, `task.author` / `.execute`); each line also carries **where the value came from** (`source` — the project's config, an explicit override, or a computed default) and, when the resolved recipe is not the one that was asked for, **what it degraded from** (`degradedFrom`). Say both in plain words (never the field names): an effective recipe alone cannot tell a deliberate choice from a default, nor a degrade from a config that really names the resolved recipe — and a slot showing `solo` after a degrade from `subagent` is exactly the case the **subagents** line below explains. Detail → `/agent-workflow-kit procedures` / `recipes`; a `recipes.detectError` → say the backends couldn't be checked, so bridge-backed recipes floored at solo; the executor vehicle is unaffected.
17
17
  - **attribution** — `includeCoAuthoredBy` effective; call out a **local override** only when `local` is non-null **and** differs from `project` (a `null` `local` means the key is absent there, so the project value stands — that is not an override).
@@ -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, and the scripts op's store run moves ADR entries, rewrites their inbound links in `docs/ai` pages and regenerates the index, as the rotator does — 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` / `not-placed` / `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-store-not-current`, `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, and the scripts op's store run moves ADR entries, rewrites their inbound links in `docs/ai` pages and regenerates the index, as the rotator does — 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` / `not-placed` / `skipped-no-node-evidence`; specs → `seeded` / `refreshed` / `already-present` / `customized-preserved` / `skipped-no-node-evidence`; rules → `seeded` / `refreshed` / `regenerated` / `pending` / `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-store-not-current`, `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
 
@@ -49,7 +49,7 @@ Requires: ${CLAUDE_SKILL_DIR}/references/shared/report-footer.md · ${CLAUDE_SKI
49
49
 
50
50
  **What the spec-layer ensure does.** A deployment older than the feature-spec layer lacks `scripts/spec-schema.mjs` and `docs/ai/specs/index.md`, and its deployed `check-docs-size.mjs` predates the store collapse. In ONE order: the reader pair, then the checker pair — each seeded when absent and REFRESHED only while a file's bytes are a body a release shipped (an append-only digest catalog → `refreshed`; an edited body is preserved verbatim and withholds the writes that depend on it, the checker lane waiting on a byte-current reader pair); the store root is seeded from the bundled template, date rendered, ONLY behind a checker pair current after the run — an older or edited checker renders the store row by row and reds the hook's `--check-index`; edited files are kept aside and replaced on row 3's yes. One token by precedence: `seeded` > `refreshed` > `customized-preserved` (an edited pair, and this run wrote nothing) > `already-present`; `skipped-no-node-evidence` only when neither a root `package.json` nor any kit-seeded `scripts/*.mjs` is present (the same Node-evidence probe the enforcement-script ensure uses; an unreadable probe is `failed` / `node-evidence-unverifiable`). **The adoption state this seed leaves behind is reported, never assumed:** the Recommendations section (step 4 / 8) carries the `spec-adoption` item — `not adopted` (the store is absent: the seed offered, the decline the agent records), `adopting` (a store with no live contract: the decline offered), silenced by a recorded decline (`ack-write --lane spec-adoption`), and a store the probe cannot read is a stated skip — and `status` prints the same state on its own line.
51
51
 
52
- **What the project-rules ensure does.** Each theme's kit file `docs/ai/rules/<theme>.md` is seeded, refreshed only from a body a release shipped (an edit is kept, its line saying it carries your edit), and with no local file its effective copy and record are rebuilt. With a local file it writes neither: `pending` prints the merge to do and its record command — do the merge, show the user what changed, then run that command. A kit-file line saying it carries your edit, whatever the run's token, is offered `/agent-workflow-kit rules` to move the edit into the local file.
52
+ **What the project-rules ensure does.** Each theme's kit file `docs/ai/rules/<theme>.md` is seeded, refreshed from a body a release shipped, and any other body replaced by the template with no question and no copy kept, its line naming the local rules file `docs/ai/rules/local/<theme>.md` for a rule meant to last; with no local file its effective copy and record are rebuilt. With a local file it writes neither: `pending` prints the merge to do and its record command — do the merge, show the user what changed, then run that command.
53
53
 
54
54
  **`gates-migration` — legacy gates.json migration (consented preview — D8).** An EXISTING declaration may still carry the retired review-ledger / fold-completeness checks. Run the preview (dry-run — writes NOTHING), show the user the exact plan, and only on an explicit yes re-run it with `--apply`: canonical legacy entries (matched by their documented single-invocation cmd forms) are REMOVED, the canonical `unit-tests` cmd gains the built-in lcov reporters, and the coverage-check gate is ADDED last — atomic and COMPLETE, so the migrated declaration satisfies `run-gates --final`. **The checker rides a PRODUCER or is not declared at all** (`${CLAUDE_SKILL_DIR}/references/modes/gates.md`): with no gate producing the lcov it reads, the migration does NOT add it, an already-declared one is reported INERT, the result is not called final-run-capable, and the preview prints the paste-ready suite cmd to declare by hand — nothing is ever removed for you. CUSTOMIZED entries are NEVER auto-touched: the preview names each with a paste-ready recovery, and the commit guard must NOT be installed until they are resolved. Of step 3's run-list, only this migration and `tools/checker-gates.mjs` under the `tier` ask change an existing gates.json (the FILL preview runs at init).
55
55
 
@@ -70,13 +70,6 @@ const CATALOG = [
70
70
  kind: GUARDED,
71
71
  oneLine: 'Remove only what setup placed; it never deletes your notes and always previews before changing anything.',
72
72
  },
73
- {
74
- key: 'migrate-adr-store',
75
- invocation: invocationOf('migrate-adr-store'),
76
- group: 'Lifecycle',
77
- kind: GUARDED,
78
- oneLine: 'Migrate an older project’s ADR store to the one-file-per-ADR layout; it previews first, snapshots, and never commits.',
79
- },
80
73
  {
81
74
  key: 'status',
82
75
  invocation: invocationOf('status'),
@@ -350,7 +343,7 @@ export const kindOf = (key) => byKey.get(key)?.kind ?? null;
350
343
  // undefined / null / '' / whitespace-only / the exact bare invocation → 'bootstrap'
351
344
  // a known first token (any non-bootstrap catalog key — upgrade/status/setup/backends/recipes/
352
345
  // procedures/velocity/agents/hook/gates/set-recipe/set-flow/flow-writer/uninstall/
353
- // migrate-adr-store/help/…) → that mode
346
+ // help/…) → that mode
354
347
  // anything else (unrecognized / ambiguous) → 'help' (read-only — NEVER a writer/guarded mode)
355
348
  export const routeInvocation = (token) => {
356
349
  if (token == null) return BARE_INVOCATION_MODE;
@@ -144,7 +144,7 @@ const runStore = (cwd, deps) => {
144
144
  const r = (deps.spawnSync ?? spawnSync)(process.execPath, [join(cwd, SCRIPTS_DIR, ROTATOR), '--ensure-current'], { cwd, encoding: 'utf8' });
145
145
  const [out, err] = [outputLines(r.stdout), outputLines(r.stderr)];
146
146
  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;
147
- if (ended) return { failure: `${ENSURE} ${ended} — the ADR store is not current`, lines: [...err, ...out].map((line) => STORE + line) };
147
+ if (ended) return { failure: `${ENSURE} ${ended} — the ADR store was not confirmed current`, lines: [...err, ...out].map((line) => STORE + line) };
148
148
  const brought = (out.at(-1) ?? '').startsWith('brought-current:');
149
149
  return { brought, lines: [...(brought ? out : []), ...err].map((line) => STORE + line) };
150
150
  };
@@ -13,9 +13,10 @@
13
13
  // specs scripts/<spec layer> reader + checker pairs seeded when absent, refreshed only on
14
14
  // + docs/ai/specs/index.md a shipped prior body, an edited one replaced only on the
15
15
  // user's yes; store root seeded behind a current checker
16
- // rules docs/ai/rules/<theme>.md the kit file seeded, or refreshed on a shipped prior body; with
17
- // + effective/ + sources.json no local file the effective copy and its record rebuilt; with
18
- // one the merge an agent does is named, never done
16
+ // rules docs/ai/rules/<theme>.md the kit file seeded, refreshed on a shipped prior body, or any
17
+ // + effective/ + sources.json other body replaced, with no question and no copy kept; with no
18
+ // local file the effective copy and its record rebuilt; with one
19
+ // the merge an agent does is named, never done
19
20
  // index docs/ai/index.md regenerate-if-missing-or-stale (a GENERATED artifact); under
20
21
  // a project hook module that is not the bundled one, a write
21
22
  // the project's own checker rejects is put back
@@ -99,8 +100,9 @@ matches a canonical the kit shipped (your own wording is preserved verbatim); th
99
100
  and checker pairs, only while a file's bytes are a body a release shipped (an edited file is
100
101
  preserved, the writes that depend on it — the spec store root included — are withheld behind it,
101
102
  and ONE printed replace block keeps every edit aside and replaces it only on the user's yes); the project rules
102
- kit file, only while its bytes are a body a release shipped (an edited one is kept), with the effective
103
- file rebuilt as its copy and recorded where no local file exists; and the navigator index — a GENERATED artifact, regenerated
103
+ kit file, refreshed while its bytes are a body a release shipped and any other body replaced by the template,
104
+ with no question and no copy kept, the effective file rebuilt as its copy and recorded where no local file
105
+ exists; and the navigator index — a GENERATED artifact, regenerated
104
106
  whenever it is missing or stale; where a module the project's hook loads is not the bundled one,
105
107
  the project's own checker judges the navigator and a write it rejects is put back byte for byte.
106
108
  The executor ensure writes nothing: a placed .claude/agents/executor.md whose bytes differ from the
@@ -343,9 +343,9 @@ const hasHiddenFence = (projectDir, deps = {}) => {
343
343
  }
344
344
  };
345
345
 
346
- // The retired 3-tier ADR monoliths (AD-051): their presence is the old-layout signal a consumer must
347
- // migrate away from via the opt-in `migrate-adr-store` mode. Stable relative paths (a status probe
348
- // never imports the rotator).
346
+ // The retired 3-tier ADR monoliths (AD-051): their presence is the old-layout signal the status
347
+ // view reports; the upgrade's run of the kit's rotator moves it. Stable relative paths (a status
348
+ // probe never imports the rotator).
349
349
  // The ADR-layout probe's paths. LOCAL literals, not an import: this module backs the read-only
350
350
  // `status` view and importing the rotator would drag child_process + crypto into a status read. A
351
351
  // drift guard in family-registry.test.mjs pins each literal to the rotator's exported constant —
@@ -362,14 +362,13 @@ export const ADR_LAYOUT_PATHS = Object.freeze({
362
362
  });
363
363
  const ENOENT = 'ENOENT';
364
364
 
365
- // The ADR-store layout axis: 'old' (a retired decisions-archive monolith is still on disk — needs
366
- // the opt-in migration), 'migrated' (the one-file-per-ADR adr/ store is in place), or 'none' (no ADR
367
- // substrate at all). Keys on the monolith presence, NOT on the stamp/head (Decision 6/13).
365
+ // The ADR-store layout axis: 'old' (a retired decisions-archive monolith is on disk), 'migrated' (the
366
+ // adr/ store is in place) or 'none' (no ADR substrate); keyed on the monolith, NOT the stamp (Decision 6/13).
368
367
  // The STRICT core. Absence is ENOENT and nothing else: existsSync collapses EVERY failure to false
369
368
  // (EACCES included), so a strict policy layered on it would be vacuous in production and observable
370
369
  // only through injected deps — and ENOTDIR means a file where a directory belongs, i.e. corruption,
371
- // not "not there". Everything else propagates, so the advisor can degrade to a STATED SKIP instead
372
- // of printing "flow optimal" over a layout it could not read.
370
+ // not "not there". Everything else propagates, so a strict caller can state the failure instead of
371
+ // reading an absence over a layout it could not read.
373
372
  export const PATH_DIR = 'dir';
374
373
  export const PATH_FILE = 'file';
375
374
  export const PATH_OTHER = 'other';
@@ -422,7 +421,7 @@ export const surveyAdrLayoutStrict = (dir, deps = {}) => {
422
421
  };
423
422
 
424
423
  // The LENIENT wrapper — the read-only status view must never crash, so any failure reads `none`.
425
- // One implementation, two stated policies; the advisor uses the strict core deliberately.
424
+ // One implementation, two stated policies.
426
425
  const surveyAdrLayout = (dir, deps) => {
427
426
  try {
428
427
  return surveyAdrLayoutStrict(dir, deps);
@@ -7,7 +7,6 @@ import { join } from 'node:path';
7
7
  import { writeDocsAiFileAtomic, writeProjectFileCreateOnly } from '../atomic-write.mjs';
8
8
  import { composeFailure, composeOutcome, tmpNote } from '../ensure-ops.mjs';
9
9
  import { shellQuoteArg } from '../repo-lex.mjs';
10
- import { parseFrontmatter } from '../../references/scripts/check-docs-size.mjs';
11
10
  import { digestOf, readRecord, readUnder } from './rules-check.mjs';
12
11
  import { writeRecord } from './rules-record.mjs';
13
12
  import { RULES_PRIORS, isKnownPrior } from './rules-priors.mjs';
@@ -58,24 +57,22 @@ const survey = ({ themes, cwd, kitRoot, readFile, deps }) => {
58
57
  const classifyKit = (name, kit, template, priors) => {
59
58
  if (kit.outcome === 'absent') return 'absent';
60
59
  if (kit.bytes.equals(template)) return 'current';
61
- return isKnownPrior(name, kit.bytes, priors) ? 'prior' : 'custom';
60
+ return isKnownPrior(name, kit.bytes, priors) ? 'prior' : 'other';
62
61
  };
63
62
 
64
63
  const planTheme = ({ theme, paths, template, reads }, record, priors) => {
65
64
  const { kit, local, effective } = reads;
66
65
  const kitState = classifyKit(theme.name, kit, template, priors);
67
- const kitBytes = kitState === 'absent' || kitState === 'prior' ? template : kit.bytes;
68
- const kitWrite = { absent: 'seed', prior: 'refresh' }[kitState] ?? null;
66
+ const kitWrite = { absent: 'seed', prior: 'refresh', other: 'refresh' }[kitState] ?? null;
69
67
  const entry = record.ok ? record.themes[theme.name] : undefined;
70
- const base = { name: theme.name, paths, kitState, kitBytes, kitWrite, effectiveWrite: null, recordWrite: false };
68
+ const base = { name: theme.name, paths, kitState, kitBytes: template, kitWrite, effectiveWrite: null, recordWrite: false };
71
69
  if (local.outcome === 'ok') {
72
- const merged = entry !== undefined && effective.outcome === 'ok' && entry.kit === digestOf(kitBytes)
70
+ const merged = entry !== undefined && effective.outcome === 'ok' && entry.kit === digestOf(template)
73
71
  && entry.local === digestOf(local.bytes) && entry.effective === digestOf(effective.bytes);
74
72
  return { ...base, mode: merged ? 'merged' : 'pending', localDigest: digestOf(local.bytes) };
75
73
  }
76
- if (kitState === 'custom' && parseFrontmatter(kitBytes.toString('utf8')) === null) return { ...base, mode: 'unvouched' };
77
- const effectiveWrite = effective.outcome === 'absent' ? 'seed' : effective.bytes.equals(kitBytes) ? null : 'rebuild';
78
- const passed = { kit: digestOf(kitBytes), local: 'absent', effective: digestOf(kitBytes) };
74
+ const effectiveWrite = effective.outcome === 'absent' ? 'seed' : effective.bytes.equals(template) ? null : 'rebuild';
75
+ const passed = { kit: digestOf(template), local: 'absent', effective: digestOf(template) };
79
76
  const recorded = entry !== undefined && entry.kit === passed.kit && entry.local === 'absent' && entry.effective === passed.effective;
80
77
  const droppedEdit = effectiveWrite === 'rebuild' && entry !== undefined && entry.effective !== digestOf(effective.bytes);
81
78
  return { ...base, mode: 'copy', effectiveWrite, recordWrite: effectiveWrite !== null || !recorded, passed, droppedEdit };
@@ -86,13 +83,13 @@ const planTheme = ({ theme, paths, template, reads }, record, priors) => {
86
83
  const KIT_LINES = {
87
84
  absent: { written: 'created from the bundled template', stood: 'appeared while this run was creating it and holds the bundled template — it stands', would: 'absent — would be created from the bundled template' },
88
85
  prior: { written: 'held the body an earlier release shipped — refreshed to the bundled template', would: 'holds the body an earlier release shipped — would be refreshed to the bundled template' },
86
+ other: { written: 'differs from every body this kit knows it shipped — replaced by the bundled template', would: 'differs from every body this kit knows it shipped — would be replaced by the bundled template' },
89
87
  };
90
88
  const kitLine = (plan, fate) => {
91
89
  const { kit, local } = plan.paths;
92
90
  if (plan.kitState === 'current') return `${kit}: already the bundled template — nothing written`;
93
- if (plan.mode === 'unvouched') return `${kit}: carries your edit with no frontmatter — kept byte for byte, and nothing else was written for this theme, because the record writer cannot vouch for a file without frontmatter; your own rules belong in ${local}, where they win`;
94
- if (plan.kitState === 'custom') return `${kit}: carries your edit — kept byte for byte; your own rules belong in ${local}, where they win, and the kit's updates to this file wait while it carries the edit`;
95
- return `${kit}: ${KIT_LINES[plan.kitState][fate]}`;
91
+ const lasting = plan.kitState === 'other' ? `; a rule meant to last goes in ${local}, where it wins` : '';
92
+ return `${kit}: ${KIT_LINES[plan.kitState][fate]}${lasting}`;
96
93
  };
97
94
 
98
95
  const effectiveLine = (plan, fate) => {
@@ -141,7 +138,7 @@ const tokenOf = (plans, wrote, dryRun) => {
141
138
  if (plans.some((plan) => plan.kitWrite === 'seed' && wrote(plan, 'kit'))) return token('seeded');
142
139
  if (plans.some((plan) => plan.kitWrite === 'refresh' && wrote(plan, 'kit'))) return token('refreshed');
143
140
  if (plans.some((plan) => wrote(plan, 'effective') || wrote(plan, 'record'))) return token('regenerated');
144
- return plans.some((plan) => plan.kitState === 'custom') ? 'customized-preserved' : 'already-current';
141
+ return 'already-current';
145
142
  };
146
143
 
147
144
  // ── the writes, in order; the first that fails stops the run ─────────────────────────────────────
@@ -51,7 +51,7 @@ import { STATE_BLOCK_HOOK_COMMAND, STATE_BLOCK_HOOK_RUNTIME, isStopHookWired } f
51
51
  import { detectBackends } from './detect-backends.mjs';
52
52
  import { isDirectRun } from './direct-run.mjs';
53
53
  import { ACTIVITIES, resolveActivityRecipe, composeReadiness, safeLine } from './recipes.mjs';
54
- import { surveyFamily, surveyGateHook, surveyAdrLayoutStrict } from './family-registry.mjs';
54
+ import { surveyFamily, surveyGateHook } from './family-registry.mjs';
55
55
  import { probeSandboxMasks, needsMasksApply, patternToRel } from './sandbox-masks.mjs';
56
56
  import { shellQuoteArg } from './review-state.mjs';
57
57
  import { isFinalCapableDeclaration } from './run-gates.mjs';
@@ -219,7 +219,6 @@ export const SEVERITIES = Object.freeze({
219
219
  attribution: SEVERITY_ATTENTION,
220
220
  'footprint-global': SEVERITY_OPTIONAL,
221
221
  'family-freshness': SEVERITY_ATTENTION,
222
- 'adr-store-migration': SEVERITY_ATTENTION,
223
222
  'sandbox-masks': SEVERITY_OPTIONAL,
224
223
  'sandbox-masks.unfenced-mount': SEVERITY_ATTENTION,
225
224
  'worktrees-dir': SEVERITY_OPTIONAL,
@@ -312,7 +311,6 @@ export const WHATS = Object.freeze({
312
311
  attribution: 'AGENTS.md says attribution off but .claude/settings.json does not hide the harness trailer and PR text',
313
312
  'footprint-global': 'legacy kit ignore line(s) sit in {file} — they ignore kit paths in every repository here',
314
313
  'family-freshness': '{parts}',
315
- 'adr-store-migration': 'still on the retired 3-tier ADR layout — {shape}',
316
314
  'sandbox-masks': '{n} sandbox mask(s) clutter git status — the managed exclude block is absent or stale',
317
315
  'sandbox-masks.stale-real': '{n} sandbox mask(s) clutter git status — the exclude block is stale; {m} fenced entr(ies) are REAL paths (a fresh apply drops them)',
318
316
  'worktrees-dir': 'write access to the worktrees parent dir {dir} is not confirmed — provision may still stop',
@@ -380,7 +378,6 @@ export const BENEFITS = Object.freeze({
380
378
  attribution: 'attribution — the harness adds no Co-Authored-By trailer, PR text or session link, as your AGENTS.md block requires',
381
379
  'footprint-global': 'hygiene — the legacy machine-global excludes stop ignoring kit paths in every other repository on this host',
382
380
  'family-freshness': 'currency — placed family members carry the latest shipped fixes and features',
383
- 'adr-store-migration': 'durability — every decision becomes its own file with a generated navigator, instead of one hand-rotated pile',
384
381
  'sandbox-masks': 'zero clutter — a mask git ignores through the block leaves git status; a mount-only one leaves git add -A and the review fingerprint too',
385
382
  'worktrees-dir': 'parallel features — the host-specific write allowance or terminal fallback is surfaced before provision',
386
383
  'spec-adoption': 'contracts — a plan names the contract it builds to, and a change to a governed slice is visible at review instead of after it',
@@ -443,7 +440,6 @@ export const OPT_IN_CAPABILITIES = Object.freeze([
443
440
  { id: 'full-flow-profile', mode: 'upgrade', advisorKey: 'profile-gap' },
444
441
  { id: 'jev-connect', mode: 'jev', advisorKey: 'jev-connect' },
445
442
  { id: 'jev-skill', mode: 'jev', advisorKey: 'jev-skill' },
446
- { id: 'adr-store-migration', mode: 'migrate-adr-store', advisorKey: 'adr-store-migration' },
447
443
  { id: 'review-recipe', mode: 'set-recipe', advisorKey: 'review-recipe' },
448
444
  // The execute slot is a DISTINCT opt-in from the review slot, and the same probe reports both —
449
445
  // which is why the review-recipe benefit is worded for either slot rather than for review alone.
@@ -1412,7 +1408,7 @@ const readReadLaneToggle = (root, deps) => {
1412
1408
  // D3: the risk-marked keys — every key here has a per-item posture note in the mode doc, surfaced
1413
1409
  // at the consent moment; the static contract test asserts EXACT bidirectional coverage
1414
1410
  // (risk-marked keys == mode-doc note keys — a dropped note goes red, not silent).
1415
- export const RISK_NOTED_KEYS = Object.freeze(['bridge-tier', 'read-lane', 'worktrees-dir', 'adr-store-migration', 'gates-inert', 'source-size', 'gate-hook', 'mcp-channel', 'spec-adoption', 'enforcement', 'hook-checks', 'profile-gap', 'jev-connect', 'jev-skill', 'attribution', 'footprint-global']);
1411
+ export const RISK_NOTED_KEYS = Object.freeze(['bridge-tier', 'read-lane', 'worktrees-dir', 'gates-inert', 'source-size', 'gate-hook', 'mcp-channel', 'spec-adoption', 'enforcement', 'hook-checks', 'profile-gap', 'jev-connect', 'jev-skill', 'attribution', 'footprint-global']);
1416
1412
 
1417
1413
  // The feature-spec layer's adoption state (contract: kit/spec-adoption). The canon lets a plan cite
1418
1414
  // zero governing specs while a project adopts the layer, and nothing ever said whether adoption had
@@ -1536,39 +1532,6 @@ const probeWorktreesDir = ({ root, deps, add, skip }) => {
1536
1532
  }
1537
1533
  };
1538
1534
 
1539
- // The ADR-store crossing. Until now this mode declared it had NO advisor capability, on the argument
1540
- // that status and upgrade already report the old layout — but they only reported the MONOLITH shape,
1541
- // so a project whose deployed rotator merely predates the store was told nothing by anything.
1542
- //
1543
- // Honest scope: the advisor is the deterministic section every `upgrade` run ends with, so this is
1544
- // NOT a new door for someone who never runs status or upgrade — it MECHANIZES the upgrade door.
1545
- //
1546
- // It reads the STRICT layout survey deliberately: the lenient one turns every fs failure into
1547
- // "no ADR layout here", which would print «flow optimal» over a layout the probe could not read. A
1548
- // failure must become a STATED SKIP, never an absence.
1549
- // Each shape states a fact about THIS tree that holds whether or not a store directory exists —
1550
- // `old-unrotated` also covers a tree whose store is already there but whose rotation script is not,
1551
- // and saying "the store is not in place" there would be false.
1552
- const ADR_LAYOUT_SHAPES = Object.freeze({
1553
- old: 'a legacy archive file is still on disk and must be exploded into the per-file store',
1554
- 'old-unrotated': 'the deployed rotation script predates the store and keeps writing the retired layout',
1555
- });
1556
- export const probeAdrStore = ({ root, deps, add, skip }) => {
1557
- try {
1558
- const shape = ADR_LAYOUT_SHAPES[surveyAdrLayoutStrict(root, deps)];
1559
- if (!shape) return; // migrated, or no ADR substrate at all — nothing to offer
1560
- // The apply is the bare dry run: consent takes two steps, as profile-gap's does — the first yes
1561
- // runs it and the plan is relayed, the same line with --apply runs only on a second yes over it.
1562
- add(
1563
- 'adr-store-migration',
1564
- fillTemplate(WHATS['adr-store-migration'], { shape }),
1565
- `node ${q(toolPath('migrate-adr-store.mjs'))} --dry-run --cwd ${q(root)}`,
1566
- );
1567
- } catch (err) {
1568
- skip('adr-store-migration', err);
1569
- }
1570
- };
1571
-
1572
1535
  // The typed-channel item. It asks the READ-ONLY registration leaf and nothing else — importing the
1573
1536
  // writer would pull the atomic-write core into the advisor's graph (read-graph-purity.test.mjs).
1574
1537
  const probeMcpChannel = ({ root, deps, add, skip }) => {
@@ -1719,7 +1682,6 @@ const PROBES = Object.freeze([
1719
1682
  probeCheapAgents,
1720
1683
  probeExecutorVehicle,
1721
1684
  probeFamilyFreshness,
1722
- probeAdrStore,
1723
1685
  probeMasksItem,
1724
1686
  probeFootprintGlobal,
1725
1687
  probeWorktreesDir,
@@ -99,7 +99,7 @@ const renderProject = (vm, { color }) => {
99
99
  // actionable tokens render the SAME line: 'old' (a monolith on disk) and 'old-unrotated' (an
100
100
  // old-scheme rotator that never rotated) differ only in the discriminator, never in the remedy.
101
101
  if (ACTIONABLE_ADR_LAYOUTS.includes(p.adrLayout)) {
102
- lines.push(` ${pad('ADR store', STAMP_COL)}old layout — run /agent-workflow-kit migrate-adr-store`);
102
+ lines.push(` ${pad('ADR store', STAMP_COL)}old layout — /agent-workflow-kit upgrade moves it where scripts/ holds the kit's decisions rotator, or prints the rotator's refusal`);
103
103
  }
104
104
  // Every state renders — an owner opens this surface deliberately, so "not adopted" is the one line
105
105
  // that must never be missing; an envelope without the field says so rather than inventing a state.
@@ -50,7 +50,6 @@ export const VARIANT_LANES = Object.freeze({
50
50
  attribution: LANE_HARNESS,
51
51
  'footprint-global': LANE_HARNESS,
52
52
  'family-freshness': LANE_USER,
53
- 'adr-store-migration': LANE_CHAT,
54
53
  'sandbox-masks': LANE_CHAT,
55
54
  'sandbox-masks.unfenced-mount': LANE_CHAT,
56
55
  'worktrees-dir': LANE_HARNESS,
@@ -1,21 +0,0 @@
1
- ### Mode: migrate-adr-store
2
-
3
- <!-- opt-in-capability: adr-store-migration -->
4
-
5
- The **guarded ADR-store migration** — a one-time, opt-in move of an existing project's `docs/ai` from the retired 3-tier ADR cascade (HOT `decisions.md` → the WARM/COLD `decisions-archive*.md` monoliths) to the durable **one-file-per-ADR store** (HOT `decisions.md` + `docs/ai/adr/AD-NNN-slug.md` records + the `docs/ai/adr/log.md` navigator). **In-agent, opt-in**: the upgrade moves an older layout itself wherever `scripts/` holds the kit's rotator, so after a full upgrade this mode does nothing; it stays for a project whose `scripts/` holds no kit script. Run **`--dry-run` first, always**, show the user the plan in plain language, get explicit consent, then re-run with `--apply`. It **never commits**.
6
-
7
- When to run it: `status` reports an *old ADR layout*. That covers **two** shapes, and the remedy is the same for both — (1) a `decisions-archive*.md` monolith is still on disk, and (2) **no monolith was ever produced**: the project's deployed `scripts/archive-decisions.mjs` simply predates the store, so its own gate reports the retired three-tier world as healthy and would never mention the store. The second shape is detected by that deployed script's own provenance — never by "has `decisions.md`, lacks `adr/`", which would falsely accuse a project whose NEW rotator already reds its gate with an actionable fix, and every project that runs no Node. A project already on the one-file-per-ADR store with a fresh navigator — or a fresh deployment seeded with it — needs nothing here (the mode is a stated no-op).
8
-
9
- On the no-monolith shape `--apply` does the same work minus the explosion: snapshot → refresh the deployed enforcement scripts → **seed** the store (`docs/ai/adr/` + the navigator + a regenerated `docs/ai/index.md`) → verify. It is **re-runnable to completion from any interruption**: a store directory alone never counts as finished (the navigator must exist and the project's own `--check` must pass), the whole script refresh is re-planned on every run with the rotation script written last, and a failed index regeneration fails the run **closed** rather than reporting success.
10
-
11
- Run `node ${CLAUDE_SKILL_DIR}/tools/migrate-adr-store.mjs [--dry-run | --apply] [--cwd <project>]`:
12
-
13
- - **`--dry-run`** (default) — prints the plan and writes NOTHING: the monoliths to be exploded + retired, the pre-migration snapshot location, which deployed enforcement scripts will be refreshed (naming any that differ locally), and the rotator's conservation proof (every archived ADR accounted for).
14
- - **`--apply`** — performs it in order: (1) write a durable pre-migration **snapshot** (`decisions.md` + both monoliths + the pre-refresh `scripts/` copies) to the project's git dir (uncommittable), with a stated out-of-tree fallback off git — fail loud if neither base is writable; (2) **force-refresh** the deployed enforcement scripts (the directional subset — only kit-canon basenames the project already has) so the project's own gates run the new rotator + collapse rule; (3) run the conservation-checked **rotation** that explodes the monoliths into `adr/` records, retires them, and regenerates the navigator + `docs/ai/index.md`. Idempotent / crash-resumable.
15
-
16
- After a successful `--apply`, run the normal **`upgrade`** immediately — **before any
17
- review/commit ask** — so the deployment-lineage stamp advances to the current head (this mode
18
- **never writes stamps**); then review the migrated `docs/ai/` tree and the re-stamp together and
19
- commit them yourself in ONE gated commit.
20
-
21
- **Invariants:** guarded (mandatory `--dry-run` preview → explicit consent → `--apply`) · a durable pre-delete snapshot is written before any remove/overwrite (a locally-edited script is snapshotted, never silently clobbered) · the remove is gated on conservation passing AND the snapshot existing · a project with no old-layout monolith is a stated no-op · **never commits**.
@@ -1,482 +0,0 @@
1
- #!/usr/bin/env node
2
- // migrate-adr-store.mjs — the consent-gated, opt-in migration of an EXISTING consumer's docs/ai from
3
- // the retired 3-tier ADR cascade (HOT decisions.md → WARM/COLD monoliths) to the one-file-per-ADR
4
- // store (HOT decisions.md + docs/ai/adr/AD-NNN-slug.md records + the docs/ai/adr/log.md navigator).
5
- // Reached through the opt-in `migrate-adr-store` mode (SKILL.md): the upgrade moves an older layout
6
- // itself wherever scripts/ holds the kit's rotator, so after a full upgrade this mode does nothing; it
7
- // stays for a project whose scripts/ holds no kit script.
8
- //
9
- // What it does (in order, on --apply):
10
- // 1. GATE — docs/ai must be deployed, and the tree must be on the OLD layout. That is TWO shapes:
11
- // a decisions-archive monolith on disk, OR no monolith at all but a deployed
12
- // scripts/archive-decisions.mjs that predates the store (the project simply never
13
- // rotated). The no-monolith shape runs the crossing WITHOUT an explosion — snapshot,
14
- // script refresh, then SEED the store — and is re-runnable to completion from any crash
15
- // point, because a store directory alone never counts as finished. A tree with no ADR
16
- // substrate at all, or one already finalised, is a stated no-op.
17
- // 2. SNAPSHOT — write a durable pre-migration snapshot (decisions.md + both monoliths + the
18
- // pre-refresh consumer scripts/ copies) to the project's git dir (uncommittable), with a
19
- // stated out-of-tree fallback off git; fail LOUD if neither base is writable (Decision 5).
20
- // 3. FORCE-REFRESH — overwrite the consumer's deployed enforcement scripts (the DIRECTIONAL subset:
21
- // only kit-canon basenames the consumer's scripts/ already has) with this kit's bundled
22
- // copies, so their ongoing pre-commit gates run the NEW rotator + the NEW collapse rule.
23
- // A locally-edited script is snapshotted (step 2) before it is overwritten — never
24
- // silently clobbered — and the dry-run preview names every script that differs.
25
- // 4. MIGRATE — run the (new-scheme) rotator's conservation-checked --migrate --apply against the
26
- // project root: explode the monoliths into adr/ records, retire them, regenerate the
27
- // navigator + docs/ai/index.md. Idempotent / crash-resumable.
28
- //
29
- // Write discipline: preview (--dry-run) is the DEFAULT and writes NOTHING; --apply performs the
30
- // migration. It NEVER commits. Exit codes: 0 done / dry-run / no-op; 1 precondition STOP (no
31
- // deployment, no writable snapshot base, a failed migration); 2 usage. Dependency-free, Node >= 22.
32
- // No side effects on import.
33
-
34
- import { existsSync, readFileSync, readdirSync, statSync, mkdirSync, writeFileSync, chmodSync } from 'node:fs';
35
- import { join, resolve, dirname, relative, isAbsolute } from 'node:path';
36
- import { fileURLToPath } from 'node:url';
37
- import { spawnSync } from 'node:child_process';
38
- import { tmpdir } from 'node:os';
39
- import { writeContainedFileAtomic, assertDocsAiDeployment } from './atomic-write.mjs';
40
- import {
41
- monolithsPresent,
42
- HOT_REL,
43
- WARM_REL,
44
- COLD_REL,
45
- ADR_DIR_REL,
46
- NAV_REL,
47
- defaultRegenerateIndex,
48
- runCli as runArchiveDecisions,
49
- } from '../references/scripts/archive-decisions.mjs';
50
- import { isDirectRun } from './direct-run.mjs';
51
- import { surveyAdrLayoutStrict, ADR_LAYOUT_PATHS } from './family-registry.mjs';
52
-
53
- const HERE = dirname(fileURLToPath(import.meta.url));
54
- const KIT_ROOT = resolve(HERE, '..');
55
- const KIT_SCRIPTS = join(KIT_ROOT, 'references', 'scripts');
56
- const CONSUMER_SCRIPTS_REL = 'scripts';
57
- const SNAPSHOT_PREFIX = 'agent-workflow-adr-migration-snapshot';
58
-
59
- const EXIT_OK = 0;
60
- const EXIT_PRECONDITION = 1;
61
- const EXIT_USAGE = 2;
62
-
63
- export const MIGRATE_ADR_STORE_STOP = 'MIGRATE_ADR_STORE_STOP';
64
- const stop = (message) =>
65
- Object.assign(new Error(`[agent-workflow-kit] ${message}`), { name: 'MigrateAdrStoreStop', code: MIGRATE_ADR_STORE_STOP, exitCode: EXIT_PRECONDITION });
66
- const usageFail = (message) =>
67
- Object.assign(new Error(`[agent-workflow-kit] ${message}`), { exitCode: EXIT_USAGE });
68
-
69
- const USAGE = `usage: migrate-adr-store [--dry-run | --apply] [--cwd <dir>] [--help]
70
-
71
- Opt-in migration of a project's docs/ai from the retired 3-tier ADR cascade to the one-file-per-ADR
72
- store. Default is --dry-run: prints the migration plan (monoliths to retire, scripts to refresh, the
73
- conservation proof) and writes NOTHING. --apply snapshots, force-refreshes the enforcement scripts,
74
- then runs the conservation-checked migration. It NEVER commits — review the tree and commit yourself.`;
75
-
76
- // The mutually-exclusive dry-run/apply parse (a consent-gated writer never lets a later flag silently
77
- // decide whether it mutates) + --cwd — the family's shared consented-writer contract.
78
- export const parseArgs = (argv) => {
79
- const parsed = argv.reduce(
80
- (acc, a, i) => {
81
- if (acc.skip) return { ...acc, skip: false };
82
- if (a === '--help' || a === '-h') return { ...acc, help: true };
83
- if (a === '--dry-run') {
84
- if (acc.apply === true) throw usageFail('--dry-run and --apply are mutually exclusive — pick one');
85
- return { ...acc, apply: false, dryRunExplicit: true };
86
- }
87
- if (a === '--apply') {
88
- if (acc.dryRunExplicit) throw usageFail('--dry-run and --apply are mutually exclusive — pick one');
89
- return { ...acc, apply: true };
90
- }
91
- if (a === '--cwd') {
92
- const value = argv[i + 1];
93
- if (value === undefined || value.startsWith('-')) throw usageFail('--cwd needs a value: --cwd <dir>');
94
- return { ...acc, cwd: value, skip: true };
95
- }
96
- throw usageFail(`unknown argument "${a}"\n${USAGE}`);
97
- },
98
- { apply: false, dryRunExplicit: false, cwd: undefined, help: false, skip: false },
99
- );
100
- return { apply: parsed.apply === true, cwd: parsed.cwd, help: parsed.help };
101
- };
102
-
103
- // The DIRECTIONAL force-refresh set (Decision 12/13): a kit-canon enforcement script whose basename is
104
- // ALSO present in the consumer's scripts/ — never ADD a script the consumer lacks, never touch a
105
- // root-only/non-canon file. Returns [{ name, canon, dst, differs }] for every refresh candidate.
106
- export const planScriptRefresh = (cwd, deps = {}) => {
107
- const exists = deps.exists ?? existsSync;
108
- const read = deps.read ?? readFileSync;
109
- const kitScripts = deps.kitScripts ?? KIT_SCRIPTS;
110
- const consumerScripts = join(cwd, CONSUMER_SCRIPTS_REL);
111
- const out = [];
112
- for (const name of readdirSync(kitScripts).sort()) {
113
- const canon = join(kitScripts, name);
114
- if (!statSync(canon).isFile()) continue;
115
- const dst = join(consumerScripts, name);
116
- if (!exists(dst)) continue; // directional: the consumer does not deploy this script — never add it
117
- const differs = read(canon, 'utf8') !== read(dst, 'utf8');
118
- out.push({ name, canon, dst, differs });
119
- }
120
- return out;
121
- };
122
-
123
- // COMPANION seeds: modules the refreshed archivers IMPORT. The refresh above is deliberately
124
- // directional (never ADDS a basename the consumer lacks), but refreshing an OLD deployment's
125
- // archivers to this kit's canon without their runtime dependency would leave every refreshed
126
- // script crashing on a missing `./markdown-blocks.mjs` import until a separate upgrade run — so
127
- // the dependency rides the SAME apply, atomically, written before its importers.
128
- // `archive-caps.mjs` joined the list the moment `archive-changelog.mjs` began importing it: a new
129
- // import by a refreshed archiver reopens this exact hole, so the list moves with the imports.
130
- //
131
- // A seed is UNCONDITIONAL only when every refreshable archiver imports it. `markdown-blocks.mjs` is
132
- // imported by all three (changelog, decisions, issues), so any refresh needs it. `archive-caps.mjs`
133
- // is imported by `archive-changelog.mjs` ALONE — seeding it on a plain ADR migration that never
134
- // refreshed the changelog archiver would write a file with no importer, which is the directional
135
- // "never ADD a basename the consumer lacks" rule broken and a log line that says something untrue.
136
- const COMPANION_SEEDS = [
137
- { name: 'markdown-blocks.mjs', requiredBy: null },
138
- { name: 'markdown-blocks.test.mjs', requiredBy: null },
139
- { name: 'archive-caps.mjs', requiredBy: 'archive-changelog.mjs' },
140
- { name: 'archive-caps.test.mjs', requiredBy: 'archive-changelog.mjs' },
141
- ];
142
- export const planCompanionSeeds = (cwd, refresh, deps = {}) => {
143
- if (refresh.length === 0) return [];
144
- const exists = deps.exists ?? existsSync;
145
- const kitScripts = deps.kitScripts ?? KIT_SCRIPTS;
146
- const consumerScripts = join(cwd, CONSUMER_SCRIPTS_REL);
147
- const refreshed = new Set(refresh.map((entry) => entry.name));
148
- const out = [];
149
- for (const { name, requiredBy } of COMPANION_SEEDS) {
150
- if (requiredBy !== null && !refreshed.has(requiredBy)) continue;
151
- const canon = join(kitScripts, name);
152
- const dst = join(consumerScripts, name);
153
- if (exists(canon) && !exists(dst)) out.push({ name, canon, dst });
154
- }
155
- return out;
156
- };
157
-
158
- const gitDirOf = (cwd, spawn) => {
159
- const r = spawn('git', ['rev-parse', '--absolute-git-dir'], { cwd, encoding: 'utf8' });
160
- return r && r.status === 0 && r.stdout ? r.stdout.trim() : null;
161
- };
162
-
163
- // A path is INSIDE the work tree (stageable) when cwd contains it. The git dir is EXEMPT — it lives
164
- // under cwd but git never stages its own contents (uncommittable by construction, the Decision-5 basis).
165
- const isUnder = (child, parent) => {
166
- const rel = relative(parent, child);
167
- return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
168
- };
169
-
170
- // The ordered snapshot bases that are provably NOT stageable: the git dir first (always safe), then the
171
- // fallback base ONLY when its snapshot dir lands OUTSIDE cwd (else it is in the work tree and could be
172
- // committed — reject it). Returns [{ base, dir, viaGitDir }] (possibly empty).
173
- const snapshotBases = (cwd, stamp, gitDir, fallbackBase) => {
174
- const bases = [];
175
- if (gitDir) bases.push({ base: gitDir, dir: resolve(gitDir, `${SNAPSHOT_PREFIX}-${stamp}`), viaGitDir: true });
176
- const fallbackDir = resolve(fallbackBase, `${SNAPSHOT_PREFIX}-${stamp}`);
177
- if (!isUnder(fallbackDir, resolve(cwd))) bases.push({ base: fallbackBase, dir: fallbackDir, viaGitDir: false });
178
- return bases;
179
- };
180
-
181
- // The pre-migration snapshot dir chosen for the preview: the first out-of-tree base (git dir, else a
182
- // fallback proven outside cwd), or { dir: null } when none is available. Pure — creates nothing.
183
- export const resolveSnapshotDir = (cwd, stamp, deps = {}) => {
184
- const spawn = deps.spawnSync ?? spawnSync;
185
- const fallbackBase = deps.snapshotFallbackBase ?? tmpdir();
186
- const gitDir = gitDirOf(cwd, spawn);
187
- const chosen = snapshotBases(cwd, stamp, gitDir, fallbackBase)[0] ?? null;
188
- return chosen ? { base: chosen.base, gitDir, dir: chosen.dir, viaGitDir: chosen.viaGitDir } : { base: null, gitDir, dir: null, viaGitDir: false };
189
- };
190
-
191
- // Write the durable snapshot (decisions.md + both monoliths + the pre-refresh consumer scripts). Tries
192
- // the git dir first, then an out-of-tree fallback; fails LOUD if none is available/writable (Decision 5).
193
- // Paths are flattened (/ → __) exactly like the rotator's own snapshot.
194
- export const writeSnapshot = (cwd, refresh, stamp, deps = {}) => {
195
- const spawn = deps.spawnSync ?? spawnSync;
196
- const read = deps.read ?? readFileSync;
197
- const exists = deps.exists ?? existsSync;
198
- const mkdir = deps.mkdir ?? ((p) => mkdirSync(p, { recursive: true }));
199
- const write = deps.write ?? ((p, b) => writeFileSync(p, b, 'utf8'));
200
- const fallbackBase = deps.snapshotFallbackBase ?? tmpdir();
201
- const gitDir = gitDirOf(cwd, spawn);
202
- const bases = snapshotBases(cwd, stamp, gitDir, fallbackBase);
203
- if (bases.length === 0) {
204
- throw stop(`refusing to migrate: no out-of-tree snapshot location (not a git repo, and the fallback would land inside the work tree ${cwd}) — a durable, non-stageable pre-migration snapshot is mandatory`);
205
- }
206
-
207
- const files = [];
208
- for (const rel of [HOT_REL, WARM_REL, COLD_REL]) {
209
- const abs = join(cwd, rel);
210
- if (exists(abs)) files.push({ rel, content: read(abs, 'utf8') });
211
- }
212
- for (const { name, dst } of refresh) {
213
- if (exists(dst)) files.push({ rel: `${CONSUMER_SCRIPTS_REL}/${name}`, content: read(dst, 'utf8') });
214
- }
215
-
216
- let lastErr = null;
217
- for (const { dir, viaGitDir } of bases) {
218
- try {
219
- mkdir(dir);
220
- for (const { rel, content } of files) write(resolve(dir, rel.replace(/[/\\]/g, '__')), content);
221
- return { dir, viaGitDir, fileCount: files.length };
222
- } catch (err) {
223
- lastErr = err;
224
- }
225
- }
226
- throw stop(`refusing to migrate: no writable snapshot location (${lastErr && lastErr.message}) — a durable pre-migration snapshot is mandatory`);
227
- };
228
-
229
- // Overwrite each refresh target with the kit canon, atomically, preserving the canon's exec bit.
230
- //
231
- // ORDER MATTERS: the rotation script is what the layout discriminator reads, so it is written LAST.
232
- // A crash partway through a refresh that had already flipped it would otherwise leave a tree that
233
- // LOOKS refreshed while other scripts are still the old copies — and a resume, keying on that same
234
- // script, would skip them forever. Written last, an interrupted refresh always re-plans in full.
235
- const DISCRIMINATOR_SCRIPT = ADR_LAYOUT_PATHS.rotator.split('/').pop();
236
- const refreshOrder = (refresh) => [
237
- ...refresh.filter((r) => r.name !== DISCRIMINATOR_SCRIPT),
238
- ...refresh.filter((r) => r.name === DISCRIMINATOR_SCRIPT),
239
- ];
240
-
241
- const applyScriptRefresh = (cwd, refresh, deps = {}) => {
242
- const read = deps.read ?? readFileSync;
243
- const chmod = deps.chmod ?? chmodSync;
244
- const stat = deps.stat ?? statSync;
245
- // Companion modules FIRST (a dependency must land before its importers), refresh order after —
246
- // the discriminator still last, so an interrupted apply always re-plans in full. Returns the
247
- // seeded names (computed pre-write; recomputing after would see them present and report none).
248
- const seeds = planCompanionSeeds(cwd, refresh, deps);
249
- for (const { canon, dst, name } of [...seeds, ...refreshOrder(refresh)]) {
250
- writeContainedFileAtomic(cwd, dst, read(canon, 'utf8'), deps, { stop, label: `${CONSUMER_SCRIPTS_REL}/${name}` });
251
- chmod(dst, stat(canon).mode & 0o777); // the exec bit is the git-tracked axis the mirror guard pins
252
- }
253
- return seeds.map((s) => s.name);
254
- };
255
-
256
- // ── the no-monolith crossing ─────────────────────────────────────────────────────
257
- //
258
- // A consumer on the RETIRED scheme that never rotated far enough to produce a monolith used to read
259
- // "a fresh new-scheme tree" here and be sent away. The discriminator is the deployed rotation
260
- // script's own provenance (family-registry.mjs), never "has decisions.md, lacks adr/".
261
- //
262
- // Re-entry is decided by what is FINISHED, never by one existence bit: the store directory existing
263
- // does not prove the navigator was written or the index regenerated, so a crash there must not turn
264
- // the next --apply into a no-op. Every write below is individually idempotent, which is why this
265
- // needs no resume ledger.
266
-
267
- // The crossing is COMPLETE when the navigator exists, the tree's own gate passes, AND the index the
268
- // crossing regenerates is fresh. The index is part of the criterion because it is a real output of
269
- // the crossing that `--check` never looks at: a crash (or a failed regeneration) between the
270
- // navigator write and the index left a tree that reported "already migrated" on the retry and never
271
- // repaired the index. An unreachable index generator is NOT treated as fresh — the crossing re-runs
272
- // and fails loudly again, which is the honest outcome for a broken generator.
273
- const INDEX_GENERATOR = join(KIT_SCRIPTS, 'check-docs-size.mjs');
274
- const isIndexFresh = (cwd, deps = {}) => {
275
- const spawn = deps.spawnSync ?? spawnSync;
276
- const r = spawn(process.execPath, [INDEX_GENERATOR, '--check-index', `--root=${cwd}`], { encoding: 'utf8' });
277
- return !r.error && r.status === 0;
278
- };
279
-
280
- // The layout verdict leads, and it is the SAME verdict the status line and the advisor read: an
281
- // old-scheme rotator beside a finished store still answers `old-unrotated`, so treating that tree as
282
- // done would leave the signal permanently lit with nothing able to clear it.
283
- const isFinalised = (cwd, runMigrate, deps = {}) =>
284
- surveyAdrLayoutStrict(cwd, deps) === 'migrated' &&
285
- substratePresent(join(cwd, NAV_REL), deps) &&
286
- runMigrate(['--check'], { root: cwd, log: () => {}, logError: () => {} }) === EXIT_OK &&
287
- isIndexFresh(cwd, deps);
288
-
289
- // `existsSync` answers false for EVERY failure, EACCES included — so asking it whether the substrate
290
- // is there would turn an UNREADABLE tree into a confident "nothing to migrate", exit 0. Absence is
291
- // ENOENT and nothing else; anything else is surfaced, never swallowed. Same policy the layout survey
292
- // already enforces, now applied where the tool acts on it.
293
- const substratePresent = (path, deps = {}) => {
294
- const stat = deps.statSync ?? statSync;
295
- try {
296
- stat(path);
297
- return true;
298
- } catch (err) {
299
- if (err && err.code === 'ENOENT') return false;
300
- throw stop(`cannot read ${path} (${err && err.message}) — refusing to report on a tree it could not inspect`);
301
- }
302
- };
303
-
304
- const crossWithoutMonolith = (cwd, args, stamp, { log, error, runMigrate, deps }) => {
305
- const hasStore = substratePresent(join(cwd, ADR_DIR_REL), deps);
306
- const hasHot = substratePresent(join(cwd, HOT_REL), deps);
307
-
308
- if (!hasHot && !hasStore) {
309
- // NOT "a fresh new-scheme tree" — this tree may well be old-scheme; it simply has no ADR
310
- // substrate for the crossing to carry across, which is exactly the rotator's own skip.
311
- log(`[migrate-adr-store] nothing to migrate — no ADR substrate (neither ${HOT_REL} nor ${ADR_DIR_REL}/) and no legacy monolith.`);
312
- return EXIT_OK;
313
- }
314
- if (hasStore && isFinalised(cwd, runMigrate, deps)) {
315
- log('[migrate-adr-store] already migrated — the one-file-per-ADR store is in place and its gate is green; nothing to do.');
316
- return EXIT_OK;
317
- }
318
- if (!hasStore && surveyAdrLayoutStrict(cwd, deps) === 'none' && !substratePresent(join(cwd, ADR_LAYOUT_PATHS.rotator), deps)) {
319
- // Nothing to refresh (the refresh is directional — it never ADDS a script) and nothing to
320
- // maintain a store we might seed. The normal upgrade owns seeding the pair.
321
- log('[migrate-adr-store] nothing to migrate — no deployed rotation script; run the normal upgrade first (it seeds the ADR enforcement pair).');
322
- return EXIT_OK;
323
- }
324
-
325
- const refresh = planScriptRefresh(cwd, deps);
326
- const drifted = refresh.filter((r) => r.differs);
327
- // The read-only preflight: the SAME parse / half-migrated guard / store-integrity check the seed
328
- // itself runs, stopping before every write. Without it a dry-run could green-light an apply that
329
- // writes the store and only then discovers it cannot converge.
330
- const preflight = (logError) => runMigrate(['--write-navigator', '--dry-run'], { root: cwd, log: () => {}, logError });
331
-
332
- if (!args.apply) {
333
- const preview = resolveSnapshotDir(cwd, stamp, deps);
334
- // Three attempts to SUMMARISE why this tree needs the crossing produced three wrong sentences —
335
- // each true of the common case and false of a state this arm deliberately supports. So the
336
- // summary is gone: the preview states the two facts it actually knows, one per line, and the
337
- // reader draws the conclusion. Nothing here can drift out of step with the tree, because nothing
338
- // here is an inference. (Which scripts are stale is already reported by the refresh line below —
339
- // never re-asserted here.)
340
- const layout = surveyAdrLayoutStrict(cwd, deps);
341
- const rotatorFact = layout === 'old-unrotated'
342
- ? `predates the one-file-per-ADR store`
343
- : substratePresent(join(cwd, ADR_LAYOUT_PATHS.rotator), deps)
344
- ? `already names the store`
345
- : `not deployed`; // and NOT "nothing to refresh" — a sibling script may still need one
346
- log('[migrate-adr-store] --dry-run — no files will be changed. Planned crossing (no legacy monolith to retire):');
347
- log(` deployed ${ADR_LAYOUT_PATHS.rotator}: ${rotatorFact}`);
348
- log(` ${ADR_DIR_REL}/: ${hasStore ? 'present, but the crossing has not been completed' : 'absent'}`);
349
- log(` snapshot → ${preview.dir ? `${preview.dir} (${preview.viaGitDir ? 'git dir' : 'out-of-tree fallback'})` : 'NONE — no out-of-tree location; run inside a git repo (apply would refuse otherwise)'}`);
350
- log(` refresh ${refresh.length} enforcement script(s) to this kit's version${drifted.length ? ` (${drifted.length} locally differ: ${drifted.map((r) => r.name).join(', ')})` : ''}`);
351
- for (const s of planCompanionSeeds(cwd, refresh, deps)) log(` seed companion module ${CONSUMER_SCRIPTS_REL}/${s.name} (imported by the refreshed archivers; absent at the consumer)`);
352
- log(` then seed the store: create ${ADR_DIR_REL}/, write ${NAV_REL} and regenerate docs/ai/index.md`);
353
- const code = preflight((m) => error(` ${m}`));
354
- if (code !== EXIT_OK) {
355
- throw stop(`the tree cannot be seeded as it stands (exit ${code}) — NOT safe to --apply; fix the reported problem, then re-run.`);
356
- }
357
- if (preview.dir === null) {
358
- throw stop('no out-of-tree snapshot location — --apply would refuse; run inside a git repo (or point the fallback outside the project), then re-run.');
359
- }
360
- log(' index regeneration is verified at --apply time (a dry-run cannot observe it without writing).');
361
- log('Run `/agent-workflow-kit migrate-adr-store` again with --apply to perform it (it never commits).');
362
- return EXIT_OK;
363
- }
364
-
365
- const pre = preflight(error);
366
- if (pre !== EXIT_OK) {
367
- throw stop(`the tree cannot be seeded as it stands (preflight exit ${pre}) — refusing to touch the tree; fix the reported problem, then re-run.`);
368
- }
369
-
370
- const snapshot = writeSnapshot(cwd, refresh, stamp, deps);
371
- // The FULL refresh is re-planned and re-applied on every entry, so an interrupted one always
372
- // completes; the discriminator script is written last (see refreshOrder).
373
- const seededNames = applyScriptRefresh(cwd, refresh, deps);
374
-
375
- // Capture the index-regeneration verdict instead of matching log prose: the rotator logs a failed
376
- // regeneration and still returns 0, so "the gates are green" would not mean the index is fresh.
377
- const regen = { ok: true, detail: '' };
378
- const seed = runMigrate(['--write-navigator'], {
379
- root: cwd,
380
- log,
381
- logError: error,
382
- regenerateIndex: (root, today, d) => {
383
- const r = (deps.regenerateIndex ?? defaultRegenerateIndex)(root, today, d);
384
- regen.ok = r.ok;
385
- regen.detail = r.detail;
386
- return r;
387
- },
388
- });
389
- if (seed !== EXIT_OK) {
390
- throw stop(`seeding the ADR store failed (exit ${seed}) — the pre-crossing snapshot is at ${snapshot.dir}; resolve the reported problem and re-run (the crossing is idempotent).`);
391
- }
392
- if (!regen.ok) {
393
- throw stop(`the ADR store was seeded but docs/ai/index.md was NOT regenerated (${regen.detail}) — the pre-crossing snapshot is at ${snapshot.dir}; fix the index generator and re-run (the crossing is idempotent).`);
394
- }
395
- const verify = runMigrate(['--check'], { root: cwd, log: () => {}, logError: error });
396
- if (verify !== EXIT_OK) {
397
- throw stop(`the ADR store was seeded but its own gate does not pass (exit ${verify}) — the pre-crossing snapshot is at ${snapshot.dir}; resolve the reported problem and re-run (the crossing is idempotent).`);
398
- }
399
-
400
- // States what this run DID, never what the tree was before it: the same arm completes an
401
- // interrupted crossing whose scripts were already current, which no "old-scheme" claim covers.
402
- log('[migrate-adr-store] crossing complete — the one-file-per-ADR store is in place (no legacy monolith was present):');
403
- log(` snapshot: ${snapshot.dir} (${snapshot.viaGitDir ? 'git dir' : 'out-of-tree fallback'}, ${snapshot.fileCount} file(s))`);
404
- log(` refreshed ${refresh.length} enforcement script(s) to this kit's version${seededNames.length ? ` + seeded ${seededNames.join(', ')}` : ''}`);
405
- log(` seeded ${ADR_DIR_REL}/ with ${NAV_REL} and regenerated docs/ai/index.md`);
406
- log(' next: run the normal upgrade (it re-stamps the deployment lineage to the current head),');
407
- log(' then review the migrated docs/ai/ tree and the re-stamp together and commit them yourself — this command never commits.');
408
- return EXIT_OK;
409
- };
410
-
411
- export const main = (argv = process.argv.slice(2), deps = {}) => {
412
- const log = deps.log ?? console.log;
413
- const error = deps.error ?? console.error;
414
- const runMigrate = deps.runArchiveDecisions ?? runArchiveDecisions;
415
- const stamp = deps.stamp ?? new Date().toISOString().replace(/[:.]/g, '-');
416
- try {
417
- const args = parseArgs(argv);
418
- if (args.help) {
419
- log(USAGE);
420
- return EXIT_OK;
421
- }
422
- const cwd = resolve(args.cwd ?? process.cwd());
423
- assertDocsAiDeployment(cwd, deps, { stop, noun: 'the ADR store', rel: 'the docs/ai ADR store' });
424
-
425
- const monoliths = monolithsPresent(cwd);
426
- if (monoliths.length === 0) {
427
- return crossWithoutMonolith(cwd, args, stamp, { log, error, runMigrate, deps });
428
- }
429
-
430
- const refresh = planScriptRefresh(cwd, deps);
431
- const drifted = refresh.filter((r) => r.differs);
432
-
433
- if (!args.apply) {
434
- const preview = resolveSnapshotDir(cwd, stamp, deps);
435
- log('[migrate-adr-store] --dry-run — no files will be changed. Planned migration:');
436
- log(` old layout: ${monoliths.join(', ')} (will be exploded into ${ADR_DIR_REL}/ then retired)`);
437
- log(` snapshot → ${preview.dir ? `${preview.dir} (${preview.viaGitDir ? 'git dir' : 'out-of-tree fallback'})` : 'NONE — no out-of-tree location; run inside a git repo (apply would refuse otherwise)'}`);
438
- log(` refresh ${refresh.length} enforcement script(s) to this kit's version${drifted.length ? ` (${drifted.length} locally differ: ${drifted.map((r) => r.name).join(', ')})` : ''}`);
439
- for (const s of planCompanionSeeds(cwd, refresh, deps)) log(` seed companion module ${CONSUMER_SCRIPTS_REL}/${s.name} (imported by the refreshed archivers; absent at the consumer)`);
440
- log(' then the conservation-checked rotation:');
441
- // Surface the rotation's own exit code: a failed dry-run must NOT print the
442
- // "run with --apply" go-ahead nor exit 0 — it would send the user to --apply on an unsafe tree.
443
- const code = runMigrate(['--migrate'], { root: cwd, log: (m) => log(` ${m}`), logError: (m) => error(` ${m}`) });
444
- if (code !== EXIT_OK) {
445
- throw stop(`the dry-run rotation would not conserve every ADR (exit ${code}) — NOT safe to --apply; fix the reported problem, then re-run.`);
446
- }
447
- // A null preview means --apply would refuse (no out-of-tree snapshot base) — never green-light it
448
- // A dry-run go-ahead must not send the user to an apply that will STOP.
449
- if (preview.dir === null) {
450
- throw stop('no out-of-tree snapshot location — --apply would refuse; run inside a git repo (or point the fallback outside the project), then re-run.');
451
- }
452
- log('Run `/agent-workflow-kit migrate-adr-store` again with --apply to perform it (it never commits).');
453
- return EXIT_OK;
454
- }
455
-
456
- // Pre-flight: validate the rotation on a dry-run (conservation + store integrity) BEFORE any
457
- // mutation, so a failure aborts having touched nothing — no snapshot, no refreshed scripts, no
458
- // half-migrated tree. The error surfaces on logError; the plan itself is suppressed (already shown).
459
- const preflight = runMigrate(['--migrate'], { root: cwd, log: () => {}, logError: error });
460
- if (preflight !== EXIT_OK) {
461
- throw stop(`the migration would not conserve every ADR (dry-run exit ${preflight}) — refusing to touch the tree; fix the reported problem, then re-run.`);
462
- }
463
-
464
- const snapshot = writeSnapshot(cwd, refresh, stamp, deps);
465
- const seededNames = applyScriptRefresh(cwd, refresh, deps);
466
- const code = runMigrate(['--migrate', '--apply'], { root: cwd, log, logError: error });
467
- if (code !== EXIT_OK) {
468
- throw stop(`the rotation failed (exit ${code}) — the pre-migration snapshot is at ${snapshot.dir}; resolve the reported problem and re-run (the migration is idempotent).`);
469
- }
470
- log('[migrate-adr-store] migrated the 3-tier ADR cascade → one-file-per-ADR store:');
471
- log(` snapshot: ${snapshot.dir} (${snapshot.viaGitDir ? 'git dir' : 'out-of-tree fallback'}, ${snapshot.fileCount} file(s))`);
472
- log(` refreshed ${refresh.length} enforcement script(s) to this kit's version${seededNames.length ? ` + seeded ${seededNames.join(', ')}` : ''}`);
473
- log(' next: run the normal upgrade (it re-stamps the deployment lineage to the current head),');
474
- log(' then review the migrated docs/ai/ tree and the re-stamp together and commit them yourself — this command never commits.');
475
- return EXIT_OK;
476
- } catch (err) {
477
- error(err.message);
478
- return err.exitCode ?? EXIT_PRECONDITION;
479
- }
480
- };
481
-
482
- if (isDirectRun(import.meta.url)) process.exitCode = main();