@sabaiway/agent-workflow-kit 14.50.0 → 15.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/SKILL.md +1 -5
- package/capability.json +1 -1
- package/package.json +1 -1
- package/references/advisor-writers.md +0 -1
- package/references/modes/recommendations.md +1 -2
- package/references/modes/status.md +1 -1
- package/tools/commands.mjs +1 -8
- package/tools/distribution-files/scripts.mjs +1 -1
- package/tools/family-registry.mjs +8 -9
- package/tools/recommendations.mjs +2 -40
- package/tools/renderers.mjs +1 -1
- package/tools/write-lanes.mjs +0 -1
- package/references/modes/migrate-adr-store.md +0 -21
- package/tools/migrate-adr-store.mjs +0 -482
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,26 @@ 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.0.0 — the opt-in ADR migration mode retires; status names the upgrade for an older ADR layout (AD-204)
|
|
8
|
+
|
|
9
|
+
**MAJOR: `/agent-workflow-kit migrate-adr-store` is gone, with no alias.** Since 14.50.0 the upgrade moves an older
|
|
10
|
+
ADR layout itself wherever `scripts/` holds the kit's decisions script, so the opt-in mode had nothing left to do
|
|
11
|
+
there. The mode, `tools/migrate-adr-store.mjs` and its suite are deleted, with the mode's catalog entry and its
|
|
12
|
+
`SKILL.md` section; the invocation now falls to `help`, like any unknown mode. No migration note is owed.
|
|
13
|
+
|
|
14
|
+
- **The advisor stops offering `adr-store-migration`.** The item is retired with no replacement, with its lane, its
|
|
15
|
+
row in `references/advisor-writers.md` and its posture note in `references/modes/recommendations.md`. The writers
|
|
16
|
+
table holds sixteen chat variants.
|
|
17
|
+
- **Status names the upgrade.** For a project on an older ADR layout (a retired archive file on disk, or a decisions
|
|
18
|
+
script older than the store), the `ADR store` line now reads `old layout — /agent-workflow-kit upgrade moves it where
|
|
19
|
+
scripts/ holds the kit's decisions rotator, or prints the rotator's refusal`, and the status mode's note carries the
|
|
20
|
+
same text.
|
|
21
|
+
- **The store run's failure says what it knows.** When the upgrade's run of `scripts/archive-decisions.mjs
|
|
22
|
+
--ensure-current` fails, its detail now ends `— the ADR store was not confirmed current` instead of `— the ADR store
|
|
23
|
+
is not current`; the cause `adr-store-not-current` is unchanged.
|
|
24
|
+
|
|
25
|
+
Where `scripts/` holds no kit script, nothing in the kit moves an older layout any more.
|
|
26
|
+
|
|
7
27
|
## 14.50.0 — the upgrade moves an older ADR layout itself, with no question (AD-203)
|
|
8
28
|
|
|
9
29
|
**`/agent-workflow-kit upgrade` now brings your ADR store current in the same run.** Before, on a project still on the
|
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: '
|
|
6
|
+
version: '15.0.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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sabaiway/agent-workflow-kit",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "15.0.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 |
|
|
@@ -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
|
|
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
|
|
|
@@ -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
|
|
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).
|
package/tools/commands.mjs
CHANGED
|
@@ -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
|
-
//
|
|
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
|
|
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
|
};
|
|
@@ -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
|
|
347
|
-
//
|
|
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
|
|
366
|
-
//
|
|
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
|
|
372
|
-
//
|
|
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
|
|
424
|
+
// One implementation, two stated policies.
|
|
426
425
|
const surveyAdrLayout = (dir, deps) => {
|
|
427
426
|
try {
|
|
428
427
|
return surveyAdrLayoutStrict(dir, deps);
|
|
@@ -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
|
|
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', '
|
|
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,
|
package/tools/renderers.mjs
CHANGED
|
@@ -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 —
|
|
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.
|
package/tools/write-lanes.mjs
CHANGED
|
@@ -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();
|