@sabaiway/agent-workflow-kit 20.2.0 → 22.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +7 -5
  3. package/SKILL.md +1 -1
  4. package/bin/install.mjs +10 -11
  5. package/capability.json +1 -1
  6. package/launchers/windsurf-workflow.md +3 -1
  7. package/migrations/3.0.0-hardened-core-loop.md +7 -6
  8. package/package.json +5 -2
  9. package/references/advisor-writers.md +1 -1
  10. package/references/contracts.md +11 -10
  11. package/references/modes/bootstrap.md +3 -3
  12. package/references/modes/commit-guard.md +1 -1
  13. package/references/modes/gates.md +2 -2
  14. package/references/modes/recommendations.md +3 -3
  15. package/references/modes/upgrade.md +6 -6
  16. package/references/scripts/{archive-caps.mjs → archives/archive-caps.mjs} +1 -1
  17. package/references/scripts/{archive-changelog.mjs → archives/archive-changelog.mjs} +7 -9
  18. package/references/scripts/{archive-decisions.mjs → archives/archive-decisions.mjs} +13 -10
  19. package/references/scripts/{archive-issues.mjs → archives/archive-issues.mjs} +7 -8
  20. package/references/scripts/{check-docs-size.mjs → docs-size/check-docs-size.mjs} +3 -4
  21. package/references/scripts/docs-size/index.mjs +2 -0
  22. package/references/scripts/family.json +45 -0
  23. package/references/scripts/family.mjs +90 -0
  24. package/references/scripts/gates/kit-command-gates.mjs +117 -0
  25. package/references/scripts/{migrate-gates.mjs → gates/migrate-gates.mjs} +263 -182
  26. package/references/scripts/{install-git-hooks.mjs → git-hooks/install-git-hooks.mjs} +50 -38
  27. package/references/scripts/run.mjs +90 -0
  28. package/references/scripts/shared/index.mjs +3 -0
  29. package/references/scripts/shared/project-root.mjs +11 -0
  30. package/references/scripts/spec-schema/index.mjs +2 -0
  31. package/references/scripts/test-reporter/reporter.mjs +130 -0
  32. package/references/shared/composition-handoff.md +1 -1
  33. package/references/shared/deploy-tail.md +2 -2
  34. package/references/templates/SPEC_TEMPLATE.md +1 -1
  35. package/references/templates/adr-record.md +3 -3
  36. package/tools/apply-danger-check.mjs +9 -5
  37. package/tools/atomic-write.mjs +3 -1
  38. package/tools/coverage-producer.mjs +76 -41
  39. package/tools/direct-run.mjs +2 -0
  40. package/tools/distribution-files/retired.mjs +99 -0
  41. package/tools/distribution-files/scripts.mjs +68 -52
  42. package/tools/ensure-configs.mjs +21 -21
  43. package/tools/ensure-ops.mjs +60 -18
  44. package/tools/ensure-specs.mjs +85 -47
  45. package/tools/ensure-vocabulary.mjs +4 -4
  46. package/tools/epic-shape-cli.mjs +1 -1
  47. package/tools/epic-shape-ledger.mjs +1 -1
  48. package/tools/epic-shape.mjs +1 -1
  49. package/tools/family-registry.mjs +3 -1
  50. package/tools/feedback-record-cli.mjs +1 -1
  51. package/tools/fold-scope.mjs +2 -2
  52. package/tools/gates-declaration.mjs +22 -14
  53. package/tools/gates-init.mjs +33 -17
  54. package/tools/git-hooks.mjs +90 -65
  55. package/tools/jev-connect.mjs +1 -1
  56. package/tools/jev-guide.mjs +1 -1
  57. package/tools/jev-skill.mjs +1 -1
  58. package/tools/known-footprint.mjs +7 -29
  59. package/tools/node-evidence.mjs +29 -15
  60. package/tools/now-cli.mjs +1 -1
  61. package/tools/payload-prune.mjs +53 -58
  62. package/tools/plan-shape-cli.mjs +1 -1
  63. package/tools/plan-shape.mjs +1 -1
  64. package/tools/project-rules/rules-record.mjs +1 -1
  65. package/tools/queue-audit-cli.mjs +1 -1
  66. package/tools/queue-audit.mjs +2 -2
  67. package/tools/queue-purge-archive.mjs +1 -1
  68. package/tools/queue-purge-cli.mjs +1 -1
  69. package/tools/queue-purge.mjs +1 -1
  70. package/tools/recommendations.mjs +37 -25
  71. package/tools/script-priors.mjs +31 -3
  72. package/tools/source-size/piles.mjs +1 -1
  73. package/tools/spec-adoption.mjs +1 -1
  74. package/tools/spec-check-ops.mjs +2 -2
  75. package/tools/spec-check.mjs +2 -2
  76. package/tools/spec-coverage.mjs +1 -1
  77. package/tools/tier-guide.mjs +1 -1
  78. package/tools/transition/index.mjs +1 -1
  79. package/tools/upgrade-runlist.mjs +3 -3
  80. package/tools/write-lanes.mjs +2 -2
  81. package/references/scripts/_expect-shim.mjs +0 -41
  82. package/references/scripts/archive-caps.test.mjs +0 -321
  83. package/references/scripts/archive-changelog.test.mjs +0 -560
  84. package/references/scripts/archive-conservation.test.mjs +0 -466
  85. package/references/scripts/archive-decisions.test.mjs +0 -1503
  86. package/references/scripts/archive-issues.test.mjs +0 -825
  87. package/references/scripts/archiver-structure.test.mjs +0 -84
  88. package/references/scripts/check-docs-size-cli.test.mjs +0 -325
  89. package/references/scripts/check-docs-size-ensure.test.mjs +0 -360
  90. package/references/scripts/check-docs-size.test.mjs +0 -395
  91. package/references/scripts/install-git-hooks-repo-exec.test.mjs +0 -185
  92. package/references/scripts/install-git-hooks.test.mjs +0 -241
  93. package/references/scripts/markdown-blocks.test.mjs +0 -310
  94. package/references/scripts/migrate-gates-branches.test.mjs +0 -302
  95. package/references/scripts/migrate-gates.test.mjs +0 -517
  96. package/references/scripts/spec-schema.test.mjs +0 -352
  97. /package/references/scripts/{markdown-blocks.mjs → shared/markdown-blocks.mjs} +0 -0
  98. /package/references/scripts/{spec-schema.mjs → spec-schema/spec-schema.mjs} +0 -0
