@sabaiway/agent-workflow-kit 23.4.0 → 23.5.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,44 @@ 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.5.0 — a rotation run that fails no longer loses journal entries or resolved issues (AD-233)
8
+
9
+ **After `/agent-workflow-kit upgrade`, `run.mjs archive-changelog` and `run.mjs archive-issues` keep every entry and
10
+ every issue when a run stops halfway** (a full disk, a read-only file, a crash, a killed process); the next run
11
+ finishes the job. Before, a stop between two writes could lose the entries being moved.
12
+
13
+ - **Every file is written whole**, beside its target and swapped in with one rename, so an interrupted write leaves the
14
+ old file intact.
15
+ - **The changelog rotation keeps a carry**, `docs/ai/history/changelog.carry`, written before any other file and
16
+ removed last; the next run takes its entries back and prints one `restored from` line for each entry no other file
17
+ held. While a carry stands, `archive-changelog --check` is red and names the command that finishes the rotation.
18
+ - **The issues rotation writes the archive first and never adds an issue twice**, so a rerun after a failure adds
19
+ nothing twice.
20
+ - **A red run of either rotation opens with its failure**: one red block on standard output, first the failure, then
21
+ the places it names and the fix; a `package.json` that exists and cannot be read is now a red block that names it,
22
+ where the run used the folder's name before (a missing one, or one that is not valid JSON, still gives the folder's
23
+ name).
24
+ - The upgrade places three new script files in `scripts/agent-workflow/` (`shared/verdict-block.mjs`,
25
+ `archives/whole-write.mjs`, `archives/rotation-conservation.mjs`) before the rotations that use them; nothing to do
26
+ by hand. Memory 11.1.0 carries the same scripts.
27
+
28
+ ## 23.4.1 — a check that cannot read its input fails instead of passing (AD-232)
29
+
30
+ **`coverage-check --check` now fails when it cannot read the status of its lcov file, and `review-state --check`,
31
+ `review-state --await` and `commit-guard --check` now fail when they cannot list `docs/plans`.** Before, a permission
32
+ error or a disk error there read as "no lcov file" or "no plan in flight", and the check passed while it had seen
33
+ nothing. Each failure names the path and the error code and exits 1. A file or folder that does not exist means
34
+ what it meant before: nothing to check.
35
+
36
+ - **Plain `review-state` and `review-state --json` also exit 1** when `docs/plans` cannot be listed, and the help
37
+ text of `review-state` and `coverage-check` says so.
38
+ - **No check in the kit's `tools/` reads a file when it is loaded.** The kit's list of its own scripts is read when a
39
+ check first needs it, so a failed read reaches the check as its own failure, never as a crash on start. The changelog
40
+ and known-issues rotations still read `package.json` when they load.
41
+ - **The kit's own tests now run every check command against a failure at each kind of read**, and a check that
42
+ passes under one is a failing test. It found three of the four cases above; `commit-guard --check` shares
43
+ review-state's listing of `docs/plans`.
44
+
7
45
  ## 23.4.0 — the judge's model is a setting you choose once (AD-229)
8
46
 
9
47
  **You now pick the Jev version the judge asks in `/agent-workflow-kit bridge-settings`, from the versions the bridge
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.0'
6
+ version: '23.5.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.0",
6
+ "version": "23.5.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.0",
3
+ "version": "23.5.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",
@@ -55,6 +55,7 @@
55
55
  "!tools/**/*.test.mjs",
56
56
  "!tools/manifest/fixtures/**",
57
57
  "!tools/project-rules/fixtures/**",
58
+ "!tools/checker-verdict/**",
58
59
  "!references/scripts/**/*.test.mjs",
59
60
  "!references/scripts/archives/index.mjs",
60
61
  "!references/scripts/test-support/**"
@@ -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 = a LOUD `skipped-no-lcov` (exit 0, stated — produce the file via the unit-tests gate's lcov reporters); 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).
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).
@@ -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
@@ -85,11 +85,12 @@
85
85
  //
86
86
  // Dependency-free, Node >= 22. Deployed at a consumer's scripts/agent-workflow/archives/ like its siblings.
