@sabaiway/agent-workflow-kit 14.46.0 → 14.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,38 @@ Semantically versioned ([semver](https://semver.org)), newest first. The `versio
4
4
  is the current release. `upgrade` mode reads a project's `docs/ai/.workflow-version` and applies
5
5
  every `migrations/<version>-<slug>.md` newer than it, in semver order.
6
6
 
7
+ ## 14.48.0 — the kit's decisions script brings an ADR store current in one command; a copy of its previous body is now a known earlier body (AD-200)
8
+
9
+ **`references/scripts/archive-decisions.mjs` is memory 8.5.0's script, byte for byte.** Its new `--ensure-current`
10
+ mode judges the ADR store before any write and brings it current (migrate, rotate, the navigator only when it
11
+ differs), writing nothing when it already is; every write it makes to a project file, in every mode, replaces that
12
+ file whole through a temporary file and a rename. Detail: memory's CHANGELOG, 8.5.0.
13
+
14
+ - **The previous body is now a known earlier body.** A `scripts/archive-decisions.mjs` as memory 8.1.3 to 8.4.0
15
+ shipped it is refreshed by the upgrade's `scripts` step with no question, unless the project is on an older ADR
16
+ layout, where the decisions files stay held back, or its ADR layout cannot be read. Without this row the new bundled
17
+ body would make that copy read as an edit, named in the replace block and kept aside on the yes.
18
+ - **Unchanged until a later release:** the upgrade does not run the new mode yet; its text, the `migrate-adr-store`
19
+ mode and the hold-back of the decisions files on an older ADR layout stay as they are.
20
+
21
+ MINOR: the mirrored mode and one catalog row.
22
+
23
+ ## 14.47.0 — the `hook-checks` item no longer replaces your hook installer; a hook line it left out names the upgrade (AD-199)
24
+
25
+ **Applying `hook-checks` no longer replaces your hook installer.** Before, its apply first replaced a
26
+ `scripts/install-git-hooks.mjs` an earlier release shipped with the kit's current one, and could put it in place
27
+ beside older installer tests. Since 14.46.0 the upgrade keeps every kit script current, so that replace only repeated
28
+ the upgrade's work, and it is gone:
29
+
30
+ - **`hook-checks` runs your installer as it stands.** Its preview prints no `refresh:` line, the apply itself writes
31
+ and restores no file (the installer still writes the hook), and the check before the apply refuses any write for
32
+ this item. Its note in the Recommendations mode no longer warns that the replace may grow a recorded size.
33
+ - **A hook line the installer left out names the upgrade.** When the installer exits 0 but the hook lacks a line the
34
+ `commit-guard` or `hook-checks` apply passed, the apply still exits 6, and its line now ends by naming
35
+ `/agent-workflow-kit upgrade`, which brings the installer to the kit's current body (a body a release shipped
36
+ refreshed with no question, any other kept aside and replaced on its one yes), then says to apply the item again. Before, the line called a refresh from the kit's copy your own step.
37
+ - Migration note 3.0.0 step 4 says the same.
38
+
7
39
  ## 14.46.0 — every upgrade keeps all the kit's scripts in your `scripts/` current, an edit kept aside and replaced on the one yes (AD-198)
8
40
 
9
41
  **A kit script in `scripts/` no longer stays stale or missing forever.** Before, the upgrade's `scripts` step
package/SKILL.md CHANGED
@@ -3,7 +3,7 @@ name: agent-workflow-kit
3
3
  description: Deploy or upgrade a portable AI-agent memory-and-workflow system in any project. Use when the user wants to bootstrap `docs/ai/` + an entry-point `AGENTS.md` (+ `CLAUDE.md` alias) + cap/archive/index enforcement in a new or existing repo, set up the Memory Map and session protocols, install the docs-rotation pre-commit hook, or run `/agent-workflow-kit` / `/agent-workflow-kit upgrade`. Triggers on phrases like "set up the memory system", "deploy the AI workflow here", "bootstrap docs/ai", "upgrade the workflow". New to the epic, story and task tier? Run `/agent-workflow-kit tier`. A typed decision with a confidence from Jev? Run `/agent-workflow-kit jev`.
4
4
  disable-model-invocation: true
5
5
  metadata:
6
- version: '14.46.0'
6
+ version: '14.48.0'
7
7
  ---
8
8
 
9
9
  # agent-workflow-kit
package/capability.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schema": 1,
4
4
  "name": "agent-workflow-kit",
5
5
  "kind": "composition-root",
6
- "version": "14.46.0",
6
+ "version": "14.48.0",
7
7
  "provides": [],
8
8
  "roles": {},
9
9
  "detect": {
@@ -27,11 +27,11 @@ loudly, never silently.
27
27
  advisor's `commit-guard` item arms the pre-commit hook: the agent applies it on the user's yes
28
28
  after its check, by the consent route of the Recommendations mode, and the apply reads the hook
29
29
  back to verify the arm took. A 2.x deployment's project-local `scripts/install-git-hooks.mjs`
30
- predates the arm, and the upgrade preserves existing scripts: an unarmed hook after the
31
- installer's exit 0 makes the apply exit 6 with one line naming the hook, and the item returns
32
- at the next run. A cmp -s against the kit's references/scripts/ copy tells whether the
33
- project's copy is the current one; a differing copy may be an older deploy or the user's own
34
- edit, and refreshing it is the user's own step.
30
+ predates the arm: an unarmed hook after the installer's exit 0 makes the apply exit 6 with
31
+ one line naming the hook and the guard line the installer left out, ending with the upgrade
32
+ route — `/agent-workflow-kit upgrade` keeps that installer aside and replaces it with the kit's
33
+ current body on its one yes (an installer this old is never refreshed without that yes) — and
34
+ the item returns at the next run.
35
35
  5. **Re-stamp:** init/upgrade re-stamps `docs/ai/.workflow-version` to 3.0.0.
36
36
 
37
37
  ## Verification
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sabaiway/agent-workflow-kit",
3
- "version": "14.46.0",
3
+ "version": "14.48.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",
@@ -38,7 +38,7 @@ A variant's posture note, where its key has one, is printed by `init` from this
38
38
  - `source-size` — the arms differ by what the declared gate IS. **`adopted-elsewhere`** — the gate runs a DIFFERENT real copy of this checker (a vendored deployment): the practice runs, the advisor cannot resolve it as its own sibling, and the realpath anchor does not widen (that stops a lookalike). So the convergence is the ack writer's preview (`--lane source-size-copy` → `sourceSizeCopyAck`), never `--adopt`, which would mint and then be refused by the fill on the declared id. The fingerprint binds the declared claims AS AUTHORED, sorted, not resolved paths, so a second external copy re-fires it. **`id-squatter`** — a gate carries the `source-size` id and is not this checker under any reading: it claims the practice while nothing measures module size, so it is the user's own step (rename the id, or repoint the cmd at this `--check`). **`unminted`**, for both copies: a gate refusing every run over an authored or incomplete record (over an absent one the check judges layout alone), attention, and NO acknowledgement silences it; only the verb differs (with the gate declared elsewhere, `--write-baseline`). **`schema-1`** — the check stops on a minted schema-1 config, so this arm comes first: its `--write-baseline` line carries NO reason (a pinned one would launder a raise; a raise riding the move refuses and you relay it), every run until the move. **`layout`** — on a config with no layout record, the record of the piles already there comes first, as its own item: a no writes nothing and the item returns every run; its `recipe:` line names the branch states, and `source-size.layout` is applied before the `hook-checks` check line runs, whose layout line follows that record. Risk profile: `docs/ai/gates.json` is a PRIVILEGED file, so every arm here either records an acknowledgement or hands you an edit — the kit declares nothing on its own.
39
39
  - `gate-hook` — the base arm is the ordinary opt-in wiring offer on the harness lane: the agent applies it on the chat yes after the check; `init` previews and applies it on the terminal yes as the route the user may take instead. The **`marker-stale`** arm is not: the placed hook validates your declaration through its OWN baked copy and goes dark on any key it does not know, so a declaration carrying the `lcovProducer` key under a hook that predates it silently turns auto-approval OFF, and every gate prompts again with no error anywhere. The condition is the key's PRESENCE, not its value: `"lcovProducer": false` darkens it exactly as `true` does. The arm is deliberately marker-scoped — a stale hook is otherwise harmless — and it is a harness item: its writer is `gate-hook --apply --reseed`, which replaces the placed hook with the bundled bytes in place (and wires the entry only while it is unwired), so the agent applies it on the chat yes after the check, whose result names the replaced file with the old and the new digest; `init` applies it on the terminal y as the route the user may take instead. When the read-lane is also enabled, this arm and `read-lane.stale` would report the same file with the same recovery, so exactly one renders — **this one**: a hook that postdates the read-lane and merely predates the marker key reads `lanes.json` perfectly well. Risk profile: one placed hook file replaced by the bundled runtime; the declaration is never touched.
40
40
  - `enforcement` — copies the bundled `references/scripts/*.mjs` runnable scripts and their tests, then runs the project's own hook installer, which installs the pre-commit hook. The lane is harness: the agent applies the item on the chat yes after the check, whose result shows each script the kit places with its bytes and the installer it runs with its bytes; `init` applies it on the batch terminal yes as the route the user may take instead. The copy is create-only: an existing file stands and nothing is written through a link, and the offer renders only when `scripts/` is absent or a plain directory contains no bundled basename. The hook invokes `node` directly, so a committer without it on PATH gets a loud failure. The installer refuses to overwrite a pre-commit hook it did not write: an install it refuses removes the scripts this apply copied, and the item is offered again with the installer's output shown; over a pre-commit hook the installer did not write the item is not offered — its skip names the user's own step. Risk profile: local tooling and a Git hook are added on the chat yes after the check, or on init's y.
41
- - `hook-checks` — the agent applies the item on the chat yes after the check, refreshing a known-prior installer to the kit's before the installer arms its planned lines; `init` applies it on the terminal y as the route the user may take instead. Risk profile: future commits stop on the rules check and, where judged, on the size check's findings — lines, aggregate and layout; where the size practice measures `scripts/`, the refresh may grow past a recorded size, and the next check stops until that growth is recorded with a reason; over a clone with no pre-commit hook the installer writes its whole hook, so commits also stop on its docs, archive and `scripts/` test lines.
41
+ - `hook-checks` — the agent applies the item on the chat yes after the check; `init` applies it on the terminal y as the route the user may take instead. Risk profile: future commits stop on the rules check and, where judged, on the size check's findings — lines, aggregate and layout; over a clone with no pre-commit hook the installer writes its whole hook, so commits also stop on its docs, archive and `scripts/` test lines.
42
42
  - `attribution` — the agent applies the item on the chat yes after the check, setting one key in the project `.claude/settings.json`; `init` applies it on the terminal y as the route the user may take instead. An existing "includeCoAuthoredBy": false already converges the item unless an "attribution" key sets a commit or PR text; a local-scope override is the user's own edit. Risk profile: one settings key, nothing widened.
43
43
  - `footprint-global` — the agent applies the item on the chat yes after the check, which prints each line it removes; `init` applies it on the terminal y as the route the user may take instead. Another of the user's repositories may rely on the same lines: a no keeps the block, and the item returns at the next run. The apply prints the removed lines as a backup. Risk profile: lines removed from the machine-global excludes file.
44
44
  - `mcp-channel` — the offer is to REGISTER the kit's read-only stdio MCP server in this project on the harness lane: a registration is a command your MCP client will RUN. The agent applies it on the chat yes after the check; `init` previews the exact entry and applies it on the terminal y as the route the user may take instead. What the registration buys: path questions and literal searches become typed tool calls whose arguments are named JSON fields instead of a string handed to a shell, so a pipe, a redirect or a quote inside a pattern or a path stays DATA and is never interpreted. Posture: the server is a **read-only child of your client** (path/type/size/line facts and literal search over this project root; no write and no exec API), and like the client itself it runs **outside the Bash sandbox** — the sandbox is not what bounds it, the server's own root containment is. The two allow rules it adds make those two tools promptless and nothing else. The **`.differing`** arm is also a harness item: an `agent-workflow` entry already stands in `.mcp.json` and **structurally differs** from what this kit copy would write (another kit copy, a hand-edited path, an added `env`; the comparison ignores key order, so re-serialized identical bytes are the same registration). The check shows the entry standing in `.mcp.json` and the entry it would write; the chat yes confirms the replacement. `init` previews `mcp --replace` and replaces only on the terminal y. Stated limit: this item does **not** detect a `disabledMcpjsonServers` veto, so a converged `mcp-channel` means *what the mode writes is in place*, not *the client will load it* — see `${CLAUDE_SKILL_DIR}/references/modes/mcp.md`. Risk profile: a new read-only channel your client will launch; no write or exec exposure; a differing registration is replaced only on the checked chat yes or the terminal y and every other declaration is kept.
@@ -44,8 +44,18 @@
44
44
  // earn a go-ahead without risking a partial write.
45
45
  // --dry-run print the planned rotation move-set + inbound-rewrite set (file:line, old
46
46
  // target → new target), change nothing.
47
+ // --ensure-current bring the store current, alone: judge it before any write by the functions above
48
+ // (migrate a monolith, rotate a HOT window over its cap, write the navigator only
49
+ // when it differs, refuse a dead reference the moves would not cure), write, and
50
+ // close with an in-process --check. Exit 0 (the last stdout line `already-current`
51
+ // or `brought-current: <actions>`), 1 (no work-tree file changed), 3 (a file
52
+ // changed, then the run failed), 2 (usage).
47
53
  // --today=YYYY-MM-DD pin the lastUpdated stamp (tests / reproducible runs).
48
54
  //
55
+ // Every project-file write replaces its file whole: a temporary file beside it (named after it, never ending
56
+ // in .md), then one rename. The fs seams for tests: deps.writeFileSync (each file written), deps.renameSync
57
+ // (each rename), deps.rmSync (each removal), deps.fsyncSync (each sync) — node:fs when absent.
58
+ //
49
59
  // Reference-scan boundary + stated limitations: the inbound-link scan covers docs/ai/** ONLY (links
50
60
  // in README / agent entry points are out of scope); the ADR corpus surfaces themselves are NEVER
51
61
  // rewritten — a rewrite-form link to a moved id inside decisions.md, an adr/ record or a monolith
@@ -75,11 +85,11 @@
75
85
  //
76
86
  // Dependency-free, Node >= 22. Deployed into a consumer's scripts/ like its siblings.
77
87
 
78
- import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, rmSync, statSync, realpathSync } from 'node:fs';
79
- import { dirname, resolve, join, posix } from 'node:path';
88
+ import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync, readdirSync, rmSync, statSync, realpathSync, openSync, fsyncSync, closeSync } from 'node:fs';
89
+ import { dirname, resolve, join, posix, relative, isAbsolute } from 'node:path';
80
90
  import { fileURLToPath } from 'node:url';