@@ -13,7 +13,7 @@ Requires: ${CLAUDE_SKILL_DIR}/references/shared/report-footer.md · ${CLAUDE_SKI
13
13
  1. `entry-block` — `node ${CLAUDE_SKILL_DIR}/tools/inject-methodology.mjs reconcile <project>/AGENTS.md` → the kit block between its two workflow:kit comment lines, its table one row per theme, written current with no question and no copy kept, its line naming the route (text of your own goes outside the two workflow:kit comment lines; a change to a kit rule goes in its theme's file under docs/ai/rules/local/): added · already current · written · refused · a hard STOP.
14
14
  2. `footprint` — `node ${CLAUDE_SKILL_DIR}/tools/hide-footprint.mjs --dir <project> --reconcile --dry-run` → visibility: visible · ambiguous · hidden — consent (conditional): ambiguous → ask which it is BEFORE anything; hidden → the conditional re-run without `--dry-run` (its surfaced paths ask per bootstrap step 9).
15
15
  3. `configs` — `node ${CLAUDE_SKILL_DIR}/tools/ensure-configs.mjs --reconcile --cwd <project>` → one line per ensure: `seeded` / `note-refreshed` / `refreshed` / `regenerated` / `pending` / `already-current` / `customized-preserved` / `malformed-preserved` / `already-present` / `not-placed` / `skipped-no-node-evidence` / `failed`.
16
- 4. `gates-migration` — `node ${CLAUDE_SKILL_DIR}/references/scripts/migrate-gates.mjs --kit-tools ${CLAUDE_SKILL_DIR}/tools --cwd <project>` → the preview plan · INERT checker · CUSTOMIZED entries, each named — consent: apply only on an explicit yes, re-run with `--apply`.
16
+ 4. `gates-migration` — `node ${CLAUDE_SKILL_DIR}/references/scripts/gates/migrate-gates.mjs --kit-tools ${CLAUDE_SKILL_DIR}/tools --cwd <project> --apply` → every move written with no question, each acted row with its `was:`: SWITCH · EXTEND · REMOVE · KEPT · CUSTOMIZED · OFFER — consent (conditional): the coverage-check add alone, on an explicit yes run its printed OFFER line, the same command with `--apply --add-checker`.
17
17
  5. `bridges` — `node ${CLAUDE_SKILL_DIR}/tools/setup-backends.mjs --refresh-placed` → per-bridge lines: refreshed · already current · skipped — with its stated reason (not placed / newer than the bundle / unsupported host) · `skipped-readonly` · could not refresh.
18
18
  6. `tier` — `node ${CLAUDE_SKILL_DIR}/tools/tier-preview.mjs --cwd <project>` → per gap: present · offered · declined · undecidable · applied · recorded · refused — consent: one ask, only when offered.
19
19
  7. `bridge-settings` — `node ${CLAUDE_SKILL_DIR}/tools/bridge-settings.mjs --reconcile` → outcome line(s), pasted verbatim: ok · absent · flagged · duplicates · unusable.
@@ -32,7 +32,7 @@ Requires: ${CLAUDE_SKILL_DIR}/references/shared/report-footer.md · ${CLAUDE_SKI
32
32
 
33
33
  **`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 kit block — no lineage-head bump, no migration file.
34
34
 
35
- **`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` / `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` / `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** — before the equal-head exit, the migrations and the re-stamp. Add `--dry-run` to preview without writing a byte. Like the kit block + the footprint reconcile, all nine reach an equal-head deployment **without a lineage-head bump or a migration file**.
35
+ **`configs` — the project-configuration ensures, ONE run.** The ONE command performs **all nine** ensures — orchestration config · gate declaration · autonomy declaration · vehicles declaration · executor check · spec layer · enforcement scripts · 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` / `malformed-preserved`; gates, autonomy and vehicles → `seeded` / `already-present`; executor → `not-placed` / `already-current` / `pending`; specs → `seeded` / `refreshed` / `already-present` / `skipped-no-node-evidence`; scripts → `seeded` / `refreshed` / `already-present` / `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** — before the equal-head exit, the migrations and the re-stamp. Add `--dry-run` to preview without writing a byte. Like the kit block + the footprint reconcile, all nine reach an equal-head deployment **without a lineage-head bump or a migration file**.
36
36
 
37
37
  **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, the current note is left and an absent, prior or any other note is written current with no question and no copy kept, **every activity and slot the user set kept** (CRLF/whitespace normalized first) → `note-refreshed`; a differing note's line names the route — a note of your own goes in AGENTS.md, outside the kit block's two workflow:kit comment lines; 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 or keeps the file (memory upgrade step 2) and this ensure writes the note; in the **fallback** path it does both. (Memory stays standalone.)
38
38
 
@@ -42,15 +42,15 @@ Requires: ${CLAUDE_SKILL_DIR}/references/shared/report-footer.md · ${CLAUDE_SKI
42
42
 
43
43
  **What the executor ensure does.** It never writes: a placed `.claude/agents/executor.md` whose bytes differ from the body derived from `docs/ai/vehicles.json` is `pending` and an absent one is `not-placed` — the advisor's `agents` item writes the derived body.
44
44
 
45
- **What the enforcement-script ensure does.** It judges every kit script — each `*.mjs` of `${CLAUDE_SKILL_DIR}/references/scripts/` but the spec-layer pairs — once the component is accepted: a kit script outside the seed names (memory's own copies) stands in `scripts/` as a regular file. Each file by proof, with no question and no copy kept: a shipped prior is refreshed, an edited body replaced (its line names where a lasting edit goes), an absent file placed, the current body left. The hook installer and its two suites go first; a closing line says the commit hook runs the files written. A declined enforcement offer keeps the standing seed files current with the modules they import, places no other kit script (one line says so) and words that hook-run line as a condition. With no kit script there: `not-placed`, nothing written. **The ADR store, after the writes:** where the run judged the rotator, it runs `scripts/archive-decisions.mjs --ensure-current`, with no question, which brings the store current (an older layout moved) or writes nothing; its lines are relayed under `ADR store: `. A rotator that does not bring the store current is `failed` / `adr-store-not-current`, the scripts written above staying as written: its refusal stops the upgrade. Where the size practice measures `scripts/`, a write may grow a root past its record: the size check names its own reasoned `--write-baseline`. **Whether Node runs here is PROVEN, never proxied:** the ensure runs on a regular `package.json` at the root OR on any kit-seeded `scripts/*.mjs` already deployed; only when every probe answers absent does it report `skipped-no-node-evidence`, a line naming every probe it checked, while the config ensures still run; a probe that cannot be read is `failed` with the cause `node-evidence-unverifiable`, nothing written. **A `skipped-*` outcome whose stated reason this tool could itself disprove may not exist**. A deployed pre-commit hook takes a new installer body only when the installer next runs: the `enforcement` check line and apply, by the consent route, re-run it (it refuses a non-marker hook as always); until then `scripts/pre-commit.local` does not run.
45
+ **What the enforcement-script ensure does.** It judges every kit script of the kit folder `scripts/agent-workflow/` — each deployed `*.mjs` of `${CLAUDE_SKILL_DIR}/references/scripts/` but the spec layer's pairs, the test reporter and `run.mjs`, which the spec-layer ensure places first — once the component is accepted: a kit script outside the seed names (memory's own copies) stands in the kit folder as a regular file, or a regular file stands in `scripts/` under the old flat name of the hook installer. Each file by proof, with no question and no copy kept: a shipped prior is refreshed, an edited body replaced (its line names where a lasting edit goes), an absent file placed, the current body left. The hook installer goes first; a closing line says the commit hook runs the files written. On a declined enforcement offer, a project with Node evidence gets every seed file, the decisions rotator and the modules it imports, kept current (an absent one placed); the run places no other kit script (one line says so) and words that hook-run line as a condition. **The ADR store, after the writes:** where the run judged the rotator, it runs the kit folder's rotator with `--ensure-current`, with no question, which brings the store current (an older layout moved) or writes nothing; its lines are relayed under `ADR store: `. A rotator that does not bring the store current is `failed` / `adr-store-not-current`, the scripts written above staying as written: its refusal stops the upgrade. **The move from the flat layout, the run's last act.** A deployment of an earlier release holds the kit's old files flat in `scripts/` (the names of `PRIOR_FILES` in `${CLAUDE_SKILL_DIR}/tools/script-priors.mjs`). After every write landed and the store run passed, and only while `scripts/agent-workflow/run.mjs` stands, each `scripts/<name>` of those names whose bytes are a body this kit shipped is removed, `scripts/<name>: removed — the kit's scripts live in scripts/agent-workflow/`, when its replacement `scripts/agent-workflow/<path>` stands or it has none (a suite, the test-support file, the gate migration); one whose replacement is not placed yet is kept with its line and waits for the next run, and so is every old file while `run.mjs` does not stand (under `--only scripts` the spec-layer ensure does not place it). A file whose bytes differ from every body this kit shipped is the user's, named and left, never written or removed; a link, a directory, an unreadable file or a failed unlink is named and left. A removal counts as `refreshed`; `--dry-run` removes nothing and prints what would be removed. After a removal the run prints one line per regular `scripts/*.test.mjs` left that is not the kit's (a suite of the user's own, which the kit's hook does not run: wire it with `node --test scripts/<file>` in `scripts/pre-commit.local`); inside a git work tree one `git grep` line over the old names, the kit folder excluded, and its boundary line (the hooks dir and ignored files are the user's to check), outside one a line saying so; and, in a visible deployment, one line to commit `scripts/agent-workflow/`, the removed files and, as the upgrade changed them, `docs/ai/gates.json` and `package.json` as one change, merged into every branch still committed or installed on. **Edit each grep hit in this upgrade:** a `node scripts/<file>` of a kit check becomes `node scripts/agent-workflow/run.mjs <name>` with its arguments; a path of a deployed file becomes `scripts/agent-workflow/<path>`; a suite and the test-support file have no deployed path (a suite of the user's own is the suite line's, and a file of the user's importing the support file keeps a copy under a name of its own); a hit of the gate migration is row 4's registry `gates-migration` command, never a path under the kit folder; a record in `docs/ai/source-size.json` is regenerated by the size check's `--write-baseline`. Edit `package.json`'s scripts in this upgrade too (the documented wiring of `contracts.md`): a `prepare` script fails at Node's cannot-find-module until then. Row 4's migration switches the old gates and the `hook-checks` item switches the managed commit hook. **What stays open:** a no on the hook item leaves every commit stopped at Node's error naming a removed file until the item is applied or `node scripts/agent-workflow/run.mjs install-git-hooks` is run; a gate row 4 keeps is named with its own line and runs as declared until that line is acted on; the hooks dir (another hook of the user's) and ignored files are outside the printed line; a checkout without the kit folder commits under the hook's checkout line and installs through its own old installer, which refuses the clone's name-free hook (exit 1, so a `prepare` there fails) until it takes the move; in a project named `agent-workflow` the new hook carries the old installer's marker, so that installer rewrites the hook to the old paths instead, and every commit of a moved checkout stops at Node's error naming a removed file until `node scripts/agent-workflow/run.mjs install-git-hooks`, run in a moved checkout, writes it back. The suite and grep lines print once, on the run that removed: an upgrade stopped after that run and before these edits finishes them from this paragraph — wire each regular `scripts/*.test.mjs` outside the names of `PRIOR_FILES` as a suite, and search with `git grep -n -F --untracked -e <name> … -- . ':!scripts/agent-workflow'`, one `-e` per name of `PRIOR_FILES`. Where the size practice measures `scripts/`, a write may grow a root past its record: the size check names its own reasoned `--write-baseline`. **Whether Node runs here is PROVEN, never proxied:** Node evidence is a regular root `package.json`, or a regular file, every folder above it a plain directory, at one of the kit's flat script names in `scripts/` or at a deployed path in `scripts/agent-workflow/`; `skipped-no-node-evidence` only when the probe finds none, a line naming every probe it checked, while the config ensures still run; a probe that cannot be read is `failed` with the cause `node-evidence-unverifiable`, nothing written. **A `skipped-*` outcome whose stated reason this tool could itself disprove may not exist**. A deployed pre-commit hook takes a new installer body only when the installer next runs: the `enforcement` check line and apply, by the consent route, re-run it (it refuses a non-marker hook as always); until then `scripts/pre-commit.local` does not run.
46
46
 
47
47
  **What the navigator ensure does.** `docs/ai/index.md` is the always-loaded navigator the entry point declares, and it is GENERATED — no template ships it, so a deployment that never ran the generator boots from a broken entry point (and a Node project's hook fails its index check). The ensure runs the bundled generator's finalizer and reports `regenerated` (it was missing or stale — it was written) or `already-current` (nothing written); under a hook module that is not the bundled one, a write the project's own checker rejects is put back → `customized-preserved`. It never skips a No-Node project: the generator runs from `${CLAUDE_SKILL_DIR}/references/scripts/` on the agent host, not from the project's `scripts/`. **Its position in the run-list is EARLY and therefore NOT authoritative** — the `tier` offer (and, on the migrated path, steps 6–7) may still change `docs/ai` afterwards — so the authoritative run is the LATE `--only index` rung documented at both exits; the early one is idempotent: an untouched tree changes nothing.
48
48
 
49
- **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. The four pair files follow the enforcement-script rule, with no question and no copy kept: a shipped prior is refreshed (an append-only digest catalog), an edited body replaced (its line names where a lasting edit goes), an absent file placed, the current body left. In ONE order: the reader pair, then the checker pair, then the store root, seeded create-only from the bundled template, date rendered — an older checker renders the store row by row and reds the hook's `--check-index`, so the checker is written first, and a write that fails stops every later one. A closing line says a commit hook that runs the files written may stop the next commit. One token by precedence: `seeded` > `refreshed` > `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.
49
+ **What the spec-layer ensure does.** A deployment older than the feature-spec layer lacks the kit folder's spec reader and `docs/ai/specs/index.md`, and its deployed `check-docs-size.mjs` predates the store collapse. The spec layer's files in `scripts/agent-workflow/` — the three it deploys, `spec-schema/spec-schema.mjs`, `spec-schema/index.mjs` and `docs-size/check-docs-size.mjs`, no suite among them — the files they import, the test reporter `scripts/agent-workflow/test-reporter/reporter.mjs` and the stable kit command `scripts/agent-workflow/run.mjs`, which runs it, follow the enforcement-script rule, with no question and no copy kept: a shipped prior is refreshed (an append-only digest catalog), an edited body replaced (its line names where a lasting edit goes), an absent file placed, the current body left. This ensure runs before the enforcement-script ensure, so those files, the reporter and `run.mjs` stand before that ensure judges the kit folder and removes the old flat files. In ONE order: the reader, then the checker, then the test reporter, then `run.mjs`, then the store root, seeded create-only from the bundled template, date rendered — an older checker renders the store row by row and reds the hook's `--check-index`, so the checker is written first, and a write that fails stops every later one. A closing line says a commit hook that runs the files written may stop the next commit. One token by precedence: `seeded` > `refreshed` > `already-present`; Node evidence is a regular root `package.json`, or a regular file, every folder above it a plain directory, at one of the kit's flat script names in `scripts/` or at a deployed path in `scripts/agent-workflow/`; `skipped-no-node-evidence` only when the probe finds none (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.
50
50
 
51
51
  **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.
52
52
 
53
- **`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).
53
+ **`gates-migration` — legacy gates.json migration (the mandatory move — D8).** An EXISTING declaration may still carry the retired review-ledger / fold-completeness checks or a gate an earlier kit wrote. The step runs the migration with `--apply`, writing every move with no question, atomically, each acted row printed with its `was:`: a canonical legacy entry (matched by its documented single-invocation cmd form) is REMOVED when its target is proven absent, else named CUSTOMIZED; the canonical `unit-tests` cmd gains the stable kit command (`node scripts/agent-workflow/run.mjs unit-tests`, which adds the lcov reporter and the kit test reporter), a hand-written `node --test <paths>` included, and a gate an earlier kit wrote (`node --test` with its reporter flag set, under any id) is SWITCHED to it — both only while the kit folder holds this kit's command and reporter, which the `configs` step above places, else the gate is KEPT with one line naming the path and its remedy; a declared coverage-check gate is moved last. The new lcov can turn a declared checker that read no producer live, so a plain run that read green may read red after the move. **The coverage check is optional and rides a PRODUCER**: over a producer with no checker the step prints one OFFER line, and only on the user's explicit yes run it (`--apply --add-checker`, the checker added last); with no producer it is withheld, and an already-declared one with none before it is named with the fact and the remedy (`${CLAUDE_SKILL_DIR}/references/modes/gates.md`) — nothing is ever removed for you. CUSTOMIZED entries are NEVER auto-touched: each is named 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).
54
54
 
55
55
  **`bridges` — placed-bridge refresh — stamp-independent, same gate, BEFORE the equal-head short-circuit.** Run
56
56
  `node ${CLAUDE_SKILL_DIR}/tools/setup-backends.mjs --refresh-placed` and **paste its per-bridge
@@ -88,7 +88,7 @@ Requires: ${CLAUDE_SKILL_DIR}/references/shared/report-footer.md · ${CLAUDE_SKI
88
88
  **The LATE navigator finalizer — the AUTHORITATIVE run, after the last `docs/ai` mutation.** The `tier` offer above may write `docs/ai`, so the step-3 index ensure may be behind by the time the run-list ends. Re-run that ONE op here, before the step-4 report: `node ${CLAUDE_SKILL_DIR}/tools/ensure-configs.mjs --reconcile --only index --cwd <project>`. Relay **this** line in the report (it supersedes the early one; an untouched tree changes nothing, a failure STOPs the upgrade like any other ensure). On the migrated path the same rung runs again at the END of step 7 — after the migrations, before the step-8 re-stamp.
89
89
  4. **Equal-head exit — a real successful-exit report, not a bare stop.** If the stamp **equals** the head, the lineage is up to date — but step 3 (the stamp-independent reconciles) ran first and may have changed things, so this is a proper exit report, not a no-op:
90
90
  - **A skip line that contradicts the observed tree is a FINDING, never pasted as neutral.** Every ensure skip names the fact it proved (the probes that answered absent); if the tree you can see disproves that reason — a "no Node" skip beside deployed Node scripts, a "not deployed" skip beside a stamped `docs/ai` — do not relay the line as an outcome: raise it in the report as a defect of the tool, with the contradicting fact named, and stop short of any step that would build on the skip.
91
- - **Report step 3's outcome in plain language** — the kit block (`entry-block`): whether it was *added* at the start of the file, was *already current* (nothing changed) or was *written* with the current kit text (its route: text of your own goes outside the two workflow:kit comment lines; a change to a kit rule goes in its theme's file under docs/ai/rules/local/), with each `note:` line about a text the engine does not supply; the **nine project-configuration ensure** (`configs`) lines exactly as the one ensure run composed them (the ensures and their outcome tokens are enumerated in step 3), each rendered in plain language: what was created, what was left exactly as the user wrote it, and — for a `failed` line — what stopped it; for the navigator, relay the **late** `--only index` line, not the early one; the **`gates-migration`** result — *nothing to migrate*, the shown plan *applied* on your explicit yes, or the plan *left unapplied* (consent not given), with any INERT checker or CUSTOMIZED entries named; the **placed-bridge refresh** (`bridges`) outcome — paste the tool's per-bridge lines verbatim (they are already plain: *refreshed* / *already current* / *skipped — not placed* / `skipped-readonly` with its re-scan verdict / *could not refresh* + recovery); the **full-flow offer** (`tier`) lines; the **bridge-settings reconcile** (`bridge-settings`) outcome (paste the tool's line(s) verbatim); and, for a hidden deployment, whether the hidden-mode footprint (`footprint`) was *moved to project-local*, was *already project-local* (nothing changed), or needed a question (ambiguous visibility). Plain wording only — never the reconcile/slot/anchor/marker terms (the never-leak-kit-internals Gotcha — `${CLAUDE_SKILL_DIR}/references/shared/deploy-tail.md`).
91
+ - **Report step 3's outcome in plain language** — the kit block (`entry-block`): whether it was *added* at the start of the file, was *already current* (nothing changed) or was *written* with the current kit text (its route: text of your own goes outside the two workflow:kit comment lines; a change to a kit rule goes in its theme's file under docs/ai/rules/local/), with each `note:` line about a text the engine does not supply; the **nine project-configuration ensure** (`configs`) lines exactly as the one ensure run composed them (the ensures and their outcome tokens are enumerated in step 3), each rendered in plain language: what was created, what was left exactly as the user wrote it, and — for a `failed` line — what stopped it; for the navigator, relay the **late** `--only index` line, not the early one; the **`gates-migration`** result — *nothing to migrate*, or the moves *written*, each with its `was:`, with any KEPT gate, CUSTOMIZED entry, checker fact or the OFFER of the coverage check named; the **placed-bridge refresh** (`bridges`) outcome — paste the tool's per-bridge lines verbatim (they are already plain: *refreshed* / *already current* / *skipped — not placed* / `skipped-readonly` with its re-scan verdict / *could not refresh* + recovery); the **full-flow offer** (`tier`) lines; the **bridge-settings reconcile** (`bridge-settings`) outcome (paste the tool's line(s) verbatim); and, for a hidden deployment, whether the hidden-mode footprint (`footprint`) was *moved to project-local*, was *already project-local* (nothing changed), or needed a question (ambiguous visibility). Plain wording only — never the reconcile/slot/anchor/marker terms (the never-leak-kit-internals Gotcha — `${CLAUDE_SKILL_DIR}/references/shared/deploy-tail.md`).
92
92
  - **Never surface the structure number on this exit.** Whatever step 3 did, do **not** recite the `docs/ai` structure version, the internal versioning vocabulary, or the two-axes note here — the number is inert on an equal-head exit; it belongs to *Version disclosure* in `${CLAUDE_SKILL_DIR}/references/shared/report-footer.md` (shown at the never-downgrade STOP, the explicit status view, or on an explicit ask). Frame the success itself per the final bullet: if step 3 changed anything, say **what changed** in plain human terms; only a pure zero-diff no-op is *settings already current — no update needed*.
93
93
  - **Render the mandatory Recommendations section — on this exit too, BEFORE the footer.** Run `node ${CLAUDE_SKILL_DIR}/tools/recommendations.mjs --cwd <project-root>` and PRESENT its output — from the `## Recommendations (agent-workflow)` header — in the user's conversational language: every fact, count and item from the tool, nothing added or dropped; commands, paths, hosts and rule strings byte-exact; show the raw tool block on request. The section is present-even-when-empty (with everything optimal the body is exactly `no recommendations — flow optimal.`) and VERDICT-FIRST — the composed verdict line renders from the frozen templates `{K} item(s) need attention` / `nothing is broken` / `{N} optional recommendation(s), apply any you want` / `optimality NOT attested — {M} probe check(s) skipped`. Then apply each kit item by the kit route, with no question: its check line in the sandbox, then at once its apply line once outside it. Then OFFER the consent route: the user picks items in plain language; surface each picked item's posture note and get the explicit confirm; run its lane's rendered lines — chat: the one-liner; harness: the check line, then on the yes to its result the apply line; user: the user's own step — per the full consent route in `${CLAUDE_SKILL_DIR}/references/modes/recommendations.md`. Pinned order on this exit: Recommendations block → optional applies → report footer → the commit ask (the advisor/apply lane never lands after the commit ask).
94
94
  - **Recommendations lanes — both exits.** The four lanes (`chat`, `harness`, `kit`, `user`), the consent route and the kit route live in `${CLAUDE_SKILL_DIR}/references/modes/recommendations.md`; `init` stays a route the user may take.
@@ -19,7 +19,7 @@
19
19
  // Dependency-free (one sibling import for the shared failure shape), Node >= 22. No side effects on
20
20
  // import.
21
21
 
22
- import { fail } from './markdown-blocks.mjs';
22
+ import { fail } from '../shared/index.mjs';
23
23
 
24
24
  // Each tier carries its OWN remedy, because the three run out of room for different reasons and one
25
25
  // piece of advice is wrong for two of them: COLD is already sharded per month, and WARM is a window
@@ -39,25 +39,23 @@
39
39
  // --today=YYYY-MM-DD (default today UTC) — useful for tests / reproducible runs
40
40
 
41
41
  import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, realpathSync } from 'node:fs';
42
- import { dirname, resolve, basename } from 'node:path';
42
+ import { resolve, basename } from 'node:path';
43
43
  import { fileURLToPath } from 'node:url';
44
- import { tokenizeMarkdown, findParagraphBreak, fail } from './markdown-blocks.mjs';
44
+ import { tokenizeMarkdown, findParagraphBreak, fail, findProjectRoot } from '../shared/index.mjs';
45
45
  import { capFor, countLines, shardingWarning } from './archive-caps.mjs';
46
46
 
47
- const __filename = fileURLToPath(import.meta.url);
48
- const __dirname = dirname(__filename);
49
- const ROOT = resolve(__dirname, '..');
47
+ const ROOT = findProjectRoot(import.meta.url);
50
48
 
51
- const readProjectName = () => {
49
+ export const readProjectName = (root) => {
52
50
  try {
53
- const pkg = JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf8'));
51
+ const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));
54
52
  if (pkg.name) return pkg.name;
55
53
  } catch {
56
54
  /* no package.json — fall back to repo dir basename */
57
55
  }
58
- return basename(ROOT);
56
+ return basename(root);
59
57
  };
60
- const PROJECT_NAME = readProjectName();
58
+ const PROJECT_NAME = readProjectName(ROOT);
61
59
 
62
60
  const CHANGELOG_REL = 'docs/ai/changelog.md';
63
61
  const HISTORY_REL = 'docs/ai/history';
@@ -83,7 +83,7 @@
83
83
  // destructive --migrate --apply writes a durable snapshot to the git dir (uncommittable, the
84
84
  // review-receipts precedent) BEFORE any delete, with a stated out-of-tree fallback off git.
85
85
  //
86
- // Dependency-free, Node >= 22. Deployed into a consumer's scripts/ like its siblings.
86
+ // Dependency-free, Node >= 22. Deployed at a consumer's scripts/agent-workflow/archives/ like its siblings.
87
87
 
88
88
  import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync, readdirSync, rmSync, statSync, realpathSync, openSync, fsyncSync, closeSync } from 'node:fs';
89
89
  import { dirname, resolve, join, posix, relative, isAbsolute } from 'node:path';
@@ -91,10 +91,12 @@ import { fileURLToPath } from 'node:url';
91
91
  import { spawnSync } from 'node:child_process';
92
92
  import { createHash, randomBytes } from 'node:crypto';
93
93
  import { tmpdir } from 'node:os';
94
- import { tokenizeMarkdown } from './markdown-blocks.mjs';
94
+ import { tokenizeMarkdown, findProjectRoot } from '../shared/index.mjs';
95
95
 
96
96
  const __dirname = dirname(fileURLToPath(import.meta.url));
97
- const DEFAULT_ROOT = resolve(__dirname, '..');
97
+ const DEFAULT_ROOT = findProjectRoot(import.meta.url);
98
+ // The command this rotator prints for itself is the stable kit command (spec kit-command).
99
+ const SELF = 'node scripts/agent-workflow/run.mjs archive-decisions';
98
100
 
99
101
  export const HOT_REL = 'docs/ai/decisions.md';
100
102
  // The retired monolith tiers — still READ during migration (their entries explode into records) and
@@ -888,16 +890,17 @@ export const writeSnapshot = (root, files, deps = {}) => {
888
890
  };
889
891
 
890
892
  // ── index regeneration (item (h) — reuse the ONE generator in check-docs-size.mjs) ──────
893
+ // A declared spawn edge to the docs-size module's CLI, resolved from this file's own directory — never an import.
891
894
 
892
- const CHECK_DOCS_SIBLING = resolve(__dirname, 'check-docs-size.mjs');
893
- const INDEX_INSTRUCT = 'run `node scripts/check-docs-size.mjs --write-index` to refresh docs/ai/index.md';
895
+ const CHECK_DOCS_SIBLING = resolve(__dirname, '..', 'docs-size', 'check-docs-size.mjs');
896
+ const INDEX_INSTRUCT = 'run `node scripts/agent-workflow/run.mjs docs-size --write-index` to refresh docs/ai/index.md';
894
897
 
895
898
  export const defaultRegenerateIndex = (root, today, deps = {}) => {
896
899
  const exists = deps.existsSync ?? existsSync;
897
900
  const spawn = deps.spawnSync ?? spawnSync;
898
901
  const sibling = deps.sibling ?? CHECK_DOCS_SIBLING;
899
902
  if (!exists(sibling)) {
900
- return { ok: false, detail: `the index generator is not beside this script — ${INDEX_INSTRUCT}` };
903
+ return { ok: false, detail: `the index generator is not beside this script — an upgrade places the docs checker; then ${INDEX_INSTRUCT}` };
901
904
  }
902
905
  const r = spawn(process.execPath, [sibling, '--write-index', '--report', `--root=${root}`, `--today=${today}`], { encoding: 'utf8' });
903
906
  if (r.error || r.status !== 0) {
@@ -1187,7 +1190,7 @@ const runCheck = (root, today, log, logError) => {
1187
1190
  // absent) is a half-migrated / half-deleted tree, never a clean "no substrate" skip.
1188
1191
  const present = monolithsPresent(root);
1189
1192
  if (present.length > 0) {
1190
- logError(`[archive-decisions] FAIL: legacy monolith present (${present.join(', ')}) — the ADR store is half-migrated; run \`node scripts/archive-decisions.mjs --migrate --apply\` first.`);
1193
+ logError(`[archive-decisions] FAIL: legacy monolith present (${present.join(', ')}) — the ADR store is half-migrated; run \`${SELF} --migrate --apply\` first.`);
1191
1194
  return 1;
1192
1195
  }
1193
1196
  if (!hasHot && !hasStore) {
@@ -1211,7 +1214,7 @@ const runCheck = (root, today, log, logError) => {
1211
1214
  // Arm B: the verdict names the parsed unit count, not just raw lines — with the loud parse
1212
1215
  // path, zero can only mean genuinely empty, never a populated file read as nothing.
1213
1216
  log(`[archive-decisions] ${HOT_REL}: ${hot.rawLines}/${hot.cap} lines, ${hot.entries.length} ADR(s) in the HOT window`);
1214
- if (hot.cap !== null && hot.rawLines > hot.cap) problems.push(`${HOT_REL} is over its cap (${hot.rawLines}/${hot.cap}) — run \`node scripts/archive-decisions.mjs\` to explode the oldest entries`);
1217
+ if (hot.cap !== null && hot.rawLines > hot.cap) problems.push(`${HOT_REL} is over its cap (${hot.rawLines}/${hot.cap}) — run \`${SELF}\` to explode the oldest entries`);
1215
1218
  }
1216
1219
  log(`[archive-decisions] ${ADR_DIR_REL}: ${adrEntries.length} record(s)`);
1217
1220
 
@@ -1222,7 +1225,7 @@ const runCheck = (root, today, log, logError) => {
1222
1225
  const expected = buildNavigator(corpus, existsSync(navPath) ? navLastUpdated(readFileSync(navPath, 'utf8')) : today);
1223
1226
  const onDisk = existsSync(navPath) ? readFileSync(navPath, 'utf8') : null;
1224
1227
  if (onDisk !== expected) {
1225
- problems.push(`${NAV_REL} is stale (out of sync with the ADR corpus) — run \`node scripts/archive-decisions.mjs --write-navigator\` and commit it`);
1228
+ problems.push(`${NAV_REL} is stale (out of sync with the ADR corpus) — run \`${SELF} --write-navigator\` and commit it`);
1226
1229
  }
1227
1230
 
1228
1231
  problems.push(...collectReferenceViolations(root, new Set(hotEntries.map((e) => e.id)), new Set(adrEntries.map((e) => e.id))));
@@ -1238,7 +1241,7 @@ const runCheck = (root, today, log, logError) => {
1238
1241
  const runRotate = (root, flags, today, deps, log, logError) => {
1239
1242
  const present = monolithsPresent(root);
1240
1243
  if (present.length > 0) {
1241
- logError(`[archive-decisions] FAIL: legacy monolith present (${present.join(', ')}) — the ADR store is half-migrated; run \`node scripts/archive-decisions.mjs --migrate --apply\` first (a default rotate never half-explodes).`);
1244
+ logError(`[archive-decisions] FAIL: legacy monolith present (${present.join(', ')}) — the ADR store is half-migrated; run \`${SELF} --migrate --apply\` first (a default rotate never half-explodes).`);
1242
1245
  return 1;
1243
1246
  }
1244
1247
  const plan = planRotation(root, today);
@@ -32,23 +32,22 @@
32
32
  // --today=YYYY-MM-DD (default UTC today)
33
33
 
34
34
  import { readFileSync, writeFileSync, mkdirSync, existsSync, realpathSync } from 'node:fs';
35
- import { dirname, resolve, basename } from 'node:path';
35
+ import { resolve, basename } from 'node:path';
36
36
  import { fileURLToPath } from 'node:url';
37
- import { tokenizeMarkdown, fail } from './markdown-blocks.mjs';
37
+ import { tokenizeMarkdown, fail, findProjectRoot } from '../shared/index.mjs';
38
38
 
39
- const __dirname = dirname(fileURLToPath(import.meta.url));
40
- const ROOT = resolve(__dirname, '..');
39
+ const ROOT = findProjectRoot(import.meta.url);
41
40
 
42
- const readProjectName = () => {
41
+ export const readProjectName = (root) => {
43
42
  try {
44
- const pkg = JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf8'));
43
+ const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));
45
44
  if (pkg.name) return pkg.name;
46
45
  } catch {
47
46
  /* no package.json — fall back to repo dir basename */
48
47
  }
49
- return basename(ROOT);
48
+ return basename(root);
50
49
  };
51
- const PROJECT_NAME = readProjectName();
50
+ const PROJECT_NAME = readProjectName(ROOT);
52
51
 
53
52
  const KNOWN_REL = 'docs/ai/known_issues.md';
54
53
  const HISTORY_REL = 'docs/ai/history';
@@ -29,11 +29,10 @@ import { existsSync, lstatSync, realpathSync } from 'node:fs';
29
29
  import { dirname, resolve, relative, join, basename, sep } from 'node:path';
30
30
  import { fileURLToPath } from 'node:url';
31
31
  import { randomBytes } from 'node:crypto';
32
- import { readSpecDocument, SPECS_COLLAPSE } from './spec-schema.mjs';
32
+ import { readSpecDocument, SPECS_COLLAPSE } from '../spec-schema/index.mjs';
33
+ import { findProjectRoot } from '../shared/index.mjs';
33
34
 
34
- const __filename = fileURLToPath(import.meta.url);
35
- const __dirname = dirname(__filename);
36
- const ROOT = resolve(__dirname, '..');
35
+ const ROOT = findProjectRoot(import.meta.url);
37
36
  const DOCS_DIR = resolve(ROOT, 'docs/ai');
38
37
  const INDEX_PATH = resolve(DOCS_DIR, 'index.md');
39
38
 
@@ -0,0 +1,2 @@
1
+ // The docs-size module's one door (spec script-family): the frontmatter reader the kit's tools import.
2
+ export { parseFrontmatter } from './check-docs-size.mjs';
@@ -0,0 +1,45 @@
1
+ {
2
+ "schema": 1,
3
+ "entries": [
4
+ { "path": "family.mjs", "role": "skill-home" },
5
+ { "path": "family.test.mjs", "role": "suite" },
6
+ { "path": "run.mjs", "role": "deployed", "seed": false },
7
+ { "path": "run.test.mjs", "role": "suite" },
8
+ { "path": "docs-size/check-docs-size.mjs", "role": "deployed", "seed": false },
9
+ { "path": "docs-size/index.mjs", "role": "skill-home" },
10
+ { "path": "docs-size/check-docs-size.test.mjs", "role": "suite" },
11
+ { "path": "docs-size/check-docs-size-cli.test.mjs", "role": "suite" },
12
+ { "path": "docs-size/check-docs-size-ensure.test.mjs", "role": "suite" },
13
+ { "path": "spec-schema/spec-schema.mjs", "role": "deployed", "seed": false },
14
+ { "path": "spec-schema/index.mjs", "role": "deployed", "seed": false },
15
+ { "path": "spec-schema/spec-schema.test.mjs", "role": "suite" },
16
+ { "path": "archives/archive-changelog.mjs", "role": "deployed", "seed": false },
17
+ { "path": "archives/archive-issues.mjs", "role": "deployed", "seed": false },
18
+ { "path": "archives/archive-decisions.mjs", "role": "deployed", "seed": true },
19
+ { "path": "archives/archive-caps.mjs", "role": "deployed", "seed": false },
20
+ { "path": "archives/index.mjs", "role": "support" },
21
+ { "path": "archives/archive-changelog.test.mjs", "role": "suite" },
22
+ { "path": "archives/archive-issues.test.mjs", "role": "suite" },
23
+ { "path": "archives/archive-decisions.test.mjs", "role": "suite" },
24
+ { "path": "archives/archive-caps.test.mjs", "role": "suite" },
25
+ { "path": "archives/archive-conservation.test.mjs", "role": "suite" },
26
+ { "path": "archives/archiver-structure.test.mjs", "role": "suite" },
27
+ { "path": "git-hooks/install-git-hooks.mjs", "role": "deployed", "seed": false },
28
+ { "path": "git-hooks/install-git-hooks.test.mjs", "role": "suite" },
29
+ { "path": "git-hooks/install-git-hooks-repo-exec.test.mjs", "role": "suite" },
30
+ { "path": "gates/migrate-gates.mjs", "role": "skill-home" },
31
+ { "path": "gates/kit-command-gates.mjs", "role": "skill-home" },
32
+ { "path": "gates/migrate-gates.test.mjs", "role": "suite" },
33
+ { "path": "gates/migrate-gates-branches.test.mjs", "role": "suite" },
34
+ { "path": "gates/kit-command-gates.test.mjs", "role": "suite" },
35
+ { "path": "shared/markdown-blocks.mjs", "role": "deployed", "seed": true },
36
+ { "path": "shared/project-root.mjs", "role": "deployed", "seed": true },
37
+ { "path": "shared/index.mjs", "role": "deployed", "seed": true },
38
+ { "path": "shared/markdown-blocks.test.mjs", "role": "suite" },
39
+ { "path": "shared/project-root.test.mjs", "role": "suite" },
40
+ { "path": "test-reporter/reporter.mjs", "role": "deployed", "seed": false },
41
+ { "path": "test-reporter/reporter.test.mjs", "role": "suite" },
42
+ { "path": "test-support/_expect-shim.mjs", "role": "support" },
43
+ { "path": "test-support/index.mjs", "role": "support" }
44
+ ]
45
+ }
@@ -0,0 +1,90 @@
1
+ // family.mjs — the one reader of the script family's manifest (spec script-family).
2
+ //
3
+ // family.json lists every file of this tree but itself: its path relative to the tree, its role and, on a
4
+ // deployed entry alone, whether the rotator needs it to load (seed). readFamily returns the entries frozen, in
5
+ // the manifest's order, or throws an error naming the manifest's path, the offending field and the one cause —
6
+ // a strict config: an unknown key, a missing field or a value outside its grammar is refused, never guessed.
7
+ // Dependency-free, Node >= 22. No side effects on import.
8
+
9
+ import { readFileSync } from 'node:fs';
10
+ import { dirname, join } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+
13
+ const HERE = dirname(fileURLToPath(import.meta.url));
14
+
15
+ export const FAMILY_FILE = 'family.json';
16
+ export const FAMILY_ROLES = Object.freeze(['deployed', 'skill-home', 'suite', 'support']);
17
+
18
+ const SCHEMA = 1;
19
+ const TOP_KEYS = ['schema', 'entries'];
20
+ const ENTRY_KEYS = ['path', 'role', 'seed'];
21
+ const TOP_FILES = new Set(['family.mjs', 'family.test.mjs', 'run.mjs', 'run.test.mjs']);
22
+ const MODULES = new Set(['docs-size', 'spec-schema', 'archives', 'git-hooks', 'gates', 'shared', 'test-support', 'test-reporter']);
23
+ const FILE_NAME = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
24
+
25
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
26
+
27
+ // A path is one of the top-level files, or <module>/<file> with the module one of the eight.
28
+ const inGrammar = (path) => {
29
+ const parts = path.split('/');
30
+ if (parts.length === 1) return TOP_FILES.has(path);
31
+ return parts.length === 2 && MODULES.has(parts[0]) && FILE_NAME.test(parts[1]);
32
+ };
33
+
34
+ const checkKeys = (object, keys, where, refuse) => {
35
+ const unknown = Object.keys(object).find((key) => !keys.includes(key));
36
+ if (unknown !== undefined) refuse(`${where}${unknown}`, `unknown key (allowed: ${keys.join(', ')})`);
37
+ };
38
+
39
+ const readEntry = (raw, at, seen, refuse) => {
40
+ const where = `entries[${at}]`;
41
+ if (!isObject(raw)) refuse(where, 'an entry must be an object');
42
+ checkKeys(raw, ENTRY_KEYS, `${where}.`, refuse);
43
+ for (const field of ['path', 'role']) {
44
+ if (!(field in raw)) refuse(`${where}.${field}`, 'missing');
45
+ if (typeof raw[field] !== 'string') refuse(`${where}.${field}`, 'must be a string');
46
+ }
47
+ const { path, role } = raw;
48
+ if (!inGrammar(path)) {
49
+ refuse(`${where}.path`, `${JSON.stringify(path)} is outside the grammar (${[...TOP_FILES].join(', ')} or <module>/<file> of ${[...MODULES].join(', ')})`);
50
+ }
51
+ if (seen.has(path)) refuse(`${where}.path`, `duplicate ${JSON.stringify(path)}`);
52
+ seen.add(path);
53
+ if (!FAMILY_ROLES.includes(role)) refuse(`${where}.role`, `${JSON.stringify(role)} is not one of ${FAMILY_ROLES.join(', ')}`);
54
+ if (role === 'deployed') {
55
+ if (!('seed' in raw)) refuse(`${where}.seed`, 'missing on a deployed entry');
56
+ if (typeof raw.seed !== 'boolean') refuse(`${where}.seed`, 'must be a boolean');
57
+ } else if ('seed' in raw) {
58
+ refuse(`${where}.seed`, 'only a deployed entry carries a seed');
59
+ }
60
+ return Object.freeze({ path, module: path.includes('/') ? path.split('/')[0] : null, role, seed: raw.seed === true });
61
+ };
62
+
63
+ // The family of the manifest in `dir` (this reader's own directory when none is given).
64
+ export const readFamily = (dir = HERE) => {
65
+ const manifest = join(dir, FAMILY_FILE);
66
+ const refuse = (field, cause) => {
67
+ throw new Error(`${manifest}: ${field === null ? '' : `${field}: `}${cause}`);
68
+ };
69
+ let text;
70
+ try {
71
+ text = readFileSync(manifest, 'utf8');
72
+ } catch (error) {
73
+ refuse(null, `cannot read the manifest (${error.code ?? error.message})`);
74
+ }
75
+ let parsed;
76
+ try {
77
+ parsed = JSON.parse(text);
78
+ } catch (error) {
79
+ refuse(null, `not JSON (${error.message})`);
80
+ }
81
+ if (!isObject(parsed)) refuse(null, 'the top level must be an object');
82
+ checkKeys(parsed, TOP_KEYS, '', refuse);
83
+ for (const key of TOP_KEYS) if (!(key in parsed)) refuse(key, 'missing');
84
+ if (parsed.schema !== SCHEMA) refuse('schema', `must be ${SCHEMA}, got ${JSON.stringify(parsed.schema)}`);
85
+ if (!Array.isArray(parsed.entries)) refuse('entries', 'must be an array');
86
+ const seen = new Set();
87
+ const entries = parsed.entries.map((raw, at) => readEntry(raw, at, seen, refuse));
88
+ if (!entries.some((entry) => entry.role === 'deployed')) refuse(null, 'no deployed entry — a family that deploys nothing is no family');
89
+ return Object.freeze(entries);
90
+ };
@@ -0,0 +1,117 @@
1
+ // kit-command-gates.mjs — the gate migration's reading of a kit-check gate (spec kit-command): a matched gate over a
2
+ // current kit folder is switched to the stable kit command, any other form naming a check is named with its repoint.
3
+ // Dependency-free, Node >= 22. No side effects on import.
4
+
5
+ import { lstatSync, readFileSync } from 'node:fs';
6
+ import { dirname, join, posix } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { KIT_COMMANDS, KIT_COMMAND_PATH } from '../run.mjs';
9
+ import { readFamily } from '../family.mjs';
10
+
11
+ const TREE = dirname(dirname(fileURLToPath(import.meta.url)));
12
+ const KIT_FOLDER = dirname(KIT_COMMAND_PATH);
13
+ const SCRIPTS_FOLDER = dirname(KIT_FOLDER);
14
+ const COMMAND = `node ${KIT_COMMAND_PATH}`;
15
+
16
+ const fileNameOf = (path) => path.slice(path.lastIndexOf('/') + 1);
17
+ const NAME_BY_FILE = new Map(Object.entries(KIT_COMMANDS).map(([name, target]) => [fileNameOf(target), name]));
18
+ const flatOf = (target) => `${SCRIPTS_FOLDER}/${fileNameOf(target)}`;
19
+
20
+ // path token → { name, flat } for the deployed or the flat path of a known name, relative to the project root.
21
+ const KNOWN_PATHS = new Map(Object.entries(KIT_COMMANDS).flatMap(([name, target]) => [
22
+ [`${KIT_FOLDER}/${target}`, { name, flat: false }],
23
+ [flatOf(target), { name, flat: true }],
24
+ ]));
25
+
26
+ const SAFE_FLAG = /^--[A-Za-z0-9][A-Za-z0-9-]*$/;
27
+ const MATCHED = /^node +("[^"]*"|[^\s"]+)((?: +[^\s"]+)*)$/;
28
+ const CHECK_FILE = new RegExp(`(?<![A-Za-z0-9._-])(${[...NAME_BY_FILE.keys()].map((file) => file.replaceAll('.', '\\.')).join('|')})(?=$|[\\s"';&|<>()])`, 'g');
29
+
30
+ const unquoted = (token) => (token.length > 1 && token.startsWith('"') && token.endsWith('"') ? token.slice(1, -1) : token);
31
+
32
+ // The gate's one kit-check invocation, or null: `node`, one path token of a known name, then only safe `--` flags.
33
+ const matchOf = (cmd) => {
34
+ const found = MATCHED.exec(cmd.trim());
35
+ if (!found) return null;
36
+ const token = unquoted(found[1]).replace(/^\.\//, '');
37
+ const known = KNOWN_PATHS.get(token);
38
+ const flags = found[2].split(' ').filter(Boolean);
39
+ if (!known || !flags.every((flag) => SAFE_FLAG.test(flag))) return null;
40
+ return { ...known, token, args: flags };
41
+ };
42
+
43
+ // Every known name whose target's file name stands whole in the cmd and not as the end of its deployed path, one per occurrence.
44
+ const namedChecks = (cmd) => [...cmd.matchAll(CHECK_FILE)].flatMap((found) => {
45
+ const name = NAME_BY_FILE.get(found[1]);
46
+ return cmd.slice(0, found.index).endsWith(`agent-workflow/${posix.dirname(KIT_COMMANDS[name])}/`) ? [] : [name];
47
+ });
48
+
49
+ export const repointsOf = (gate) => namedChecks(gate.cmd).map((name) => ({ id: gate.id, repoint: `${COMMAND} ${name}` }));
50
+
51
+ // The first path, relative to the project, that keeps the name from being current — the command, its target and
52
+ // what the target loads — or null when it is.
53
+ const firstStaleKitPath = (projectDir, name) => {
54
+ const at = (path) => join(projectDir, ...path.split('/'));
55
+ const isPlain = (path, kind) => {
56
+ try {
57
+ const stat = lstatSync(at(path));
58
+ return kind === 'directory' ? stat.isDirectory() : stat.isFile();
59
+ } catch {
60
+ return false;
61
+ }
62
+ };
63
+ const folders = new Set();
64
+ for (const folder of [SCRIPTS_FOLDER, KIT_FOLDER]) {
65
+ if (!isPlain(folder, 'directory')) return folder;
66
+ folders.add(folder);
67
+ }
68
+ const deployedPaths = new Set(readFamily(TREE).filter((entry) => entry.role === 'deployed').map(({ path }) => path));
69
+ const needed = new Set([fileNameOf(KIT_COMMAND_PATH), KIT_COMMANDS[name]]);
70
+ for (const path of needed) {
71
+ const deployed = `${KIT_FOLDER}/${path}`;
72
+ const folder = dirname(deployed);
73
+ if (!folders.has(folder)) {
74
+ if (!isPlain(folder, 'directory')) return folder;
75
+ folders.add(folder);
76
+ }
77
+ if (!isPlain(deployed, 'file')) return deployed;
78
+ try {
79
+ const source = readFileSync(join(TREE, path));
80
+ if (!deployedPaths.has(path) || !readFileSync(at(deployed)).equals(source)) return deployed;
81
+ for (const found of source.toString('utf8').matchAll(/(?:\bfrom\s*|\bimport\s*(?:\(\s*)?)['"](\.[^'"\n]+)['"]/g)) needed.add(posix.join(posix.dirname(path), found[1]));
82
+ } catch {
83
+ return deployed;
84
+ }
85
+ }
86
+ return null;
87
+ };
88
+
89
+ const isAbsent = (path) => {
90
+ try { lstatSync(path); } catch (error) { return error.code === 'ENOENT'; }
91
+ return false;
92
+ };
93
+
94
+ export const planKitCommandGates = (gates, projectDir) => {
95
+ const read = gates.map((gate) => {
96
+ const cmd = gate !== null && typeof gate === 'object' && typeof gate.cmd === 'string' ? gate.cmd : '';
97
+ return { gate, match: matchOf(cmd), names: namedChecks(cmd) };
98
+ });
99
+ const namesToCheck = new Set(read.flatMap(({ match, names }) => match ? [match.name, ...names] : names));
100
+ const staleByName = new Map([...namesToCheck].map((name) => [name, firstStaleKitPath(projectDir, name)]));
101
+ const result = { gates: [], switched: [], withheld: [], repoints: [] };
102
+ for (const { gate, match, names } of read) {
103
+ const stale = match ? staleByName.get(match.name) : null;
104
+ if (stale !== null) {
105
+ if (match) result.withheld.push({ id: gate.id, path: stale });
106
+ result.gates.push(gate);
107
+ } else if (match && (!match.flat || isAbsent(join(projectDir, match.token)))) {
108
+ const cmd = [COMMAND, match.name, ...match.args].join(' ');
109
+ result.switched.push({ id: gate.id, cmd, was: gate.cmd });
110
+ result.gates.push({ ...gate, cmd });
111
+ } else {
112
+ for (const name of names) if (staleByName.get(name) === null) result.repoints.push({ id: gate.id, repoint: `${COMMAND} ${name}` });
113
+ result.gates.push(gate);
114
+ }
115
+ }
116
+ return result;
117
+ };