@sabaiway/agent-workflow-kit 23.4.1 → 23.6.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,48 @@ 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
+ ## 23.6.0 — a changed file that a test runs elsewhere can be committed through the final run (AD-234)
8
+
9
+ **After `/agent-workflow-kit upgrade`, a project can list in `docs/ai/coverage-declared.json` the changed files that
10
+ nothing runs at their own path** — a fixture a test copies out and runs in a temporary folder, for example — each with
11
+ a reason. Before, such a file had no executed line in the coverage data, so `coverage-check` failed it on every
12
+ `run-gates --final` and the commit could not pass the guard.
13
+
14
+ - **The list is written by hand**, one exact path per entry:
15
+ `{ "schema": 1, "entries": [{ "path": "tools/fixture.mjs", "reason": "copied out and run by fixture.test.mjs" }] }`.
16
+ - **An entry can remove a coverage failure**: a listed changed file with no executed line in the coverage data is
17
+ not judged and is printed with its reason; a listed file that the run does execute is judged as any other file.
18
+ An entry naming a path git knows that is not a regular file (a link, a folder) fails the check, changed or not.
19
+ - **Every run prints the list's lines** (`coverage-check: declared list — …`), and `run-gates` echoes them under a
20
+ green coverage gate, so nothing is skipped silently.
21
+ - **The final run binds the list**: `run-gates --final` records its hash in the receipt, and `commit-guard` refuses a
22
+ list edited, created or deleted after that run. A list that is not valid fails the check with one line naming the
23
+ defect.
24
+ - **Without the file nothing changes.** One exception: `run-gates --final` now stops before it starts unless git
25
+ names one work tree for the project (a git environment pointing elsewhere included, which the commit guard
26
+ already refused), and its refusal names the git location it found and why.
27
+
28
+ ## 23.5.0 — a rotation run that fails no longer loses journal entries or resolved issues (AD-233)
29
+
30
+ **After `/agent-workflow-kit upgrade`, `run.mjs archive-changelog` and `run.mjs archive-issues` keep every entry and
31
+ every issue when a run stops halfway** (a full disk, a read-only file, a crash, a killed process); the next run
32
+ finishes the job. Before, a stop between two writes could lose the entries being moved.
33
+
34
+ - **Every file is written whole**, beside its target and swapped in with one rename, so an interrupted write leaves the
35
+ old file intact.
36
+ - **The changelog rotation keeps a carry**, `docs/ai/history/changelog.carry`, written before any other file and
37
+ removed last; the next run takes its entries back and prints one `restored from` line for each entry no other file
38
+ held. While a carry stands, `archive-changelog --check` is red and names the command that finishes the rotation.
39
+ - **The issues rotation writes the archive first and never adds an issue twice**, so a rerun after a failure adds
40
+ nothing twice.
41
+ - **A red run of either rotation opens with its failure**: one red block on standard output, first the failure, then
42
+ the places it names and the fix; a `package.json` that exists and cannot be read is now a red block that names it,
43
+ where the run used the folder's name before (a missing one, or one that is not valid JSON, still gives the folder's
44
+ name).
45
+ - The upgrade places three new script files in `scripts/agent-workflow/` (`shared/verdict-block.mjs`,
46
+ `archives/whole-write.mjs`, `archives/rotation-conservation.mjs`) before the rotations that use them; nothing to do
47
+ by hand. Memory 11.1.0 carries the same scripts.
48
+
7
49
  ## 23.4.1 — a check that cannot read its input fails instead of passing (AD-232)
8
50
 
9
51
  **`coverage-check --check` now fails when it cannot read the status of its lcov file, and `review-state --check`,
package/README.md CHANGED
@@ -257,8 +257,8 @@ file), or run the guarded `/agent-workflow-kit uninstall`.
257
257
  | `/agent-workflow-kit rules` | any time | **your project rules** — the kit lays down default rules per theme (the first is project layout: where code, tests and specs live) in `docs/ai/rules/<theme>.md`; your own rules go into `docs/ai/rules/local/<theme>.md` and win where they differ. Tell the agent in plain words what to change: it shows the exact text first and writes your local file only on your yes, then rebuilds the effective file `docs/ai/rules/effective/<theme>.md` that agents read (merging your rules over the kit’s by meaning) and checks it is current. It also drops your local rules on request. Never commits. |
258
258
  | `/agent-workflow-kit grounding` | any time | **grounded-review facts assembler** — mechanizes populating `agy-review --facts @f`: slices your entry-point's **Hard Constraints** section verbatim (exactly one match, else a loud stop) and/or a plan's three canon sections (`## Goal and boundary` + `## Module ledger` + `## Verification`, each required; duplicates stop), under the same byte budget the agy wrapper enforces (minus `--reserve-bytes` for the artifact share), with a loud tail-trim on overflow. `--autonomy` (AD-044) appends the COMPUTED effective autonomy policy from the git-top `docs/ai/autonomy.json` (every red-line + per-activity level, stated source line; absent file → the computed defaults ARE the policy, exit 0; a malformed policy fails CLOSED, exit 1). `--extra <text|@file>` (repeatable) appends your own facts **byte-verbatim** after the mechanical sections, so the merge is a tool input rather than a shell append — an `@file` must sit inside the proven git work tree (never the git dir) or the system temp surface, and is read through a no-follow descriptor (a FIFO cannot block it, a symlink leaf cannot substitute its target). Prints to stdout; `--out` writes **one scratch file only** — system-temp outside the repo ($TMPDIR / /tmp, rewritable) or a **fresh** gitignored in-repo path (create-only, exclusive write; an existing in-repo file, even gitignored, is refused — the `.env` clobber class); tracked, not-ignored-in-repo, other outside-repo, and symlink/non-regular destinations are all refused. Never commits, never runs a subscription CLI. |
259
259
  | `/agent-workflow-kit core-evidence` | any time | **the ONE loop-evidence writer** (strip-the-kit) — every core evidence record lands in a single append-only JSONL store inside the git dir (never committable; versioned schema, latest-per-key supersession, byte-identical duplicates refused, malformed lines fail every reader closed). `red-proof "<file>#<pattern>"` declares an observed-red **BEFORE a bugfix** (N/N red runs + content custody + base + the pre-fix fingerprint; green/mixed/timeout are DISTINGUISHED refusals — nothing written); `degrade --backend --reason` is the ONLY escape for an unavailable review backend (per-tree, never all backends); `summary` renders the whole loop state statelessly (gate result · per-backend verdicts · red-proofs · degrades) — no ledger, no rounds, nothing remembered. Honest residual: records are forgeable — self-discipline, not a security boundary. Never commits, never runs a subscription CLI. |