81
91
  import { spawnSync } from 'node:child_process';
82
- import { createHash } from 'node:crypto';
92
+ import { createHash, randomBytes } from 'node:crypto';
83
93
  import { tmpdir } from 'node:os';
84
94
  import { tokenizeMarkdown } from './markdown-blocks.mjs';
85
95
 
@@ -520,7 +530,67 @@ export const verifyRewriteConservation = (plan) => {
520
530
  const summarizeRewrites = (plans) =>
521
531
  plans.flatMap((plan) => plan.rewrites.map((rw) => `${plan.rel}:${rw.line} ${rw.old} → ${rw.new}`));
522
532
 
523
- export const writeInboundRewrites = (root, plans) => {
533
+ // ── whole-file writes (a temporary file beside the target, then one rename) ─────────────
534
+
535
+ // The fs seams: every file the rotator writes goes through deps.writeFileSync, every rename through
536
+ // deps.renameSync, every removal through deps.rmSync, every sync through deps.fsyncSync. onChange fires once a
537
+ // project file has changed.
538
+ const fsIo = (deps = {}, onChange = () => {}) => {
539
+ const rename = deps.renameSync ?? renameSync;
540
+ const remove = deps.rmSync ?? rmSync;
541
+ return {
542
+ write: deps.writeFileSync ?? writeFileSync,
543
+ fsync: deps.fsyncSync ?? fsyncSync,
544
+ remove,
545
+ rename: (from, to) => {
546
+ rename(from, to);
547
+ onChange();
548
+ },
549
+ removeFile: (path) => {
550
+ remove(path);
551
+ onChange();
552
+ },
553
+ };
554
+ };
555
+
556
+ const fsyncPath = (io, path, flags = 'r') => {
557
+ const fd = openSync(path, flags);
558
+ try {
559
+ io.fsync(fd);
560
+ } finally {
561
+ closeSync(fd);
562
+ }
563
+ };
564
+ const DIRECTORY_FSYNC_UNSUPPORTED = ['EINVAL', 'ENOTSUP', 'EOPNOTSUPP', 'EPERM', 'EISDIR'];
565
+
566
+ // An interruption leaves the target whole — its old bytes or its new ones: the temporary file, named per run
567
+ // so no earlier run's leftover meets the exclusive create, is created exclusively, synced, then renamed over
568
+ // the target. A failed write removes it, never a name another writer holds; its name never ends in .md, so no
569
+ // reader of the store takes a leftover for a document.
570
+ const writeWhole = (io, path, content) => {
571
+ const temp = `${path}.${process.pid}-${randomBytes(4).toString('hex')}.tmp`;
572
+ try {
573
+ io.write(temp, content, { encoding: 'utf8', flag: 'wx' });
574
+ fsyncPath(io, temp, 'r+'); // Windows flushes a file only through a handle open for writing
575
+ io.rename(temp, path);
576
+ } catch (err) {
577
+ if (err?.code !== 'EEXIST') {
578
+ try {
579
+ io.remove(temp, { force: true });
580
+ } catch (cleanupErr) {
581
+ err.message += ` (its temporary file ${temp} was left: ${cleanupErr.message})`;
582
+ }
583
+ }
584
+ throw err;
585
+ }
586
+ try {
587
+ fsyncPath(io, dirname(path));
588
+ } catch (err) {
589
+ if (!DIRECTORY_FSYNC_UNSUPPORTED.includes(err?.code)) throw err; // the rename is complete either way
590
+ }
591
+ };
592
+
593
+ export const writeInboundRewrites = (root, plans, io = fsIo()) => {
524
594
  // Two passes (the plan is computed pre-write, D4): verify the LIVE bytes of EVERY planned file
525
595
  // first, then write — a drift anywhere refuses with NOTHING written in the rewrite phase.
526
596
  for (const plan of plans) {
@@ -529,36 +599,49 @@ export const writeInboundRewrites = (root, plans) => {
529
599
  }
530
600
  }
531
601
  for (const plan of plans) {
532
- writeFileSync(resolve(root, plan.rel), `${plan.frontmatter}${plan.afterLines.join('\n')}`, 'utf8');
602
+ writeWhole(io, resolve(root, plan.rel), `${plan.frontmatter}${plan.afterLines.join('\n')}`);
533
603
  }
534
604
  };
535
605
 
606
+ // The unfenced lines of one markdown file, each with its file line and whether it sits in the preamble
607
+ // (before the first `## ` heading).
608
+ const liveLines = (rel, text) => {
609
+ const { frontLines, lines, fencedLines, headings } = tokenizeMarkdown(text, rel);
610
+ const first = headings.find((h) => h.level === 2 && h.text.startsWith('## '));
611
+ const blocksFrom = first ? first.index : lines.length;
612
+ return lines.flatMap((line, index) => (fencedLines.has(index) ? [] : [{ fileLine: frontLines + index + 1, line, inPreamble: index < blocksFrom }]));
613
+ };
614
+
536
615
  // CHECK scope (read-only, wider): docs/ai/** including decisions.md (whole file) and the adr/
537
616
  // records, excluding only the generated navigator. (a) a `decisions.md#ad-NNN…` id outside the
538
617
  // CURRENT HOT window is dead (an archived id is stale, not resolving); (b) an `adr/AD-NNN-slug.md`
539
- // link must name an existing record FILE (exact filename, not id-presence).
540
- const collectReferenceViolations = (root, hotIds, archivedIds) => {
618
+ // link must name an existing record FILE (exact filename, not id-presence). Neither rule reads the
619
+ // linking file's own path, so a block is judged the same before and after it moves.
620
+ const scanReferences = (docs, hotIds, archivedIds, recordExists) => {
541
621
  const violations = [];
542
- for (const rel of walkDocsMarkdown(root).filter((r) => r !== NAV_REL)) {
543
- const { frontLines, lines, fencedLines } = tokenizeMarkdown(readFileSync(resolve(root, rel), 'utf8'), rel);
544
- for (let index = 0; index < lines.length; index += 1) {
545
- if (fencedLines.has(index)) continue;
546
- const fileLine = frontLines + index + 1;
547
- for (const m of lines[index].matchAll(HOT_LINK_RE)) {
622
+ for (const [rel, live] of docs) {
623
+ for (const { fileLine, line } of live) {
624
+ for (const m of line.matchAll(HOT_LINK_RE)) {
548
625
  if (hotIds.has(m[2])) continue;
549
626
  const why = archivedIds.has(m[2]) ? `AD-${m[2]} is archived — repoint the link at ${ADR_DIR_REL}/` : `AD-${m[2]} is not in the current HOT window`;
550
627
  violations.push(`${rel}:${fileLine}: dead ADR anchor "${m[0]}" — ${why}`);
551
628
  }
552
- for (const m of lines[index].matchAll(RECORD_LINK_RE)) {
553
- if (!existsSync(resolve(root, ADR_DIR_REL, m[1]))) {
554
- violations.push(`${rel}:${fileLine}: dead ADR record link "${m[0]}" — no record file ${ADR_DIR_REL}/${m[1]}`);
555
- }
629
+ for (const m of line.matchAll(RECORD_LINK_RE)) {
630
+ if (!recordExists(m[1])) violations.push(`${rel}:${fileLine}: dead ADR record link "${m[0]}" — no record file ${ADR_DIR_REL}/${m[1]}`);
556
631
  }
557
632
  }
558
633
  }
559
634
  return violations;
560
635
  };
561
636
 
637
+ const collectReferenceViolations = (root, hotIds, archivedIds) =>
638
+ scanReferences(
639
+ walkDocsMarkdown(root).filter((r) => r !== NAV_REL).map((rel) => [rel, liveLines(rel, readFileSync(resolve(root, rel), 'utf8'))]),
640
+ hotIds,
641
+ archivedIds,
642
+ (name) => existsSync(resolve(root, ADR_DIR_REL, name)),
643
+ );
644
+
562
645
  // ── tier / store IO ─────────────────────────────────────────────────────────────────────
563
646
 
564
647
  export const lineCountOf = (text) => text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
@@ -646,8 +729,9 @@ const NEW_ARCHIVE_LINE = (oldestId) =>
646
729
  // A preamble that never mentioned the archive is left untouched (a consumer's own wording preserved).
647
730
  // Assumes the archive prose is one logical blockquote line (the shipped shape); a hand-wrapped
648
731
  // continuation line carrying NEITHER marker is left in place (a stated, benign residual).
732
+ const isArchiveLine = (line) => /decisions-archive/.test(line) || /\*\*Archive:\*\*/.test(line);
733
+
649
734
  export const rewriteHotPreamble = (preamble, oldestId) => {
650
- const isArchiveLine = (line) => /decisions-archive/.test(line) || /\*\*Archive:\*\*/.test(line);
651
735
  const out = [];
652
736
  let replaced = false;
653
737
  for (const line of preamble.split('\n')) {
@@ -759,29 +843,48 @@ const resolveGitDir = (root, spawn) => {
759
843
  return r && r.status === 0 && r.stdout ? r.stdout.trim() : null;
760
844
  };
761
845
 
846
+ const isInside = (root, path) => {
847
+ const rel = relative(resolve(root), resolve(path));
848
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
849
+ };
850
+
762
851
  // Snapshot the docs the migration is about to destroy (decisions.md + both monoliths) into the git
763
- // dir (uncommittable — never in the work tree, never stageable). Off git → a stated tmpdir fallback;
764
- // fails LOUD if neither base is writable. Returns { dir, base } for the caller to report.
852
+ // dir (uncommittable — never in the work tree, never stageable). Off git → a stated tmpdir fallback,
853
+ // refused when it lies inside the project root; a base whose write fails partway has its partial
854
+ // directory removed before the next is tried; fails LOUD naming both when neither base is writable.
855
+ // Returns { dir, base } for the caller to report.
765
856
  export const writeSnapshot = (root, files, deps = {}) => {
766
857
  const spawn = deps.spawnSync ?? spawnSync;
767
858
  const stamp = deps.stamp ?? `${new Date().toISOString().replace(/[:.]/g, '-')}`;
768
859
  const fallbackBase = deps.snapshotFallbackBase ?? tmpdir();
860
+ const io = fsIo(deps);
769
861
  const gitDir = resolveGitDir(root, spawn);
770
- const bases = gitDir ? [gitDir, fallbackBase] : [fallbackBase];
771
- let lastErr = null;
862
+ const failures = gitDir ? [] : ['no git dir'];
863
+ const bases = gitDir ? [gitDir] : [];
864
+ if (isInside(root, fallbackBase)) failures.push(`the temp dir ${fallbackBase} lies inside the project root`);
865
+ else bases.push(fallbackBase);
772
866
  for (const base of bases) {
773
867
  const dir = resolve(base, `${SNAPSHOT_PREFIX}-${stamp}`);
868
+ let made = false;
774
869
  try {
775
870
  mkdirSync(dir, { recursive: true });
871
+ made = true;
776
872
  for (const { rel, content } of files) {
777
- writeFileSync(resolve(dir, rel.replace(/\//g, '__')), content, 'utf8');
873
+ io.write(resolve(dir, rel.replace(/\//g, '__')), content, 'utf8');
778
874
  }
779
875
  return { dir, base, viaGitDir: base === gitDir };
780
876
  } catch (err) {
781
- lastErr = err;
877
+ failures.push(`${dir}: ${err.message}`);
878
+ if (made) {
879
+ try {
880
+ io.remove(dir, { recursive: true, force: true });
881
+ } catch (rmErr) {
882
+ failures.push(`its partial directory was left: ${rmErr.message}`);
883
+ }
884
+ }
782
885
  }
783
886
  }
784
- throw fail(1, `refusing to migrate: no writable snapshot location (git dir + fallback both failed: ${lastErr && lastErr.message}) — a durable pre-delete snapshot is mandatory`);
887
+ throw fail(1, `refusing to migrate: no writable snapshot location (git dir + fallback both failed: ${failures.join('; ')}) — a durable pre-delete snapshot is mandatory`);
785
888
  };
786
889
 
787
890
  // ── index regeneration (item (h) — reuse the ONE generator in check-docs-size.mjs) ──────
@@ -805,12 +908,11 @@ export const defaultRegenerateIndex = (root, today, deps = {}) => {
805
908
 
806
909
  // ── shared store-write helpers ──────────────────────────────────────────────────────────
807
910
 
808
- const writeRecords = (root, records) => {
911
+ const writeRecords = (root, records, io) => {
809
912
  const dir = resolve(root, ADR_DIR_REL);
810
913
  mkdirSync(dir, { recursive: true });
811
- // Index the existing filenames by id ONCE (O(store), not O(records × store)) so a stale same-id
812
- // file under a DIVERGENT slug (a retitled or prior-run remnant) can be pruned — exactly one file
813
- // per id survives, the canonical slug wins.
914
+ // Index the existing filenames by id ONCE (O(store), not O(records × store)) so a same-id file
915
+ // under a DIVERGENT slug (a retitled or prior-run remnant) moves to its canonical name.
814
916
  const existingById = new Map();
815
917
  for (const name of readdirSync(dir)) {
816
918
  const m = name.match(RECORD_FILE_RE);
@@ -822,40 +924,53 @@ const writeRecords = (root, records) => {
822
924
  let written = 0;
823
925
  let skipped = 0;
824
926
  for (const record of records) {
825
- for (const name of existingById.get(record.id) ?? []) {
826
- if (name !== record.fileName) rmSync(resolve(dir, name));
827
- }
828
927
  const path = resolve(dir, record.fileName);
928
+ // ONE rename, never a copy: no instant holds zero or two files for the id (the store loader
929
+ // refuses two); the body is then written whole, so either failure leaves one record a re-run completes.
930
+ const other = (existingById.get(record.id) ?? []).find((name) => name !== record.fileName);
931
+ if (other) io.rename(resolve(dir, other), path);
829
932
  const body = renderRecord(record);
830
933
  if (existsSync(path) && readFileSync(path, 'utf8') === body) {
831
934
  skipped += 1; // crash-resumable: a byte-identical record is left as is
832
935
  continue;
833
936
  }
834
- writeFileSync(path, body, 'utf8');
937
+ writeWhole(io, path, body);
835
938
  written += 1;
836
939
  }
837
940
  return { written, skipped };
838
941
  };
839
942
 
840
- const writeNavigatorFile = (root, corpus, today) => {
943
+ const writeNavigatorFile = (root, corpus, today, io) => {
841
944
  const dir = resolve(root, ADR_DIR_REL);
842
945
  mkdirSync(dir, { recursive: true });
843
- writeFileSync(resolve(root, NAV_REL), buildNavigator(corpus, today), 'utf8');
946
+ writeWhole(io, resolve(root, NAV_REL), buildNavigator(corpus, today));
844
947
  };
845
948
 
846
- const writeHot = (root, hot, retained, today) => {
949
+ const writeHot = (root, hot, retained, today, io) => {
847
950
  const oldestId = retained.length > 0 ? retained[0].id : hot.entries.length > 0 ? hot.entries[0].id : '000';
848
951
  const preamble = rewriteHotPreamble(hot.preamble, oldestId);
849
952
  const frontmatter = stampLastUpdated(hot.frontmatter, today);
850
- writeFileSync(hot.path, renderTier(frontmatter, preamble, retained), 'utf8');
953
+ writeWhole(io, hot.path, renderTier(frontmatter, preamble, retained));
954
+ };
955
+
956
+ // Pinned write order: records → inbound rewrites → navigator → HOT rewrite → monolith removal, so every
957
+ // interrupted state re-runs to completion.
958
+ const applyMoves = (root, plan, today, io, withNavigator = true) => {
959
+ writeRecords(root, plan.records, io);
960
+ writeInboundRewrites(root, plan.rewritePlans, io);
961
+ if (withNavigator) writeNavigatorFile(root, [...plan.retained, ...loadAdrStore(root)], today, io);
962
+ writeHot(root, plan.hot, plan.retained, today, io);
963
+ for (const rel of plan.present) io.removeFile(resolve(root, rel));
851
964
  };
852
965
 
853
966
  // ── CLI ─────────────────────────────────────────────────────────────────────────────────
854
967
 
855
- const USAGE = 'Usage: archive-decisions.mjs [--check|--migrate [--apply]|--write-navigator|--dry-run] [--today=YYYY-MM-DD]';
968
+ const USAGE = 'Usage: archive-decisions.mjs [--check|--migrate [--apply]|--write-navigator|--dry-run|--ensure-current] [--today=YYYY-MM-DD]';
969
+
970
+ const MODE_FLAGS = [['--check', 'check'], ['--migrate', 'migrate'], ['--apply', 'apply'], ['--write-navigator', 'writeNavigator'], ['--dry-run', 'dryRun']];
856
971
 
857
972
  const parseArgs = (argv) => {
858
- const flags = { check: false, migrate: false, apply: false, writeNavigator: false, dryRun: false, help: false };
973
+ const flags = { check: false, migrate: false, apply: false, writeNavigator: false, dryRun: false, ensureCurrent: false, help: false };
859
974
  let today = null;
860
975
  for (const arg of argv) {
861
976
  if (arg === '--check') flags.check = true;
@@ -863,6 +978,7 @@ const parseArgs = (argv) => {
863
978
  else if (arg === '--apply') flags.apply = true;
864
979
  else if (arg === '--write-navigator') flags.writeNavigator = true;
865
980
  else if (arg === '--dry-run') flags.dryRun = true;
981
+ else if (arg === '--ensure-current') flags.ensureCurrent = true;
866
982
  else if (arg === '--help' || arg === '-h') flags.help = true;
867
983
  else if (arg.startsWith('--today=')) today = arg.slice('--today='.length);
868
984
  else throw fail(2, `Unknown argument: ${arg}\n${USAGE}`);
@@ -871,6 +987,10 @@ const parseArgs = (argv) => {
871
987
  if (flags.migrate && flags.apply && flags.dryRun) {
872
988
  throw fail(2, `--migrate --apply --dry-run is contradictory — plain --migrate IS the dry run; drop --apply to preview or --dry-run to apply\n${USAGE}`);
873
989
  }
990
+ const beside = MODE_FLAGS.filter(([, key]) => flags[key]).map(([flag]) => flag);
991
+ if (flags.ensureCurrent && beside.length > 0) {
992
+ throw fail(2, `--ensure-current ${beside.join(' ')} is a usage error — --ensure-current is one mode, run alone\n${USAGE}`);
993
+ }
874
994
  return { flags, today };
875
995
  };
876
996
 
@@ -895,9 +1015,22 @@ const assertStoreIntegrity = (hotEntries, adrEntries) => {
895
1015
  }
896
1016
  };
897
1017
 
1018
+ // A HOT window whose newest entry alone exceeds its cap cannot be brought under it by moving entries.
1019
+ const assertHotReducible = (hot, retained) => {
1020
+ const rewrittenPreamble = rewriteHotPreamble(hot.preamble, retained.length > 0 ? retained[0].id : '000');
1021
+ if (hot.cap !== null && lineCountOf(renderTier(hot.frontmatter, rewrittenPreamble, retained)) > hot.cap) {
1022
+ throw fail(1, `${HOT_REL} is over its cap but cannot be reduced (the newest entry alone exceeds ${hot.cap} lines) — trim it or raise the cap (a maintainer decision; this script only moves entries).`);
1023
+ }
1024
+ };
1025
+
1026
+ const snapshotFilesOf = ({ hot, warm, cold }) => [
1027
+ { rel: HOT_REL, content: hot.raw },
1028
+ ...(warm.exists ? [{ rel: WARM_REL, content: warm.raw }] : []),
1029
+ ...(cold.exists ? [{ rel: COLD_REL, content: cold.raw }] : []),
1030
+ ];
1031
+
898
1032
  const runMigrate = (root, flags, today, deps, log, logError) => {
899
1033
  const present = monolithsPresent(root);
900
- const hasHot = existsSync(resolve(root, HOT_REL));
901
1034
  if (present.length === 0) {
902
1035
  if (existsSync(resolve(root, ADR_DIR_REL))) {
903
1036
  log('[archive-decisions] already migrated — no legacy monolith present; nothing to do.');
@@ -906,7 +1039,44 @@ const runMigrate = (root, flags, today, deps, log, logError) => {
906
1039
  log('[archive-decisions] nothing to migrate — no legacy decisions-archive monolith found.');
907
1040
  return 0;
908
1041
  }
909
- if (!hasHot) throw fail(1, `${HOT_REL} not found but a legacy monolith is present — a broken tree; restore ${HOT_REL} before migrating.`);
1042
+ const plan = planMigration(root, today);
1043
+ const { retained, records, rewritePlans, oldItems } = plan;
1044
+ const summary = {
1045
+ records: records.map((r) => r.fileName),
1046
+ retainedHot: retained.map((e) => `AD-${e.id}`),
1047
+ monolithsRetired: present,
1048
+ inboundRewrites: summarizeRewrites(rewritePlans),
1049
+ conservation: `${oldItems.length} corpus blocks → ${retained.length} retained-HOT + ${records.length} records (conserved)`,
1050
+ };
1051
+
1052
+ if (!flags.apply) {
1053
+ log('[archive-decisions] --migrate DRY-RUN — no files will be changed.');
1054
+ log(JSON.stringify(summary, null, 2));
1055
+ return 0;
1056
+ }
1057
+
1058
+ const snapshot = writeSnapshot(root, snapshotFilesOf(plan), deps);
1059
+ // Only after conservation passed AND the snapshot exists does applyMoves remove the monoliths.
1060
+ applyMoves(root, plan, today, fsIo(deps));
1061
+
1062
+ const regen = (deps.regenerateIndex ?? defaultRegenerateIndex)(root, today);
1063
+ log('[archive-decisions] migrated the 3-tier cascade → one-file-per-ADR store:');
1064
+ log(` snapshot: ${snapshot.dir} (${snapshot.viaGitDir ? 'git dir' : 'out-of-tree fallback'})`);
1065
+ log(` records written: ${records.length} under ${ADR_DIR_REL}/`);
1066
+ log(` inbound links rewritten: ${summary.inboundRewrites.length} across ${rewritePlans.length} file(s)`);
1067
+ log(` retained HOT: ${summary.retainedHot.join(', ') || '(none)'}`);
1068
+ log(` retired monoliths: ${present.join(', ')}`);
1069
+ log(` navigator: ${NAV_REL}`);
1070
+ if (regen.ok) log(' regenerated docs/ai/index.md');
1071
+ else logError(`[archive-decisions] docs/ai/index.md NOT regenerated — ${regen.detail}`);
1072
+ return 0;
1073
+ };
1074
+
1075
+ // The migration's whole preflight — the corpus union, conservation, store integrity and every link
1076
+ // check — with no write: --migrate and --ensure-current both run it.
1077
+ const planMigration = (root, today) => {
1078
+ const present = monolithsPresent(root);
1079
+ if (!existsSync(resolve(root, HOT_REL))) throw fail(1, `${HOT_REL} not found but a legacy monolith is present — a broken tree; restore ${HOT_REL} before migrating.`);
910
1080
 
911
1081
  const hot = loadHot(root);
912
1082
  const warm = loadMonolith(root, WARM_REL);
@@ -973,48 +1143,7 @@ const runMigrate = (root, flags, today, deps, log, logError) => {
973
1143
  ]);
974
1144
  const rewritePlans = planInboundRewrites(root, movedById, true);
975
1145
  for (const plan of rewritePlans) verifyRewriteConservation(plan);
976
-
977
- const summary = {
978
- records: records.map((r) => r.fileName),
979
- retainedHot: retained.map((e) => `AD-${e.id}`),
980
- monolithsRetired: present,
981
- inboundRewrites: summarizeRewrites(rewritePlans),
982
- conservation: `${oldItems.length} corpus blocks → ${retained.length} retained-HOT + ${records.length} records (conserved)`,
983
- };
984
-
985
- if (!flags.apply) {
986
- log('[archive-decisions] --migrate DRY-RUN — no files will be changed.');
987
- log(JSON.stringify(summary, null, 2));
988
- return 0;
989
- }
990
-
991
- const snapshotFiles = [
992
- { rel: HOT_REL, content: hot.raw },
993
- ...(warm.exists ? [{ rel: WARM_REL, content: warm.raw }] : []),
994
- ...(cold.exists ? [{ rel: COLD_REL, content: cold.raw }] : []),
995
- ];
996
- const snapshot = writeSnapshot(root, snapshotFiles, deps);
997
-
998
- // Pinned write order: records → inbound rewrites → HOT rewrite / monolith removal.
999
- writeRecords(root, records);
1000
- writeInboundRewrites(root, rewritePlans);
1001
- const corpus = [...retained, ...loadAdrStore(root)];
1002
- writeNavigatorFile(root, corpus, today);
1003
- writeHot(root, hot, retained, today);
1004
- // Only NOW — conservation passed AND the snapshot exists — remove the monoliths.
1005
- for (const rel of present) rmSync(resolve(root, rel));
1006
-
1007
- const regen = (deps.regenerateIndex ?? defaultRegenerateIndex)(root, today);
1008
- log('[archive-decisions] migrated the 3-tier cascade → one-file-per-ADR store:');
1009
- log(` snapshot: ${snapshot.dir} (${snapshot.viaGitDir ? 'git dir' : 'out-of-tree fallback'})`);
1010
- log(` records written: ${records.length} under ${ADR_DIR_REL}/`);
1011
- log(` inbound links rewritten: ${summary.inboundRewrites.length} across ${rewritePlans.length} file(s)`);
1012
- log(` retained HOT: ${summary.retainedHot.join(', ') || '(none)'}`);
1013
- log(` retired monoliths: ${present.join(', ')}`);
1014
- log(` navigator: ${NAV_REL}`);
1015
- if (regen.ok) log(' regenerated docs/ai/index.md');
1016
- else logError(`[archive-decisions] docs/ai/index.md NOT regenerated — ${regen.detail}`);
1017
- return 0;
1146
+ return { present, hot, warm, cold, existingStore, retained, toExplode, records, rewritePlans, oldItems };
1018
1147
  };
1019
1148
 
1020
1149
  const runWriteNavigator = (root, flags, today, deps, log, logError) => {
@@ -1036,7 +1165,7 @@ const runWriteNavigator = (root, flags, today, deps, log, logError) => {
1036
1165
  log(`[archive-decisions] --write-navigator DRY-RUN — no files will be changed; ${corpus.length} ADR(s) validated.`);
1037
1166
  return 0;
1038
1167
  }
1039
- writeNavigatorFile(root, corpus, today);
1168
+ writeNavigatorFile(root, corpus, today, fsIo(deps));
1040
1169
  const regen = (deps.regenerateIndex ?? defaultRegenerateIndex)(root, today);
1041
1170
  log(`[archive-decisions] wrote ${NAV_REL} (${corpus.length} ADRs in the corpus).`);
1042
1171
  if (regen.ok) log(' regenerated docs/ai/index.md');
@@ -1112,18 +1241,44 @@ const runRotate = (root, flags, today, deps, log, logError) => {
1112
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).`);
1113
1242
  return 1;
1114
1243
  }
1244
+ const plan = planRotation(root, today);
1245
+ if (plan.idle) {
1246
+ log(`[archive-decisions] nothing to rotate — HOT ${plan.hot.rawLines}/${plan.hot.cap}, ${plan.existingStore.length} archived record(s).`);
1247
+ return 0;
1248
+ }
1249
+ const summary = {
1250
+ explode: plan.records.map((r) => r.fileName),
1251
+ retainedHot: plan.retained.map((e) => `AD-${e.id}`),
1252
+ inboundRewrites: summarizeRewrites(plan.rewritePlans),
1253
+ };
1254
+ if (flags.dryRun) {
1255
+ log('[archive-decisions] DRY-RUN — no files will be changed.');
1256
+ log(JSON.stringify(summary, null, 2));
1257
+ return 0;
1258
+ }
1259
+
1260
+ applyMoves(root, plan, today, fsIo(deps));
1261
+ const regen = (deps.regenerateIndex ?? defaultRegenerateIndex)(root, today);
1262
+ log('[archive-decisions] rotated:');
1263
+ log(` exploded to adr/: ${summary.explode.join(', ') || '(none)'}`);
1264
+ log(` inbound links rewritten: ${summary.inboundRewrites.length} across ${plan.rewritePlans.length} file(s)`);
1265
+ log(` retained HOT: ${summary.retainedHot.join(', ')}`);
1266
+ if (regen.ok) log(' regenerated docs/ai/index.md');
1267
+ else logError(`[archive-decisions] docs/ai/index.md NOT regenerated — ${regen.detail}`);
1268
+ return 0;
1269
+ };
1270
+
1271
+ // The rotate's whole preflight with no write. `idle` when nothing moves: the default rotate idles while
1272
+ // no entry overflows and HOT is within its cap; --ensure-current (withinCap false) whenever HOT is within it.
1273
+ const planRotation = (root, today, rotateWithinCap = true) => {
1115
1274
  const hot = loadHot(root);
1116
1275
  const existingStore = loadAdrStore(root);
1117
1276
  const { retained, toExplode } = boundHot(hot.entries, hot.frontmatter, hot.preamble, hot.cap ?? Infinity);
1118
- if (toExplode.length === 0 && hot.rawLines <= (hot.cap ?? Infinity)) {
1277
+ if (hot.rawLines <= (hot.cap ?? Infinity) && (toExplode.length === 0 || !rotateWithinCap)) {
1119
1278
  assertStoreIntegrity(hot.entries, existingStore); // a no-op still refuses a corrupt store (dup / partition)
1120
- log(`[archive-decisions] nothing to rotate — HOT ${hot.rawLines}/${hot.cap}, ${existingStore.length} archived record(s).`);
1121
- return 0;
1122
- }
1123
- const rewrittenPreamble = rewriteHotPreamble(hot.preamble, retained.length > 0 ? retained[0].id : '000');
1124
- if (hot.cap !== null && lineCountOf(renderTier(hot.frontmatter, rewrittenPreamble, retained)) > hot.cap) {
1125
- throw fail(1, `${HOT_REL} is over its cap but cannot be reduced (the newest entry alone exceeds ${hot.cap} lines) — trim it or raise the cap (a maintainer decision; this script only moves entries).`);
1279
+ return { idle: true, present: [], hot, existingStore, retained: hot.entries, toExplode: [], records: [], rewritePlans: [] };
1126
1280
  }
1281
+ assertHotReducible(hot, retained);
1127
1282
 
1128
1283
  const records = explode(toExplode, today);
1129
1284
  // Crash-resume (fold-induced): a record from a prior crashed rotate may already be on
@@ -1145,31 +1300,79 @@ const runRotate = (root, flags, today, deps, log, logError) => {
1145
1300
  assertMovingBlocksFreeOfRelativeAdrLinks(root, new Set(movedById.keys()), new Set(retained.map((e) => e.id)));
1146
1301
  const rewritePlans = planInboundRewrites(root, movedById, false);
1147
1302
  for (const plan of rewritePlans) verifyRewriteConservation(plan);
1303
+ return { idle: false, present: [], hot, existingStore, retained, toExplode, records, rewritePlans };
1304
+ };
1148
1305
 
1149
- const summary = {
1150
- explode: records.map((r) => r.fileName),
1151
- retainedHot: retained.map((e) => `AD-${e.id}`),
1152
- inboundRewrites: summarizeRewrites(rewritePlans),
1153
- };
1154
- if (flags.dryRun) {
1155
- log('[archive-decisions] DRY-RUN — no files will be changed.');
1156
- log(JSON.stringify(summary, null, 2));
1306
+ // --ensure-current: every decision is judged before the first write, by the plans above and the check's
1307
+ // own collector over the store the planned moves leave; then the writes, the index, and a closing --check.
1308
+ const runEnsure = (root, today, deps, log, logError) => {
1309
+ const present = monolithsPresent(root);
1310
+ const hasHot = existsSync(resolve(root, HOT_REL));
1311
+ if (present.length === 0 && !hasHot && !existsSync(resolve(root, ADR_DIR_REL))) {
1312
+ const orphaned = collectReferenceViolations(root, new Set(), new Set());
1313
+ if (orphaned.length > 0) throw fail(1, `no ADR substrate, yet ADR references point into one:\n ${orphaned.join('\n ')}`);
1314
+ log(`[archive-decisions] SKIP — no ADR substrate (neither ${HOT_REL} nor ${ADR_DIR_REL}); nothing to bring current.`);
1315
+ log('already-current');
1157
1316
  return 0;
1158
1317
  }
1318
+ let plan;
1319
+ if (present.length > 0) {
1320
+ plan = planMigration(root, today);
1321
+ assertHotReducible(plan.hot, plan.retained);
1322
+ } else if (hasHot) plan = planRotation(root, today, false);
1323
+ else plan = { idle: true, present: [], hot: null, existingStore: loadAdrStore(root), retained: [], toExplode: [], records: [], rewritePlans: [] };
1324
+
1325
+ // The store the planned moves leave: each moved id under its canonical record name, every other
1326
+ // record name of a moved id pruned, the planned rewrites applied, the monoliths' preambles gone.
1327
+ const moved = new Map(plan.records.map((r, i) => [r.id, { ...plan.toExplode[i], fileName: r.fileName }]));
1328
+ const store = [...plan.existingStore.filter((e) => !moved.has(e.id)), ...moved.values()];
1329
+ const corpus = [...plan.retained, ...store];
1330
+ const recordNames = new Set([...plan.existingStore.filter((e) => !moved.has(e.id)).map((e) => e.fileName), ...plan.records.map((r) => r.fileName)]);
1331
+ const rewrites = new Map(plan.rewritePlans.map((p) => [p.rel, p]));
1332
+ const docs = walkDocsMarkdown(root).filter((rel) => rel !== NAV_REL).map((rel) => {
1333
+ const rw = rewrites.get(rel);
1334
+ const live = liveLines(rel, rw ? `${rw.frontmatter}${rw.afterLines.join('\n')}` : readFileSync(resolve(root, rel), 'utf8'));
1335
+ if (plan.present.includes(rel)) return [rel, live.filter((l) => !l.inPreamble)];
1336
+ if (rel === HOT_REL && !plan.idle) return [rel, live.filter((l) => !(l.inPreamble && isArchiveLine(l.line)))];
1337
+ return [rel, live];
1338
+ });
1339
+ const dead = scanReferences(docs, new Set(plan.retained.map((e) => e.id)), new Set(store.map((e) => e.id)), (name) => recordNames.has(name));
1340
+ if (dead.length > 0) throw fail(1, `refusing before any write — ADR references the planned moves would not cure:\n ${dead.join('\n ')}`);
1159
1341
 
1160
- // Pinned write order: records → inbound rewrites → HOT rewrite (crash-resume idempotency).
1161
- writeRecords(root, records);
1162
- writeInboundRewrites(root, rewritePlans);
1163
- const corpus = [...retained, ...loadAdrStore(root)];
1164
- writeNavigatorFile(root, corpus, today);
1165
- writeHot(root, hot, retained, today);
1166
- const regen = (deps.regenerateIndex ?? defaultRegenerateIndex)(root, today);
1167
- log('[archive-decisions] rotated:');
1168
- log(` exploded to adr/: ${summary.explode.join(', ') || '(none)'}`);
1169
- log(` inbound links rewritten: ${summary.inboundRewrites.length} across ${rewritePlans.length} file(s)`);
1170
- log(` retained HOT: ${summary.retainedHot.join(', ')}`);
1171
- if (regen.ok) log(' regenerated docs/ai/index.md');
1172
- else logError(`[archive-decisions] docs/ai/index.md NOT regenerated — ${regen.detail}`);
1342
+ const navPath = resolve(root, NAV_REL);
1343
+ const navOnDisk = existsSync(navPath) ? readFileSync(navPath, 'utf8') : null;
1344
+ const navStale = navOnDisk === null || buildNavigator(corpus, navLastUpdated(navOnDisk)) !== navOnDisk;
1345
+ const actions = [present.length > 0 && 'migrated', present.length === 0 && !plan.idle && 'rotated', navStale && 'navigator written'].filter(Boolean);
1346
+ if (actions.length === 0) {
1347
+ log('already-current');
1348
+ return 0;
1349
+ }
1350
+
1351
+ let changed = false;
1352
+ let written = false;
1353
+ let snapshot = null;
1354
+ try {
1355
+ if (present.length > 0) snapshot = writeSnapshot(root, snapshotFilesOf(plan), deps);
1356
+ const io = fsIo(deps, () => {
1357
+ changed = true;
1358
+ });
1359
+ if (plan.idle) writeNavigatorFile(root, corpus, today, io);
1360
+ else applyMoves(root, plan, today, io, navStale);
1361
+ written = true;
1362
+ const regen = (deps.regenerateIndex ?? defaultRegenerateIndex)(root, today);
1363
+ if (!regen.ok) logError(`[archive-decisions] docs/ai/index.md NOT regenerated — ${regen.detail}`);
1364
+ const checkLines = [];
1365
+ if (runCheck(root, today, () => {}, (line) => checkLines.push(line)) !== 0) throw new Error(checkLines.join('\n '));
1366
+ } catch (err) {
1367
+ if (written) logError(`[archive-decisions] the store was written and does not pass --check:\n ${err.message}`);
1368
+ else logError(`[archive-decisions] ${err.message}`);
1369
+ if (snapshot) logError(`[archive-decisions] snapshot: ${snapshot.dir}`);
1370
+ if (!changed) return 1;
1371
+ if (!written) logError('[archive-decisions] a project file changed before the failure — a re-run completes the move.');
1372
+ return 3;
1373
+ }
1374
+ if (snapshot) log(`snapshot: ${snapshot.dir}`);
1375
+ log(`brought-current: ${actions.join(', ')}`);
1173
1376
  return 0;
1174
1377
  };
1175
1378
 
@@ -1183,6 +1386,7 @@ export const runCli = (argv, deps = {}) => {
1183
1386
  }
1184
1387
  const today = todayOpt ?? new Date().toISOString().slice(0, 10);
1185
1388
 
1389
+ if (flags.ensureCurrent) return runEnsure(root, today, deps, log, logError);
1186
1390
  if (flags.migrate) return runMigrate(root, flags, today, deps, log, logError);
1187
1391
  if (flags.writeNavigator) return runWriteNavigator(root, flags, today, deps, log, logError);
1188
1392
  if (flags.check) return runCheck(root, today, log, logError);
@@ -26,7 +26,6 @@ import { findOnPath } from './detect-backends.mjs';
26
26
  import { consoleArgv } from './write-lanes.mjs';
27
27
  import { BUNDLED_SCRIPT_NAMES, INSTALLER_REL, SCRIPTS_REL, formatPlan, planGitHooks } from './git-hooks.mjs';
28
28
  import { ATTRIBUTION_HIDDEN, ATTRIBUTION_KEY, writeAttribution } from './attribution.mjs';
29
- import { classifyDeployedScript } from './script-priors.mjs';
30
29
  import { globalRemovalOf, planGlobalRemoval } from './hide-footprint.mjs';
31
30
  import { isDirectRun } from './direct-run.mjs';
32
31
  import { dirCovers as covers } from './declared-paths.mjs';
@@ -221,7 +220,7 @@ export const scopeOf = (variant, facts, deps = {}) => {
221
220
  const scripts = join(facts.root, SCRIPTS_REL);
222
221
  if (GIT_VARIANTS.includes(variant)) {
223
222
  directories.splice(0, directories.length, ...(variant === 'hook-checks' ? [] : [scripts]));
224
- filePaths.push(...(variant === 'hook-checks' ? [join(facts.root, INSTALLER_REL)] : BUNDLED_SCRIPT_NAMES.map((name) => join(scripts, name))));
223
+ if (variant !== 'hook-checks') filePaths.push(...BUNDLED_SCRIPT_NAMES.map((name) => join(scripts, name)));
225
224
  }
226
225
  const rules = ['--rules-check', join(facts.toolsDir, 'project-rules', 'rules-cli.mjs')];
227
226
  const layout = ['--layout-check', join(facts.toolsDir, 'source-size-check.mjs')];
@@ -318,12 +317,6 @@ export const plannedChange = (variant, facts, deps = {}) => {
318
317
  } else if (GIT_VARIANTS.includes(variant)) {
319
318
  const plan = (deps.planGitHooks ?? planGitHooks)({ root: facts.root, variant, toolsDir: facts.toolsDir });
320
319
  for (const copy of plan.copies.filter(({ action }) => action === 'created')) writes.push({ path: copy.path, bytes: copy.bytes });
321
- if (plan.refresh) {
322
- // The one replace hook-checks makes: the bundled installer's bytes over a catalogued prior body.
323
- const bundled = readFileSync(join(facts.toolsDir, '..', 'references', INSTALLER_REL));
324
- const { path, bytes, replaces } = plan.refresh;
325
- writes.push({ path, bytes, replaces, matches: bundled.equals(bytes) && classifyDeployedScript(replaces, basename(INSTALLER_REL), bundled) === 'prior' });
326
- }
327
320
  runs = { argv: plan.runs.shown, line: formatPlan(plan).at(-1) };
328
321
  } else if (variant === WORKTREES) {
329
322
  const plan = writeVelocityProfile({ cwd: facts.root, dryRun: true, worktrees: true }, writerDeps);
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // git-hooks.mjs — the thin writer of the three git-hook items (`enforcement`, `commit-guard`,
3
- // `hook-checks`): it copies the bundled scripts create-only, refreshes a known-prior installer, and
4
- // spawns the project's own scripts/install-git-hooks.mjs, which decides the hook at the write. The leaf
3
+ // `hook-checks`): it copies the bundled scripts create-only and spawns the project's own
4
+ // scripts/install-git-hooks.mjs as it stands, which decides the hook at the write. The leaf
5
5
  // decides nothing about the hook: the danger check binds the copies and the installer bytes this dry run
6
6
  // answers, never git's hooks dir. It is also the home of the one pre-commit reader, which the
7
7
  // commit-guard and hook-checks applies run after the installer to verify the arm.
@@ -10,12 +10,11 @@ import { createHash } from 'node:crypto';
10
10
  import { spawnSync } from 'node:child_process';
11
11
  import { dirname, join, resolve } from 'node:path';
12
12
  import { fileURLToPath } from 'node:url';
13
- import { writeContainedFileAtomic, writeProjectFileCreateOnly } from './atomic-write.mjs';
13
+ import { writeProjectFileCreateOnly } from './atomic-write.mjs';
14
14
  import { BUNDLED_SCRIPT_NAMES, INSTALLER_REL, NODE_EVIDENCE_SCRIPTS, SCRIPTS_DIR } from './node-evidence.mjs';
15
15
  import { shellQuoteArg } from './repo-lex.mjs';
16
16
  import { GIT_MAX_BUFFER } from './git-env.mjs';
17
17
  import { isDirectRun } from './direct-run.mjs';
18
- import { classifyDeployedScript } from './script-priors.mjs';
19
18
  import { checkRules } from './project-rules/index.mjs';
20
19
  import { readLayoutSetup } from './source-size-core.mjs';
21
20
 
@@ -34,6 +33,8 @@ const USAGE = 'usage: git-hooks (--enforcement | --commit-guard | --hook-checks)
34
33
  const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
35
34
  const usageError = (message) => Object.assign(new Error(message), { exitCode: EXIT_USAGE });
36
35
  const refusal = (message) => Object.assign(new Error(message), { exitCode: EXIT_REFUSED });
36
+ // The one route the two re-read lines end with: an installer that left a passed line out is not the kit's current body.
37
+ export const UPGRADE_ROUTE = "/agent-workflow-kit upgrade refreshes, with no question, an installer body it knows a release shipped, and on its one yes keeps any other installer aside and replaces it with the kit's current body; if it stops on another cause, resolve the cause it names and run it again; then apply this item again";
37
38
 
38
39
  const nodeAt = (path, lstat) => {
39
40
  try {
@@ -122,7 +123,7 @@ export const plannedRoles = (answers, hook) => ROLES.filter(({ key }) =>
122
123
  export const unsafeToolsPath = (toolsDir, platform) => (ROLES.some(({ tool }) => safeHookPath(tool(toolsDir), platform) === null)
123
124
  ? `the kit's tools path ${toolsDir} carries ", $, a backtick, a backslash, CR or LF — a hook line would not run the file it names` : null);
124
125
 
125
- // hook-checks: the lines it arms, from the two answers and the hook, and a refresh of a known-prior installer.
126
+ // hook-checks: the lines it arms, from the two answers and the hook; the installer runs as it stands.
126
127
  const planHookChecks = ({ root, toolsDir, installer, scriptsNode, kinds, readFile, deps }) => {
127
128
  if (!isPlainDir(scriptsNode) || kinds.get(INSTALLER_NAME) !== 'file') throw refusal(`${installer} is absent — nothing here places the hook installer`);
128
129
  const unsafe = unsafeToolsPath(toolsDir, deps.platform);
@@ -135,12 +136,9 @@ const planHookChecks = ({ root, toolsDir, installer, scriptsNode, kinds, readFil
135
136
  if (roles.length === 0) {
136
137
  throw refusal(`nothing to plan — ${ROLES.map(({ key, role }) => `the ${role} line: ${hook[`${key}Armed`] ? 'armed' : `not armable (${answers[key].why})`}`).join('; ')}`);
137
138
  }
138
- const deployed = readFile(installer);
139
- const bundled = readFile(join(bundleDir(toolsDir), INSTALLER_NAME));
140
- const refresh = classifyDeployedScript(deployed, INSTALLER_NAME, bundled) === 'prior' ? { path: installer, bytes: bundled, replaces: deployed } : null;
141
139
  const flags = roles.flatMap(({ flag, tool }) => [flag, tool(toolsDir)]);
142
- return { root, variant: 'hook-checks', scriptsCreated: false, copies: [], refresh, roles: roles.map(({ key }) => key),
143
- runs: { argv: ['node', installer, ...flags], shown: ['node', INSTALLER_REL, ...flags], bytes: refresh ? bundled : deployed } };
140
+ return { root, variant: 'hook-checks', scriptsCreated: false, copies: [], roles: roles.map(({ key }) => key),
141
+ runs: { argv: ['node', installer, ...flags], shown: ['node', INSTALLER_REL, ...flags], bytes: readFile(installer) } };
144
142
  };
145
143
 
146
144
  // The dry run: what the apply copies and the installer it runs, with the bytes of each.
@@ -177,7 +175,6 @@ export const planGitHooks = ({ root, variant, toolsDir = TOOLS, lstat = lstatSyn
177
175
 
178
176
  export const formatPlan = (plan) => [
179
177
  ...plan.copies.map(({ name, action, bytes }) => `copy: ${SCRIPTS_REL}/${name} ${action}${action === 'created' ? ` sha256:${sha(bytes)}` : ''}`),
180
- ...(plan.refresh ? [`refresh: ${INSTALLER_REL} sha256:${sha(plan.refresh.bytes)} — replaces sha256:${sha(plan.refresh.replaces)}`] : []),
181
178
  `runs: ${plan.runs.shown.map(shellQuoteArg).join(' ')} sha256:${sha(plan.runs.bytes)}`,
182
179
  ];
183
180
 
@@ -219,58 +216,26 @@ const rollBack = (plan, created, io) => {
219
216
  return left;
220
217
  };
221
218
 
222
- // The hook's bytes, null when absent; undefined when it cannot be read, which never compares equal.
223
- const hookBytes = (path, readFile) => {
224
- try {
225
- return readFile(path);
226
- } catch (error) {
227
- return error?.code === 'ENOENT' ? null : undefined;
228
- }
229
- };
230
- const sameHook = (left, right) => left !== undefined && right !== undefined && (left === null ? right === null : right !== null && left.equals(right));
231
-
232
- // hook-checks at the write: the refresh, the spawn, the re-read of every passed line; on a failed outcome
233
- // the prior installer comes back exactly when the hook still holds the bytes it held before the spawn.
219
+ // hook-checks at the write: the spawn, then the re-read of every passed line; it writes and restores nothing.
234
220
  const applyHookChecks = (plan, resolved) => {
235
221
  const hooksDir = resolveGitHooksPath(plan.root, resolved.env);
236
222
  const preCommit = hooksDir === null ? null : join(hooksDir, 'pre-commit');
237
- const before = preCommit === null ? null : hookBytes(preCommit, resolved.readFile);
238
- const replace = (bytes) => resolved.replaceFile(plan.root, plan.runs.argv[1], bytes, {}, { label: INSTALLER_REL });
239
- if (plan.refresh) {
240
- try {
241
- replace(plan.refresh.bytes);
242
- } catch (error) {
243
- resolved.error(error?.message ?? String(error));
244
- return EXIT_INCOMPLETE;
245
- }
246
- }
247
223
  const child = resolved.spawn(plan.runs.argv, { cwd: plan.root, env: resolved.env, stdio: 'inherit' });
248
224
  const hook = readPreCommitState(plan.root, { env: resolved.env, toolsDir: resolved.toolsDir, platform: resolved.platform, gitHooksPath: () => hooksDir });
249
225
  const failure = child.status !== 0 ? `installer exited ${child.status ?? child.signal ?? child.error?.code}`
250
226
  : hook.state === 'no-hooks-dir' ? null
251
227
  : hook.state === 'unreadable' ? `${preCommit} is unreadable (${hook.code}) after the installer exited 0`
252
- : ROLES.filter(({ key }) => plan.roles.includes(key)).map(({ key, role, flag }) => (!hook[`${key}Armed`]
253
- ? `${preCommit} carries no ${role} line after the installer exited 0 — an installer older than the arm ignores ${flag}; refreshing ${INSTALLER_REL} from the kit's references/scripts/ copy is your own step`
228
+ : ROLES.filter(({ key }) => plan.roles.includes(key)).map(({ key, role }) => (!hook[`${key}Armed`]
229
+ ? `${preCommit} carries no ${role} line after the installer exited 0 — ${UPGRADE_ROUTE}`
254
230
  : hook[`${key}Foreign`] ? `${preCommit} still carries a ${role} line on a path other than this kit's after the installer exited 0` : null)).find(Boolean) ?? null;
255
231
  if (failure === null) return EXIT_OK;
256
232
  resolved.error(failure);
257
- if (!plan.refresh) return EXIT_INCOMPLETE;
258
- if (!sameHook(before, preCommit === null ? null : hookBytes(preCommit, resolved.readFile))) {
259
- resolved.error(`${INSTALLER_REL} keeps the refreshed bytes: ${preCommit} no longer holds what it held before the installer ran, or cannot be read, and the prior body would drop the new lines at its next run`);
260
- return EXIT_INCOMPLETE;
261
- }
262
- try {
263
- replace(plan.refresh.replaces);
264
- } catch (error) {
265
- resolved.error(`not restored: ${INSTALLER_REL} (${error?.message ?? error})`);
266
- }
267
233
  return EXIT_INCOMPLETE;
268
234
  };
269
235
 
270
236
  export const applyGitHooks = (plan, io = {}) => {
271
237
  const resolved = { lstat: lstatSync, unlink: unlinkSync, rmdir: rmdirSync, readdir: readdirSync, env: process.env,
272
- log: console.log, error: console.error, writeFile: writeProjectFileCreateOnly, toolsDir: TOOLS, readFile: readFileSync,
273
- replaceFile: writeContainedFileAtomic, platform: process.platform,
238
+ log: console.log, error: console.error, writeFile: writeProjectFileCreateOnly, toolsDir: TOOLS, platform: process.platform,
274
239
  spawn: (argv, options) => spawnSync(argv[0], argv.slice(1), options), ...io };
275
240
  if (plan.variant === 'hook-checks') return applyHookChecks(plan, resolved);
276
241
  const created = [];
@@ -308,7 +273,7 @@ export const applyGitHooks = (plan, io = {}) => {
308
273
  if (hook.state === 'no-hooks-dir' || hook.armed) return EXIT_OK;
309
274
  const path = join(hooksDir, 'pre-commit');
310
275
  resolved.error(hook.state === 'unreadable' ? `${path} is unreadable (${hook.code}) after the installer exited 0`
311
- : `${path} carries no commit-guard line after the installer exited 0 — an installer older than the arm ignores --commit-guard; refreshing ${INSTALLER_REL} from the kit's references/scripts/ copy is your own step`);
276
+ : `${path} carries no commit-guard line after the installer exited 0 — ${UPGRADE_ROUTE}`);
312
277
  return EXIT_INCOMPLETE;
313
278
  };
314
279
 
@@ -297,7 +297,7 @@ export const WHATS = Object.freeze({
297
297
  'gate-hook': '{n} declared gate(s) prompt per run — the gate-approval hook is not wired',
298
298
  'gate-hook.marker-stale': 'the declaration carries the lcovProducer key but the placed hook predates it — the hook goes dark and every gate prompts',
299
299
  'commit-guard': 'the gate matrix is final-run-capable but no commit-guard arms the pre-commit hook — a commit needs no green receipt yet',
300
- 'hook-checks': 'the pre-commit hook lacks this kit\'s {checks} — the kit arms each line, refreshing a known-prior installer first',
300
+ 'hook-checks': 'the pre-commit hook lacks this kit\'s {checks} — the kit arms each line',
301
301
  enforcement: ENFORCEMENT_WHAT,
302
302
  'read-lane': 'the gate hook is wired but the read-only compound lane is off — pipes/chains of seeded reads still prompt one by one',
303
303
  'read-lane.stale': 'the read-lane is ON but the placed gate hook is stale — an old hook never reads lanes.json, so the lane is silently dark; reseed it',
@@ -1,10 +1,9 @@
1
1
  // script-priors.mjs — the APPEND-ONLY catalog of every enforcement-script body this family has shipped
2
2
  // into a project's `scripts/`, as sha256 digests, and the ONE classifier a refresh asks before it
3
- // replaces a deployed script — the spec-layer ensure for its pairs, the `hook-checks` writer for the
4
- // hook installer alone and the upgrade's `scripts` ensure for every other kit script: `current`
5
- // (byte-equal to the bundled copy) · `prior` (a body a release shipped, never edited since) · `custom`
6
- // (anything else — kept aside and replaced only by the replace run the user's yes starts). The
7
- // lens-region idiom (AD-041) over whole script bodies.
3
+ // replaces a deployed script — the spec-layer ensure for its pairs and the upgrade's `scripts` ensure
4
+ // for every other kit script: `current` (byte-equal to the bundled copy) · `prior` (a body a release
5
+ // shipped, never edited since) · `custom` (anything else — kept aside and replaced only by the replace
6
+ // run the user's yes starts). The lens-region idiom (AD-041) over whole script bodies.
8
7
  //
9
8
  // Append discipline: when a release changes one of PRIOR_FILES, append the OUTGOING body's row here
10
9
  // in the same release and copy its bytes to test/fixtures/script-priors/<firstShipped>/<file>.txt —
@@ -59,6 +58,7 @@ export const SCRIPT_PRIORS = Object.freeze([
59
58
  prior('install-git-hooks.mjs', '8.3.0', '8.3.0', 'aa21b3dcbfc48ea1db7a33ed5a5c8cf30d911b266386b67159288cd12d28bc38'),
60
59
  prior('install-git-hooks.test.mjs', '8.3.0', '8.3.0', '058ac6de4dd5f83c4f09c8afd72ef2bfda365a9aea55bddd0089ce89a4e941e2'),
61
60
  prior('install-git-hooks-repo-exec.test.mjs', '8.3.0', '8.3.0', 'd5a3253fa0cd088733b927f2a7187c6484298f11dec48f6f63953e380b071c9a'),
61
+ prior('archive-decisions.mjs', '8.1.3', '8.4.0', '2e1c378fe8a395440dc17a712643a549487e87f958f9d6ec5922dced876421ad'),
62
62
  ]);
63
63
 
64
64
  export const digestOf = (bytes) => createHash('sha256').update(bytes).digest('hex');