87
87
 
88
- import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync, readdirSync, rmSync, statSync, realpathSync, openSync, fsyncSync, closeSync } from 'node:fs';
88
+ import { readFileSync, existsSync, mkdirSync, readdirSync, statSync, realpathSync } from 'node:fs';
89
89
  import { dirname, resolve, join, posix, relative, isAbsolute } from 'node:path';
90
90
  import { fileURLToPath } from 'node:url';
91
91
  import { spawnSync } from 'node:child_process';
92
- import { createHash, randomBytes } from 'node:crypto';
92
+ import { createHash } from 'node:crypto';
93
+ import { fsIo, writeWhole } from './whole-write.mjs';
93
94
  import { tmpdir } from 'node:os';
94
95
  import { tokenizeMarkdown, findProjectRoot } from '../shared/index.mjs';
95
96
 
@@ -532,66 +533,6 @@ export const verifyRewriteConservation = (plan) => {
532
533
  const summarizeRewrites = (plans) =>
533
534
  plans.flatMap((plan) => plan.rewrites.map((rw) => `${plan.rel}:${rw.line} ${rw.old} → ${rw.new}`));
534
535
 
535
- // ── whole-file writes (a temporary file beside the target, then one rename) ─────────────
536
-
537
- // The fs seams: every file the rotator writes goes through deps.writeFileSync, every rename through
538
- // deps.renameSync, every removal through deps.rmSync, every sync through deps.fsyncSync. onChange fires once a
539
- // project file has changed.
540
- const fsIo = (deps = {}, onChange = () => {}) => {
541
- const rename = deps.renameSync ?? renameSync;
542
- const remove = deps.rmSync ?? rmSync;
543
- return {
544
- write: deps.writeFileSync ?? writeFileSync,
545
- fsync: deps.fsyncSync ?? fsyncSync,
546
- remove,
547
- rename: (from, to) => {
548
- rename(from, to);
549
- onChange();
550
- },
551
- removeFile: (path) => {
552
- remove(path);
553
- onChange();
554
- },
555
- };
556
- };
557
-
558
- const fsyncPath = (io, path, flags = 'r') => {
559
- const fd = openSync(path, flags);
560
- try {
561
- io.fsync(fd);
562
- } finally {
563
- closeSync(fd);
564
- }
565
- };
566
- const DIRECTORY_FSYNC_UNSUPPORTED = ['EINVAL', 'ENOTSUP', 'EOPNOTSUPP', 'EPERM', 'EISDIR'];
567
-
568
- // An interruption leaves the target whole — its old bytes or its new ones: the temporary file, named per run
569
- // so no earlier run's leftover meets the exclusive create, is created exclusively, synced, then renamed over
570
- // the target. A failed write removes it, never a name another writer holds; its name never ends in .md, so no
571
- // reader of the store takes a leftover for a document.
572
- const writeWhole = (io, path, content) => {
573
- const temp = `${path}.${process.pid}-${randomBytes(4).toString('hex')}.tmp`;
574
- try {
575
- io.write(temp, content, { encoding: 'utf8', flag: 'wx' });
576
- fsyncPath(io, temp, 'r+'); // Windows flushes a file only through a handle open for writing
577
- io.rename(temp, path);
578
- } catch (err) {
579
- if (err?.code !== 'EEXIST') {
580
- try {
581
- io.remove(temp, { force: true });
582
- } catch (cleanupErr) {
583
- err.message += ` (its temporary file ${temp} was left: ${cleanupErr.message})`;
584
- }
585
- }
586
- throw err;
587
- }
588
- try {
589
- fsyncPath(io, dirname(path));
590
- } catch (err) {
591
- if (!DIRECTORY_FSYNC_UNSUPPORTED.includes(err?.code)) throw err; // the rename is complete either way
592
- }
593
- };
594
-
595
536
  export const writeInboundRewrites = (root, plans, io = fsIo()) => {
596
537
  // Two passes (the plan is computed pre-write, D4): verify the LIVE bytes of EVERY planned file
597
538
  // first, then write — a drift anywhere refuses with NOTHING written in the rewrite phase.