260
- | `/agent-workflow-kit coverage-check` | any time | **the final-run checker** (D3(c)+(d)) — **certifies coverage ONLY inside the `--final` run that owns the lcov** (ownership is exclusive by CONVENTION over the fixed path, not enforced — a concurrent writer to it is a stated residual, queued as LCOV-EXCLUSIVE-OWNERSHIP): an artifact on disk proves nothing about the tree it came from, so a standalone run prints its findings and states `attested=no` / `NO VERDICT` rather than a PASS (an lcov that predates an edit would otherwise certify a line the suite never executed). `attested=` claims a verdict was ISSUED, pass or fail — a run over uncovered lines still reads `attested=yes` and still exits 1, and a run whose coverage arm never executed (no lcov) reads `attested=no` even inside `--final`, because nothing was read and nothing is certified. The runner passes a nonce whose one-way commitment over `{nonce, fingerprint, base}` is the `final-start.attempt` it recorded; a context describing another tree, or matching no recorded attempt, is a REFUSAL, never a verdict. Findings are unchanged — reads the lcov the declared `unit-tests` gate produced at the FIXED git-dir path and fails on any uncovered CHANGED executable Node line (listed `file:line`; a changed file absent from the map is a file-level red; out-of-domain/unsupported files are LISTED — the claim narrowed honestly); VERIFIES every current-base red-proof declaration (bound test exists · custody hash unchanged · green N/N now · pre-fix fingerprint differs); prints `lcov-sha256=<hex|none>` of the exact bytes it consumed — the sha the `--final` receipt binds and re-hashes. An absent lcov is a LOUD `skipped-no-lcov`; a symlinked path is a refusal. `--check` is the gate exit code — declare it as the LAST gate (`run-gates --final` refuses otherwise). Read-only. |
261
- | `/agent-workflow-kit commit-guard` | any time | **the read-only pre-commit guard** (D10) — makes the commit capture the whole current working tree, so «verified» and «about to be committed» are the same bytes (the receipt itself has a stated residual — see the mode doc). FIRST it refuses an **INDEX that lags the verified working tree** (the gates and the fingerprint describe the WORKING tree while `git commit` takes the INDEX alone, and the fingerprint cannot tell them apart — so a lagging index used to ship a strict subset of what was verified): unstaged tracked paths or reviewable untracked-not-ignored paths, named up to a bounded cap with the remainder stated, a dirty tracked **submodule** named separately with its own recovery, and fail-closed on an undecidable probe. This deliberately blocks a partial commit. Then it binds the LATEST completed `run-gates --final` receipt to the EXACT current tree: refuses on a missing/red/stale receipt, fingerprint drift under the run, a dangling later attempt, declaration content drift, evidence-hash or lcov drift, or unsatisfied review obligations (the same review-state decision, recomputed over a sanitized env — forged out-of-repo stores never satisfy). Re-runs NO gate or test. Wire it into `.git/hooks/pre-commit` (the installer writes the RESOLVED invocation). `git commit --no-verify` stays the stated residual. |
260
+ | `/agent-workflow-kit coverage-check` | any time | **the final-run checker** (D3(c)+(d)) — **certifies coverage ONLY inside the `--final` run that owns the lcov** (ownership is exclusive by CONVENTION over the fixed path, not enforced — a concurrent writer to it is a stated residual, queued as LCOV-EXCLUSIVE-OWNERSHIP): an artifact on disk proves nothing about the tree it came from, so a standalone run prints its findings and states `attested=no` / `NO VERDICT` rather than a PASS (an lcov that predates an edit would otherwise certify a line the suite never executed). `attested=` claims a verdict was ISSUED, pass or fail — a run over uncovered lines still reads `attested=yes` and still exits 1, and a run whose coverage arm never executed (no lcov) reads `attested=no` even inside `--final`, because nothing was read and nothing is certified. The runner passes a nonce whose one-way commitment over `{nonce, fingerprint, base}` is the `final-start.attempt` it recorded; a context describing another tree, or matching no recorded attempt, is a REFUSAL, never a verdict. Findings are unchanged — reads the lcov the declared `unit-tests` gate produced at the FIXED git-dir path and fails on any uncovered CHANGED executable Node line (listed `file:line`; a changed file absent from the map is a file-level red; out-of-domain/unsupported files are LISTED — the claim narrowed honestly); VERIFIES every current-base red-proof declaration (bound test exists · custody hash unchanged · green N/N now · pre-fix fingerprint differs); prints `lcov-sha256=<hex|none>` of the exact bytes it consumed — the sha the `--final` receipt binds and re-hashes. An absent lcov is a LOUD `skipped-no-lcov`; a symlinked path is a refusal. A file nothing runs at its repository path (a fixture a test copies out and runs elsewhere) can be listed by hand, with a reason, in `docs/ai/coverage-declared.json`: when the lcov records no executed line for that changed file it is not judged and is printed with its reason on every run, and `--final` binds the list into its receipt. `--check` is the gate exit code — declare it as the LAST gate (`run-gates --final` refuses otherwise). Read-only. |
261
+ | `/agent-workflow-kit commit-guard` | any time | **the read-only pre-commit guard** (D10) — makes the commit capture the whole current working tree, so «verified» and «about to be committed» are the same bytes (the receipt itself has a stated residual — see the mode doc). FIRST it refuses an **INDEX that lags the verified working tree** (the gates and the fingerprint describe the WORKING tree while `git commit` takes the INDEX alone, and the fingerprint cannot tell them apart — so a lagging index used to ship a strict subset of what was verified): unstaged tracked paths or reviewable untracked-not-ignored paths, named up to a bounded cap with the remainder stated, a dirty tracked **submodule** named separately with its own recovery, and fail-closed on an undecidable probe. This deliberately blocks a partial commit. Then it binds the LATEST completed `run-gates --final` receipt to the EXACT current tree: refuses on a missing/red/stale receipt, fingerprint drift under the run, a dangling later attempt, declaration content drift, evidence-hash or lcov drift, a declared coverage list (`docs/ai/coverage-declared.json`) the receipt did not bind, or unsatisfied review obligations (the same review-state decision, recomputed over a sanitized env — forged out-of-repo stores never satisfy). Re-runs NO gate or test. Wire it into `.git/hooks/pre-commit` (the installer writes the RESOLVED invocation). `git commit --no-verify` stays the stated residual. |
262
262
  | `/agent-workflow-kit recommendations` | any time (every `upgrade` ends with it) | **read-only deployment advisor** (AD-044) — computes what in THIS deployment is configured sub-optimally (allowlist not seeded, autonomy render drifted, OS sandbox unavailable, gates undeclared, bridge friction, sandbox-mask clutter, a feature-spec layer never adopted) and renders **verdict-first**: one composed verdict line (does anything need attention?), then each item as **{severity · what · one-line benefit · an optional `recipe:` line (the bridge-tier item's missing-entries line — each missing entry by kind: allow rules, exclusions, hosts, state dirs, then what the execution wrapper codex-exec needs, then the host condition; the worktrees-dir ack fallback for a host that ignores the settings key, the agents hidden-mode reconcile follow-up, a user item's own facts, the spec-adoption decline preview, or another offer's decline preview) · the exact consent-gated apply one-liner}**; `references/advisor-writers.md` names each variant's writer or user step. The agent PRESENTS the section in the user's conversational language — every fact and count, nothing added or dropped; commands, paths, hosts and rule strings byte-exact; raw tool block on request — and runs EXACTLY the rendered one-liners and the follow-up commands required by the mode doc, only on the answer authorizing that step — your yes to apply or your explicit decline to record it — with a second yes where the mode doc requires it, surfacing each item's posture note first; a kit item it applies with no question, its check line first, the harness's own dialog the only ask, or the one plain step where auto mode refuses its check or apply. Renders **present-even-when-empty** (`no recommendations — flow optimal.`); a failed probe degrades to a stated skip line. Registry strings are fact-true frozen one-line data (posture/risk notes live in the mode doc at the consent moment); `velocity --bridge-tier` seeds the used bridges' review allow rules, `<wrapper> *` exclusions (`codex-exec *` where an execute slot delegates, keeping its permission prompt), declared hosts into `sandbox.network.allowedDomains`, and home-relative state dirs into `sandbox.filesystem.allowWrite`; hosts and dirs come from the kit service fragments (`agent-workflow-kit/tools/services/`) each bridge's `capability.json` names in `services`, then from your own services list (`services.json` beside the bridge settings file, Mode: setup), and the advisor's `bridge-tier` item counts and names each missing one. `--cwd` is required (the target project is explicit); writes nothing, never commits, never runs a subscription CLI. |
263
263
  | `/agent-workflow-kit doc-parity` | any time | **read-only doc-parity lint** (AD-049) — kills the doc-drift class where a mode-contract doc silently lags a code constant (a `--check` doc still reading `300` after the diff cap moved to `400`): a **closed, exported registry** binds each live constant (review caps, schema versions, the ledger's own class/scope vocabulary, and the autonomy-doctor EXIT/status/trusted-dir contract) to the exact token its `references/modes/*.md` contract must carry, and asserts the CURRENT value renders into every bound file — a drifted doc, an unreadable file, or an absent token **fails closed**. The values are sourced from the live imports (never re-typed), so the lint can't itself go stale; adding a binding is adding a checked entry (closed-world, edit-safe). `--check` is the gate exit code a kit maintainer runs: the lint checks the kit's own package. Never writes, never commits, never runs a subscription CLI. |
264
264
  | `/agent-workflow-kit dispatch` | any time | **the delegation engine** — makes "how much does delegating a sub-task actually buy?" a measured number instead of a feeling. `check <file>` validates a sub-task brief's contract block and exits 0/1 naming the first violated field — **form only**: whether the task is genuinely bounded, its design decided and its acceptance adequate stays your judgment, and a well-formed absurdity passes here by construction. `advise --step-class <c>` answers the question that comes BEFORE that one — which vehicle should carry this kind of sub-task, whether it is even present on this machine, and what the ledger has already recorded for threads of that class (finished, failed, closed without a fold, and still open — counted separately) — and it decides nothing: it refuses no dispatch, gates no verb, and a choice that diverges from the advice is noted rather than blocked. It reads the filesystem only: nothing is launched to find out what is installed, an absent ledger prints "no recorded history", an unreadable one prints the store's own words, and either way the advice still prints. The same block appears as a footer under a form-valid `check` — never under a refusal, so it can never hide one. `register` pre-registers an acceptance wave (step classes, pairing key, minimum observations per class, the mean and first-pass thresholds) so the bar can never be chosen after the results it judges — immutable per wave. `observe` records ONE hand-written observation (`solo-construction`, the baseline whose ratio is 1 by construction — except over a scope measuring zero bytes, which has no ratio at all and is recorded ineligible by name — or `self-reported`) — delegated numbers are never hand-written, they are derived. The writer verbs are where that derivation happens: `open` puts a delegated thread on the record with every mint-time field copied from the brief's own header, refusing a deadline the wrapper's cap plus its kill grace would not fit inside, and recording whether the tree it started from was clean against the thread's base — HEAD by default, or the tree `--checkpoint <oid>` names, so the second task of a story is measured over the first one's uncommitted work instead of opening dirty (a dirty one makes the result honestly unmeasurable rather than quietly counted), while `--task <brief>` also records which task brief the thread carries out and the files that brief lists, refusing, since the last commit, a task thread whose files overlap by path prefix those of an open task thread or of a folded thread of another brief (`files-overlap`), and a mix of the two kinds — an untasked open beside an open task thread or, for a `code` open of backend `codex`, after a task fold, and a task open beside an open untasked thread (`mixed-open`), refusing at open a Files path the snapshot scope can never hold (`task-files-scope`), and measuring a task thread over its files alone, so `return` and `fold` refuse a changed path that no open or folded task thread on the same base claims (`out-of-files`); `await` waits for that one dispatch to answer and writes nothing — only the finished receipt satisfies it, a run still holding the nonce means keep waiting, and a wait that runs out says so with its own exit code, names whether the deadline or your own timeout ended it, and authorizes nothing: a wait that ended without an answer is a question for you, never permission to dispatch again; `return` absorbs the receipt the wrapper minted — only a finished one, checked against the contract it actually ran, its deadline and its own report, and refused outright when the tree hides changes from git or moves while the return is being computed — and derives the bytes from git rather than from anyone's claim; `fold` is the acceptance, and it refuses if the tree moved since the return — precisely, it re-confirms **equality of the visible canonical payload**, which is a change detector rather than a cryptographic identity of the tree: under the default head base that payload's untracked section is unframed and carries no file mode, so a content or symlink target that imitates the marker opening the next entry can alias two trees, and making an untracked file executable moves nothing (both named as residuals in the mode doc, with the fix queued); under a checkpoint base it is one indexed diff that carries modes. A change set carrying a binary, a non-regular path, a submodule, or a symlink whose target is not valid UTF-8 is **refused** at `return` and `fold` — CONSERVATIVELY, rather than promise what the default head payload may not be able to follow — and the same refusals hold for a checkpoint thread. `degrade` closes a thread that never earned a fold, on the record and with its reason. `aggregate` prints one wave: the registered thresholds, every observation as context, and per step class the finished threads — a folded success with git-provable bytes contributes its ratio, one whose bytes are unprovable is excluded from the mean but still counts in the first-pass rate, and a failed thread, a degrade-closed one, or one folded after failing acceptance each count as a real zero. Below the registered minimum nothing is computed (insufficient); at or above it is computed and labeled PILOT evidence. It REFUSES rather than guessing: no pre-registration, an unfinished thread in scope, a recorded refusal-to-delegate that never opened a thread, or an ambiguous wave each stop the computation by name. `handoff-return --slug <s>` closes the worktree loop after `land --prepare`: it re-attests that main still holds exactly the prepared tree under the same HEAD (both recorded in the handoff at prepare time), prints the satellite handoff's user-owned content byte for byte with its boundaries, byte lengths and the main-owned destinations each part folds into, prints the handoff digest and both OIDs as its proof, states the after-the-fold order (a fold landed after the gates leaves them stale), and records ONE self-reported worktree-stream observation only when the whole prepared change set is measurable — a deletion, a rename, a symlink, a submodule or a mode-only change ends with a named NOT RECORDED instead, never a partial number. Appends only to its own ledger inside the git dir (never committable); it also writes `handoff-return`'s `write-tree` tree object and, for a checkpoint measurement, the leaf's OWN temporary index file and the blobs its forced adds store — never a ref, never the real index; never commits, never runs a subscription CLI. |
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: '23.4.1'
6
+ version: '23.6.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": "23.4.1",
6
+ "version": "23.6.0",
7
7
  "provides": [],
8
8
  "roles": {},
9
9
  "detect": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sabaiway/agent-workflow-kit",
3
- "version": "23.4.1",
3
+ "version": "23.6.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",
@@ -13,7 +13,7 @@ Run `node ${CLAUDE_SKILL_DIR}/tools/commit-guard.mjs --check [--cwd <dir>]` —
13
13
  5. fingerprint before ≠ after on the receipt (the tree moved UNDER the final run);
14
14
  6. a LATER `final-start` whose attempt never completed (interrupted run / failed receipt append — an attempt of unknown outcome never lets an earlier green stand);
15
15
  7. declaration content drift (the current `docs/ai/gates.json` {id, cmd} array no longer matches the receipt's recorded one);
16
- 8. evidence-hash drift (the store's canonical red-proof/degrade serializations moved under the receipt) or lcov drift (the consumed file's sha moved or vanished);
16
+ 8. evidence-hash drift (the store's canonical red-proof/degrade serializations moved under the receipt) or lcov drift (the consumed file's sha moved or vanished), or a declared coverage list `docs/ai/coverage-declared.json` the receipt did not bind — created, edited, deleted or unreadable after the run (the list may sit outside the fingerprint when git ignores it, so its hash rides `evidenceHashes.coverageDeclared`; a receipt of an earlier kit stands only while no list stands);
17
17
  9. unsatisfied review obligations — the SAME normative decision `review-state --check` computes (configured recipe backends, ship-class-only on the latest normal receipt, veto, the explicit degrade escape), recomputed over a SANITIZED env: the guard resolves FIXED git-dir paths for its own reads and ignores `AW_REVIEW_RECEIPTS`/`AW_CORE_EVIDENCE` (producer test seams are never guard inputs — a forged out-of-repo store never satisfies).
18
18
 
19
19
  **The empty-commit lane is a PASS that attests NOTHING — and it consults no receipt.** A content-free fingerprint over a CLEAN index means the index contributes no tree-content delta, so the commit changes no tree content: `git commit --allow-empty`, a message- or signature-only `--amend`, an empty merge. (What such a commit DOES change — its message, its parents, its signature — was never in the guard's domain.) The guard passes and says exactly that, because its whole claim is about the bytes a commit carries and here there are none. The receipt arms are SKIPPED rather than satisfied: the content-free fingerprint is the one value every clean moment shares, so a receipt found there cannot be correlated to THIS moment or base — letting it decide would make the outcome depend on which stray moment the store recorded last, the same reason `flow-check`'s `#65` rung steps over a content-free RED. The flow arm still runs (the commit still moves HEAD, and the chain bookkeeping is about that), with its own fingerprint-keyed correlations dropped through the explicit `treeCarriesBytes: false` the guard declares — the checker never derives that fact, because a routine clean-tree check still wants those rungs.
@@ -7,7 +7,7 @@ The **final-run checker** (strip-the-kit D3(c)+(d)) — two deterministic arms o
7
7
  Run `node ${CLAUDE_SKILL_DIR}/tools/coverage-check.mjs --check [--cwd <dir>]`:
8
8
 
9
9
  0. **Attestation precondition (the provenance arm).** An lcov on disk carries no evidence of the tree it came from, so reading one and issuing a verdict certifies whatever happens to be there — the false GREEN direction is the dangerous one, because a line appended AFTER the suite ran has no `DA` entry and therefore reads non-executable ("nothing to cover"). Provenance is a CONSEQUENCE in exactly one context: a `run-gates --final` run deletes the artifact before any gate spawns. That runner mints a random nonce and writes `final-start.attempt` as a ONE-WAY COMMITMENT over `{nonce, tree fingerprint, base}`; the raw nonce rides the environment to this child, which recomputes the commitment and requires the record to carry it. Neither half suffices alone — a bare nonce is unverifiable, a persisted attempt id is reconstructible from public repo state — and the commitment is also the only place the BASE is bound, since no record stores it. The raw nonce is stripped from the red-proof probe environment so no descendant retains a live capability. `attested=` states whether a coverage VERDICT was ISSUED — pass **or** fail — never whether coverage passed: a valid handshake over an lcov that lists uncovered lines still reads `attested=yes` and still exits 1. Outcomes: **attested** → the coverage verdict is issued; **no handshake** → `attested=no` + `NO VERDICT` (exit 0, findings still printed, uncovered lines still exit 1 — the findings contract is unchanged); **a valid handshake over a run that read NO lcov BYTES** (the file is absent, or the path was refused as a non-regular file) → `attested=no` + `NO VERDICT`: the run owned the artifact's lifetime and read nothing, so it certifies NOTHING — reading `yes` there would be the false green this arm exists to close, one layer up. The predicate is the consumed bytes (`lcov-sha256` is a digest, not `none`), never the skip flag, so a refused path can never attest either. The two halves are independent: WITHHOLDING the verdict never changes an exit code — an absent file stays exit 0 (the loud `skipped-no-lcov`), and the refused non-regular path keeps its OWN fail-closed exit 1; **a handshake describing another tree or matching no recorded attempt** → `REFUSED` (exit 1), never a verdict in either direction. One fully anchored `coverage-check: attested=<yes|no>` machine line rides every run, on the same exactly-once contract as the sha line — and a withheld verdict TRAVELS: `run-gates` carries it as `coverage=not-run` on the summary line and names it on the checker's table row, and `core-evidence summary` never renders an unqualified GREEN over a final record that consumed no lcov. Stated residuals, both named rather than implied: (a) an operator who runs both processes can forge the store or the code — the kit's standing self-discipline posture, not a security boundary; (b) **"the run owns the artifact" is exclusive by CONVENTION over the fixed path, not enforced** — a writer outside the run (a second `run-gates`, a hand-run `--only unit-tests`, an orphaned test process) can place foreign evidence between the deletion and the checker's read, and every check then agrees. Closing (b) needs an attempt-unique artifact path, which the runner can name but the declared producer cmd must reference — queued as LCOV-EXCLUSIVE-OWNERSHIP. What this arm removes is the false green that needs no second process and nobody trying: evidence that predates the edit.
10
- 1. **Coverage arm (D3(d)):** every CHANGED executable Node line (`.mjs`/`.cjs`/`.js`, tracked working-vs-HEAD changes + untracked-not-ignored files) must be covered — uncovered lines are LISTED `file:line` and fail; a changed file ABSENT from the lcov map is a file-level red (never "non-executable" by silence); changed out-of-domain files (e.g. `.sh`) and unsupported-source files (e.g. `.ts`) are LISTED — the claim is narrowed honestly, not widened. NO lcov file at the path (ENOENT) = a LOUD `skipped-no-lcov` (exit 0, stated — produce the file via the unit-tests gate's lcov reporters); any other status failure exits 1 naming the path and the code where it has one; a symlink at the path is a refusal (lstat, no-follow).
10
+ 1. **Coverage arm (D3(d)):** every CHANGED executable Node line (`.mjs`/`.cjs`/`.js`, tracked working-vs-HEAD changes + untracked-not-ignored files) must be covered — uncovered lines are LISTED `file:line` and fail; a changed file ABSENT from the lcov map is a file-level red (never "non-executable" by silence); changed out-of-domain files (e.g. `.sh`) and unsupported-source files (e.g. `.ts`) are LISTED — the claim is narrowed honestly, not widened. NO lcov file at the path (ENOENT) = a LOUD `skipped-no-lcov` (exit 0, stated — produce the file via the unit-tests gate's lcov reporters); any other status failure exits 1 naming the path and the code where it has one; a symlink at the path is a refusal (lstat, no-follow). **The declared list:** a project may name in `docs/ai/coverage-declared.json` — a strict config written by hand, `{ "schema": 1, "entries": [{ "path": "<exact repo path>", "reason": "<one line>" }] }` — changed files nothing runs at their repository path (a fixture a test copies out and runs elsewhere). A listed changed file with no executed line in the lcov this run read is not judged and is printed with its reason; one with an executed line is judged as any other file; every line about the list prints on every run. An unreadable or malformed list fails (exit 1) and applies nothing. Under a final run the list must be the one the run started with, or the checker REFUSES.
11
11
  2. **Red-proof arm (D3(c)):** every authoritative current-base `red-proof` declaration must verify — the bound test file exists (deleted fails), its content sha256 matches the declaration (custody), the test resolves (zero-match fails) and runs green N/N NOW, and the declaration's pre-fix fingerprint differs from the current tree (equal = reuse/forgery, refused). A malformed evidence store fails CLOSED.
12
12
 
13
13
  Wire it as the LAST declared gate in `docs/ai/gates.json` — `run-gates --final` REFUSES a declaration where the canonical coverage-check gate is not last (nothing may run after the checker consumed the lcov) or where its cmd is not ONE plain invocation of the kit's OWN tool (a masked form or a lookalike path never counts).
@@ -8,10 +8,10 @@ The **generic project gate runner** — it batches the project's OWN declared ve
8
8
 
9
9
  Run `node ${CLAUDE_SKILL_DIR}/tools/run-gates.mjs [--cwd <project>] [--only <id>]… [--final]`:
10
10
 
11
- 1. **Reads `docs/ai/gates.json`** (strict JSON, hand-editable; seeded from `references/templates/gates.json`). Each gate is `{ id, title, cmd }` plus the optional boolean **`lcovProducer`** (the producer paragraph below) — `id` a unique kebab handle, `cmd` **ONE bash command line** (brace/glob expansion works; a host without bash gets a loud preflight error, exit 6 — never a silent reinterpretation under another shell). The declaration names **WHAT to check, never who executes it** — the schema has no lane/model/routing fields and rejects unknown keys loudly.
12
- 2. **Runs each gate from the project root** and prints a per-gate **PASS/FAIL table** plus **one machine-readable summary line** as the last line (`[run-gates] status=… gates=… passed=… failed=… failed_ids=… coverage=…`). A failing gate's own output is preserved **verbatim** (triage without re-running); a green gate's output is not echoed; gates after a failure still run. **Exit 0 iff all selected gates are green.**
11
+ 1. **Reads `docs/ai/gates.json`** (strict JSON, hand-editable; seeded from `references/templates/gates.json`). Each gate is `{ id, title, cmd }` plus the optional boolean **`lcovProducer`** (the producer paragraph below) — `id` a unique kebab handle, `cmd` **ONE bash command line** (brace/glob expansion works; a host without bash gets a loud preflight error, exit 6, never another shell). The declaration names **WHAT to check, never who executes it** — the schema has no lane/model/routing fields and rejects unknown keys loudly.
12
+ 2. **Runs each gate from the project root** and prints a per-gate **PASS/FAIL table** plus **one machine-readable summary line** as the last line (`[run-gates] status=… gates=… passed=… failed=… failed_ids=… coverage=…`). A failing gate's own output is preserved **verbatim**; a green gate echoes only its checker's every-run lines (size warnings, declared-list lines); gates after a failure still run. **Exit 0 iff all selected gates are green.**
13
13
  3. **Honest outcomes, each distinct — never a silent green:** a **missing** declaration (exit 3 — the report names the recovery: create `docs/ai/gates.json` from the template; `upgrade` re-seeds a missing one), an **empty** `gates` list (exit 4), a **malformed/invalid** declaration (exit 5, loud `path: reason`). Repeatable **`--only <id>`** re-runs a subset; an unknown id is a loud usage error (exit 2). **`--pre-review`** runs the DERIVED mechanical subset (#66): the full matrix minus every gate whose cmd is a canonical kit checker invocation — derivation **matches canonical checker paths in the cmd strings** (realpath-resolved `--check` forms of review-state / commit-guard / coverage-check / flow-check, never a project-authored id), so a project abstracting a checker behind its own script declares it in `flow.pregateExclude` (an unknown id refuses loudly, exit 5). A failing subset gate gets the review-dependent diagnosis, naming the mechanical reset (a declared exclude changes the `subsetDigest`). **Under an ARMED flow (exactly one open adopted chain owned by this worktree) every subset run is RECORDED** as a `subset-attempt` via the flow store's locked append factory — the context keys `{planId, cycle, stepId, foldBatch, subsetDigest}`; index + hard-stop state are computed under the lock against the pre-run identity. **Hard stop (Decision 7/8):** the SECOND red records and exits red; past two reds every attempt needs `--diagnosis "<non-empty, byte-distinct from the prior>"` (recorded, self-servable); the THIRD red EXHAUSTS the context — further solo runs refuse, and only a recorded fresh-eyes consult verdict (a grounded bridge consult-attestation at this round context) reopens ONE further attempt. Armed-but-unrecordable (zero/several open chains, broken store) refuses loudly; a spawn failure records NO attempt; unarmed repos stay byte-unchanged. Mutually exclusive with `--only`/`--final` (exit 2); plain and `--final` runs never load the config.
14
- 4. **`--final`** — the D3(a) final verification run: it REFUSES `--only` (a subset never attests) and a declaration lacking the canonical core checks (ONE plain invocation each of the kit's OWN `review-state.mjs --check` and `coverage-check.mjs --check`, the checker declared LAST — a masked form, a compound, or a lookalike path never counts); deletes the stale git-dir lcov before the suite; exports `AW_GIT_DIR` + `AW_LCOV_FILE` to every gate cmd; records EVERY attempt (start + completed green/red) in the core-evidence store via its sole writer; and binds the receipt to { fingerprint before/after · the full declaration · per-gate results · the canonical red-proof + degrade evidence hashes · the sha of the lcov the checker actually read (exactly ONE `lcov-sha256` machine line, end-re-hashed) · **`evidenceHashes.flow`** when a flow store exists (D10: the sha of the OWNER-SCOPED flow projection — foreign worktrees never move it, except same-fingerprint planId-less globals, which share this tree's decision context; absent store → absent field; a broken store refuses up front) }. An artifact moving UNDER the run — the flow projection included — is a named `integrityFailure`; the receipt lands red. Stated residual: the movement arm is best-effort — an append racing the receipt write is refused at commit by the guard. A receipt that cannot be written is its own distinct outcome (exit 8): green gates never read as success without it. `${CLAUDE_SKILL_DIR}/references/modes/commit-guard.md` consumes the receipt at commit time (the guard re-hashes the live projection against it — a post-final append, or the store vanishing, refuses the commit).
14
+ 4. **`--final`** — the D3(a) final verification run: it REFUSES `--only` (a subset never attests), a git location other than one work tree, and a declaration lacking the canonical core checks (ONE plain invocation each of the kit's OWN `review-state.mjs --check` and `coverage-check.mjs --check`, the checker declared LAST — a masked form, a compound, or a lookalike path never counts); deletes the stale git-dir lcov before the suite; exports `AW_GIT_DIR` + `AW_LCOV_FILE` to every gate cmd; records EVERY attempt (start + completed green/red) in the core-evidence store via its sole writer; and binds the receipt to { fingerprint before/after · the full declaration · per-gate results · the canonical red-proof + degrade evidence hashes · the sha of the lcov the checker actually read (exactly ONE `lcov-sha256` machine line, end-re-hashed) · **`evidenceHashes.flow`** when a flow store exists (D10: the sha of the OWNER-SCOPED flow projection — foreign worktrees never move it, except same-fingerprint planId-less globals, which share this tree's decision context; absent store → absent field; a broken store refuses up front) · **`evidenceHashes.coverageDeclared`** when `docs/ai/coverage-declared.json` stands (an unreadable list refuses up front, exit 8) }. An artifact moving UNDER the run — the flow projection and that list included — is a named `integrityFailure`; the receipt lands red. Stated residual: an append racing the receipt write is refused at commit by the guard. A receipt that cannot be written is its own distinct outcome (exit 8): green gates never read as success without it. `${CLAUDE_SKILL_DIR}/references/modes/commit-guard.md` consumes the receipt at commit time (a post-final flow append, or the store vanishing, refuses the commit).
15
15
 
16
16
  The declaration is **seeded at bootstrap** (the template loop, `${CLAUDE_SKILL_DIR}/references/modes/bootstrap.md` step 6) and **ensured-if-missing on upgrade** from THIS kit's own template twin (`${CLAUDE_SKILL_DIR}/references/modes/upgrade.md` step 3) — independent of the installed memory substrate's age; an existing file is always **preserved byte-for-byte**. It is deliberately **not** a delegation-required memory asset: gates are optional, and absence is an honest runner outcome, not a deployment failure.
17
17
 
@@ -1,62 +1,40 @@
1
1
  #!/usr/bin/env node
2
- // Rolling-window archive for docs/ai/changelog.md.
3
- //
4
- // HOT (changelog.md) — last HOT_DAYS days
5
- // WARM (history/recent.md) — entries HOT_DAYS..WARM_DAYS old
6
- // COLD (history/YYYY-MM.md) — entries older than WARM_DAYS, compressed
7
- // META (history/condensed-index.md) — one-line TL;DRs of every archived entry
8
- //
9
- // The file is read through the shared block tokenizer (markdown-blocks.mjs): headings are
10
- // recognised only OUTSIDE fenced regions, CRLF and trailing whitespace never change the block
11
- // structure, and an unclosed fence is a loud error instead of a silent absorber. On top of the
12
- // tokens this archiver applies its own unit grammar and FAILS CLOSED: a date-shaped heading that
13
- // does not parse as an entry refuses with file:line — it is never glued into the previous entry,
14
- // never duplicated into the footer, never normalised into a different calendar date.
15
- //
16
- // NOTE (multi-year scaling): condensed-index.md grows O(total archived entries) and never sheds, so
17
- // on a multi-year horizon it is the tier that runs out of room first (~1159 lines over 2y in a
18
- // stress test). Its floor is 1500 and its ceiling 3000 (archive-caps.mjs): past the FLOOR every run
19
- // prints a sharding warning, and once the count goes PAST the ceiling the run refuses outright
20
- // rather than stamp a cap it cannot honour — the ceiling itself is still stamped. The remedy is per-year sharding (condensed-index-YYYY.md) — a queued row, never
21
- // something a run decides for itself. Stress-test rotation via the exported pure functions against
22
- // a temp copy seeded with a synthetic multi-year dataset (include burst periods).
23
- //
24
- // Modes:
25
- // (default) run rotation, mutate files in place
26
- // --dry-run print planned distribution, do not change files
27
- // --check exit 1 if changelog.md still holds entries that should be archived
28
- //
29
- // Every mode parses every source AND builds every tier-STAMPED output (WARM, COLD, META) BEFORE any
30
- // write, so a refusal — an unparsable source, or a tier that has outgrown its ceiling — fires
31
- // identically for the default run, --dry-run and --check, and nothing is written on a refused input.
32
- // The HOT changelog is deliberately NOT in that set: buildChangelog passes the file's OWN
33
- // frontmatter through and reaches a literal only when the file carries none. That fallback is
34
- // unguarded, and it is a filed queue row rather than an oversight.
35
- //
36
- // CLI overrides:
37
- // --hot-days=N (default 3)
38
- // --warm-days=N (default 30)
39
- // --today=YYYY-MM-DD (default today UTC) — useful for tests / reproducible runs
40
-
41
- import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, realpathSync } from 'node:fs';
2
+ // The changelog rotation (spec archive-rotations); META grows one line per archived entry, ~1159 lines over 2y in a stress test.
3
+
4
+ import { readFileSync, mkdirSync, readdirSync, existsSync, realpathSync } from 'node:fs';
42
5
  import { resolve, basename } from 'node:path';
43
6
  import { fileURLToPath } from 'node:url';
44
- import { tokenizeMarkdown, findParagraphBreak, fail, findProjectRoot } from '../shared/index.mjs';
45
- import { capFor, countLines, shardingWarning } from './archive-caps.mjs';
7
+ import { tokenizeMarkdown, findParagraphBreak, fail, findProjectRoot,
8
+ composeRedBlock, composeUsageRefusal, guardChecker } from '../shared/index.mjs';
9
+ import { CAP_TABLE, capFor, countLines, shardingWarning } from './archive-caps.mjs';
10
+ import { fsIo, writeWhole } from './whole-write.mjs';
11
+ import { CARRY_REL, readCarry, renderCarry, unionEntries } from './rotation-conservation.mjs';
46
12
 
47
13
  const ROOT = findProjectRoot(import.meta.url);
48
-
14
+ const CHECKER_NAME = 'archive-changelog';
15
+ const PACKAGE_REL = 'package.json';
16
+ const GUARD = Object.freeze({ name: CHECKER_NAME, exitCode: 1, remedy: 'fix the cause the stack below names, then re-run' });
17
+ const INDEX_REL = 'docs/ai/history/condensed-index.md';
18
+ const shown = (text) => text.replace(/\r/g, '\\r').replace(/\n/g, '\\n');
19
+ const composeFailure = (failed, findings, remedy, after = []) => ({
20
+ exitCode: 1,
21
+ lines: composeRedBlock({ name: CHECKER_NAME, failed: shown(failed),
22
+ findings: findings.map(({ place, text }) => ({ place, text: shown(text) })),
23
+ remedies: [shown(remedy)], after }),
24
+ });
49
25
  export const readProjectName = (root) => {
50
26
  try {
51
- const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));
52
- if (pkg.name) return pkg.name;
53
- } catch {
54
- /* no package.json — fall back to repo dir basename */
27
+ const text = readFileSync(resolve(root, PACKAGE_REL), 'utf8');
28
+ try {
29
+ return JSON.parse(text)?.name || basename(root);
30
+ } catch {
31
+ return basename(root);
32
+ }
33
+ } catch (error) {
34
+ if (error.code !== 'ENOENT') throw error;
35
+ return basename(root);
55
36
  }
56
- return basename(root);
57
37
  };
58
- const PROJECT_NAME = readProjectName(ROOT);
59
-
60
38
  const CHANGELOG_REL = 'docs/ai/changelog.md';
61
39
  const HISTORY_REL = 'docs/ai/history';
62
40
  const RECENT_REL = 'docs/ai/history/recent.md';
@@ -94,7 +72,7 @@ const parseArgs = (argv) => {
94
72
  else if (arg.startsWith('--hot-days=')) opts.hotDays = Number(arg.slice('--hot-days='.length));
95
73
  else if (arg.startsWith('--warm-days=')) opts.warmDays = Number(arg.slice('--warm-days='.length));
96
74
  else if (arg.startsWith('--today=')) opts.today = arg.slice('--today='.length);
97
- else throw fail(2, `unknown argument: ${arg}\n${USAGE}`);
75
+ else return { unknown: arg };
98
76
  }
99
77
  return { flags, opts };
100
78
  };
@@ -114,9 +92,7 @@ export const stripTrailingSeparator = (block) => {
114
92
  return lines.join('\n');
115
93
  };
116
94
 
117
- // Parse one tier's text → { frontmatter, preamble, entries, footer }. Fails closed: any
118
- // unit-shaped heading that does not parse as an entry is exit 1 naming `label:line`, and an entry
119
- // appearing after the footer boundary refuses rather than being duplicated into the footer.
95
+ // Refuse malformed date-shaped headings and entries after the footer, naming label:line.
120
96
  export const parseChangelogText = (text, label = 'changelog') => {
121
97
  const { frontmatter, frontLines, lines, headings } = tokenizeMarkdown(text, label);
122
98
  const fileLine = (index) => frontLines + index + 1;
@@ -138,6 +114,7 @@ export const parseChangelogText = (text, label = 'changelog') => {
138
114
  `${label}:${fileLine(heading.index)}: "${heading.text}" is date-shaped but ` +
139
115
  `${year}-${month}-${day} is not a real calendar date — it would previously have been ` +
140
116
  'silently normalised into a different month; fix the date, then re-run.',
117
+ `${label}:${fileLine(heading.index)}`,
141
118
  );
142
119
  }
143
120
  if (footerIdx !== -1) {
@@ -147,6 +124,7 @@ export const parseChangelogText = (text, label = 'changelog') => {
147
124
  `footer boundary at line ${fileLine(footerIdx)} — the footer must be the last section; ` +
148
125
  'it would previously have been silently duplicated into the footer; move the entry ' +
149
126
  'above the footer, then re-run.',
127
+ `${label}:${fileLine(heading.index)}`,
150
128
  );
151
129
  }
152
130
  entryHeadings.push({ index: heading.index, match: m });
@@ -159,6 +137,7 @@ export const parseChangelogText = (text, label = 'changelog') => {
159
137
  'as an entry heading — expected `## YYYY-MM-DD — title` or `## YYYY.MM.DD — title` at ' +
160
138
  'column 0 with a real calendar date. It would previously have been silently absorbed ' +
161
139
  'into the previous entry; fix the heading, then re-run.',
140
+ `${label}:${fileLine(heading.index)}`,
162
141
  );
163
142
  }
164
143
  if (heading.level === 2 && entryHeadings.length > 0 && footerIdx === -1 && NON_ENTRY_H2_RE.test(heading.text)) {
@@ -194,6 +173,7 @@ export const parseChangelogText = (text, label = 'changelog') => {
194
173
  month,
195
174
  day,
196
175
  title: title ?? '',
176
+ line: fileLine(index),
197
177
  block,
198
178
  };
199
179
  });
@@ -358,8 +338,8 @@ export const buildChangelog = ({ frontmatter, preamble, hot, footer, hasArchive
358
338
  // capFor refuses outright past the tier's ceiling; see archive-caps.mjs.
359
339
  const stamped = (tier, render) => render(capFor({ tier, count: countLines(render(0)) }));
360
340
 
361
- export const buildRecent = (entries, todayStr) => {
362
- const preamble = `# Changelog WARM Archive — ${PROJECT_NAME}\n\n> Entries aged **7–30 days** from today. Newer → [\`../changelog.md\`](../changelog.md). Older → [\`condensed-index.md\`](./condensed-index.md) plus per-month \`YYYY-MM.md\` files.`;
341
+ export const buildRecent = (entries, todayStr, projectName = readProjectName(ROOT)) => {
342
+ const preamble = `# Changelog WARM Archive — ${projectName}\n\n> Entries aged **7–30 days** from today. Newer → [\`../changelog.md\`](../changelog.md). Older → [\`condensed-index.md\`](./condensed-index.md) plus per-month \`YYYY-MM.md\` files.`;
363
343
  const body = renderEntries(entries);
364
344
  return stamped('warm', (cap) => `${FRONTMATTER('history', cap, todayStr)}\n${preamble}\n\n---\n\n${body}\n`);
365
345
  };
@@ -370,8 +350,8 @@ export const buildCold = (year, month, entries, todayStr) => {
370
350
  return stamped('cold', (cap) => `${FRONTMATTER('history', cap, todayStr)}\n${preamble}\n\n---\n\n${compressed}\n`);
371
351
  };
372
352
 
373
- export const buildCondensedIndex = (warmEntries, coldByMonth, todayStr) => {
374
- const intro = `# Condensed Index — ${PROJECT_NAME} Changelog\n\n> One-line TL;DR for every archived entry. Each line links to the file holding the full text.`;
353
+ export const buildCondensedIndex = (warmEntries, coldByMonth, todayStr, projectName = readProjectName(ROOT)) => {
354
+ const intro = `# Condensed Index — ${projectName} Changelog\n\n> One-line TL;DR for every archived entry. Each line links to the file holding the full text.`;
375
355
 
376
356
  const lines = [];
377
357
  if (warmEntries.length > 0) {
@@ -399,31 +379,45 @@ export const groupByMonth = (entries) => {
399
379
  return map;
400
380
  };
401
381
 
402
- export const runCli = (argv, deps = {}) => {
403
- const { root = ROOT, log = console.log, logError = console.error } = deps;
382
+ const buildTier = (tier, place, build) => {
383
+ try {
384
+ return build();
385
+ } catch (error) {
386
+ if (error.exitCode && !error.place) throw Object.assign(error, { tier, archivePlace: place });
387
+ throw error;
388
+ }
389
+ };
390
+ const rotate = (argv, root, log, warnings, io) => {
404
391
  try {
405
- const { flags, opts } = parseArgs(argv);
392
+ const { flags, opts, unknown } = parseArgs(argv);
393
+ if (unknown !== undefined) return { exitCode: 2, lines: composeUsageRefusal({
394
+ name: CHECKER_NAME, failed: shown('unknown argument: ' + unknown), usage: USAGE,
395
+ }) };
406
396
  if (flags.help) {
407
397
  log(USAGE);
408
398
  return 0;
409
399
  }
400
+ const project = {};
401
+ try {
402
+ project.name = readProjectName(root);
403
+ } catch (error) {
404
+ return composeFailure(`cannot read ${PACKAGE_REL}: ${error.message.split(/\r\n|[\r\n]/)[0]}`,
405
+ [{ place: PACKAGE_REL, text: "the project's name cannot be read from it" }],
406
+ 'make package.json a readable file, or remove it, then re-run');
407
+ }
410
408
  const cutoffs = computeCutoffs(opts.today, opts.hotDays, opts.warmDays);
411
409
  const todayStr = cutoffs.today.toISOString().slice(0, 10);
412
-
413
410
  const changelogPath = resolve(root, CHANGELOG_REL);
414
411
  const historyDir = resolve(root, HISTORY_REL);
415
412
  const recentPath = resolve(root, RECENT_REL);
416
413
  const indexPath = resolve(historyDir, 'condensed-index.md');
417
414
  const legacyPath = resolve(root, LEGACY_REL);
418
-
419
415
  if (!existsSync(changelogPath)) {
420
- logError(`[archive-changelog] ${CHANGELOG_REL} not found — nothing to do.`);
421
- return 1;
416
+ return composeFailure(`${CHANGELOG_REL} not found`,
417
+ [{ place: CHANGELOG_REL, text: 'the file this rotation reads does not exist' }],
418
+ `create ${CHANGELOG_REL}, then re-run`);
422
419
  }
423
-
424
- // EVERY mode parses EVERY source before any write: a refusal in the main file, the legacy
425
- // archive, recent.md or a monthly COLD file fires identically for the default run, --dry-run
426
- // and --check, naming that file's own file:line — and nothing is written.
420
+ // Every mode parses every source before any write, so a refusal names its file:line and writes nothing.
427
421
  const perFile = {};
428
422
  const parsed = parseChangelogText(readFileSync(changelogPath, 'utf8'), CHANGELOG_REL);
429
423
  perFile[CHANGELOG_REL] = parsed.entries.length;
@@ -449,21 +443,11 @@ export const runCli = (argv, deps = {}) => {
449
443
  }
450
444
  }
451
445
 
452
- // Dedupe by (date + title) — favour the freshest occurrence by file source order.
453
- const seen = new Set();
454
- const allEntries = [
455
- ...parsed.entries,
456
- ...legacyEntries,
457
- ...warmExistingEntries,
458
- ...coldExistingEntries,
459
- ]
460
- .filter((e) => {
461
- const key = `${e.dateStr}|${e.title}`;
462
- if (seen.has(key)) return false;
463
- seen.add(key);
464
- return true;
465
- })
466
- .sort((a, b) => b.dateObj.getTime() - a.dateObj.getTime());
446
+ const carry = readCarry(root);
447
+ const carryEntries = carry === null ? [] : parseChangelogText(carry, CARRY_REL).entries;
448
+ if (carry !== null) perFile[CARRY_REL] = carryEntries.length;
449
+ const { entries: allEntries, lastOnly } = unionEntries([parsed.entries, legacyEntries, warmExistingEntries, coldExistingEntries, carryEntries]);
450
+ allEntries.sort((a, b) => b.dateObj.getTime() - a.dateObj.getTime());
467
451
  const { hot, warm, cold } = categorize(allEntries, cutoffs);
468
452
  const coldByMonth = groupByMonth(cold);
469
453
 
@@ -479,39 +463,33 @@ export const runCli = (argv, deps = {}) => {
479
463
  coldFiles: [...coldByMonth.keys()].sort(),
480
464
  };
481
465
 
482
- // EVERY cap-bearing output is BUILT here, before the mode branch, and capFor refuses a tier that
483
- // has outgrown its ceiling. That refusal has to fire identically in all three modes: a `--check`
484
- // that went green on a corpus the next real run cannot write would be exactly the fail-open the
485
- // parse above already refuses to be. Building is pure — nothing reaches disk until the writes
486
- // below, so a refusal still leaves the tree untouched.
466
+ // Build every cap-bearing tier in every mode before any write; a ceiling refusal leaves the tree untouched.
487
467
  const archives = [];
488
- if (warm.length > 0) archives.push({ path: recentPath, text: buildRecent(warm, todayStr) });
468
+ if (warm.length > 0) archives.push({ path: recentPath,
469
+ text: buildTier('warm', RECENT_REL, () => buildRecent(warm, todayStr, project.name)) });
489
470
  for (const [key, entries] of coldByMonth) {
490
471
  const [year, month] = key.split('-');
491
- archives.push({ path: resolve(historyDir, `${year}-${month}.md`), text: buildCold(year, month, entries, todayStr) });
472
+ const place = `${HISTORY_REL}/${year}-${month}.md`;
473
+ archives.push({ path: resolve(historyDir, `${year}-${month}.md`),
474
+ text: buildTier('cold', place, () => buildCold(year, month, entries, todayStr)) });
492
475
  }
493
476
  if (warm.length > 0 || cold.length > 0) {
494
- const index = buildCondensedIndex(warm, coldByMonth, todayStr);
495
- // The sharding tripwire. META grows O(total) and never sheds, so it is the tier that reaches
496
- // its ceiling first; warning at the floor puts the remedy in front of whoever runs the
497
- // archiver while there is still room, instead of at the ceiling where the run refuses.
477
+ const index = buildTier('meta', INDEX_REL, () => buildCondensedIndex(warm, coldByMonth, todayStr, project.name));
498
478
  const warning = shardingWarning({ tier: 'meta', count: countLines(index) });
499
- if (warning) logError(`[archive-changelog] WARNING: ${warning}`);
479
+ if (warning) warnings.push(`[archive-changelog] WARNING: ${warning}`);
500
480
  archives.push({ path: indexPath, text: index });
501
481
  }
502
482
 
503
483
  if (flags.check) {
484
+ if (carry !== null) return composeFailure(`${CARRY_REL} stands with ${carryEntries.length} entries a rotation run left unfinished`,
485
+ [{ place: CARRY_REL, text: 'a default run stopped before it finished; this file holds every entry that run was moving' }],
486
+ 'complete the rotation with node scripts/agent-workflow/run.mjs archive-changelog', warnings.splice(0));
504
487
  const tooOldInHot = parsed.entries.filter((e) => e.dateObj < cutoffs.hotCutoff);
505
488
  if (tooOldInHot.length > 0) {
506
- logError(
507
- `[archive-changelog] FAIL: ${tooOldInHot.length} entries in ${CHANGELOG_REL} are older than ${opts.hotDays} days (relative to ${todayStr}).`,
508
- );
509
- for (const e of tooOldInHot) logError(` - ${e.dateStr} — ${e.title}`);
510
- logError('Run the changelog archive script (without --check) to rotate.');
511
- return 1;
489
+ return composeFailure(`entries of ${CHANGELOG_REL} older than ${opts.hotDays} days (relative to ${todayStr}): ${tooOldInHot.length}`,
490
+ tooOldInHot.map((entry) => ({ place: `${CHANGELOG_REL}:${entry.line}`, text: `${entry.dateStr} — ${entry.title}` })),
491
+ 'rotate them with node scripts/agent-workflow/run.mjs archive-changelog', warnings.splice(0));
512
492
  }
513
- // The verdict names what it acted on: a zero-entry tier is a DECISION — with the loud path
514
- // above, zero can only mean nothing unit-shaped is present, never a file that failed to parse.
515
493
  log(
516
494
  `[archive-changelog] OK — ${CHANGELOG_REL}: ${parsed.entries.length} parsed entries, all within ` +
517
495
  `${opts.hotDays} days of ${todayStr}; corpus ${allEntries.length} (HOT ${hot.length} / WARM ${warm.length} / COLD ${cold.length}).`,
@@ -526,16 +504,15 @@ export const runCli = (argv, deps = {}) => {
526
504
  }
527
505
 
528
506
  // Zero-corpus policy, default mode: with the loud path above, zero entries across EVERY
529
- // source can only mean genuinely nothing to rotate — a stated no-op, never a gratuitous
530
- // mkdir + rewrite. Checked against allEntries (not just HOT) so an empty HOT never blocks
507
+ // source can only mean genuinely nothing to rotate: no mkdir, no rewrite, only a standing
508
+ // carry removed. Checked against allEntries (not just HOT) so an empty HOT never blocks
531
509
  // servicing existing WARM/COLD entries.
532
510
  if (allEntries.length === 0) {
511
+ if (carry !== null) io.removeFile(resolve(root, CARRY_REL));
533
512
  log('[archive-changelog] nothing to rotate — 0 entries across every source.');
534
513
  return 0;
535
514
  }
536
515
 
537
- mkdirSync(historyDir, { recursive: true });
538
-
539
516
  const newChangelog = buildChangelog({
540
517
  frontmatter: parsed.frontmatter || FRONTMATTER('history', 700, todayStr),
541
518
  preamble: parsed.preamble,
@@ -543,9 +520,11 @@ export const runCli = (argv, deps = {}) => {
543
520
  footer: parsed.footer,
544
521
  hasArchive: warm.length > 0 || cold.length > 0,
545
522
  });
546
- writeFileSync(changelogPath, newChangelog, 'utf8');
547
-
548
- for (const archive of archives) writeFileSync(archive.path, archive.text, 'utf8');
523
+ mkdirSync(historyDir, { recursive: true });
524
+ writeWhole(io, resolve(root, CARRY_REL), renderCarry(allEntries));
525
+ writeWhole(io, changelogPath, newChangelog);
526
+ for (const archive of archives) writeWhole(io, archive.path, archive.text);
527
+ io.removeFile(resolve(root, CARRY_REL));
549
528
 
550
529
  log('[archive-changelog] migrated:');
551
530
  log(` HOT (${CHANGELOG_REL}): ${hot.length}`);
@@ -553,11 +532,29 @@ export const runCli = (argv, deps = {}) => {
553
532
  for (const key of coldByMonth.keys()) {
554
533
  log(` COLD (${HISTORY_REL}/${key}.md): ${coldByMonth.get(key).length}`);
555
534
  }
535
+ for (const entry of lastOnly) log(`[archive-changelog] restored from ${CARRY_REL}: ${entry.dateSource} — ${entry.title}`);
556
536
  return 0;
557
537
  } catch (err) {
558
- logError(`[archive-changelog] ${err.message}`);
559
- return err.exitCode ?? 1;
538
+ if (err.exitCode && err.place) return composeFailure(`cannot parse ${err.place.replace(/:\d+$/, '')}`,
539
+ [{ place: err.place, text: err.message.slice(err.place.length + 2) }], 'fix the place named above, then re-run');
540
+ if (err.exitCode && err.archivePlace) return composeFailure(`the ${err.tier} tier ${err.archivePlace} is past its ceiling`,
541
+ [{ place: err.archivePlace, text: err.message }], CAP_TABLE[err.tier].remedy);
542
+ throw err;
543
+ }
544
+ };
545
+ export const runCli = (argv, deps = {}) => {
546
+ const { root = ROOT, log = console.log, logError = console.error } = deps;
547
+ const greenLines = [];
548
+ const warnings = [];
549
+ const io = fsIo(deps);
550
+ const answer = guardChecker(GUARD, () => rotate(argv, root, (line) => greenLines.push(line), warnings, io));
551
+ if (typeof answer === 'number') {
552
+ for (const warning of warnings) logError(warning);
553
+ for (const line of greenLines) log(line);
554
+ return answer;
560
555
  }
556
+ for (const line of [...answer.lines, ...warnings]) log(line);
557
+ return answer.exitCode;
561
558
  };
562
559
 
563
560
  // Run main() only when executed directly, never on import. Compare by REAL path: an entry point