@sabaiway/agent-workflow-kit 23.4.1 → 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,27 @@ 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
+
7
28
  ## 23.4.1 — a check that cannot read its input fails instead of passing (AD-232)
8
29
 
9
30
  **`coverage-check --check` now fails when it cannot read the status of its lcov file, and `review-state --check`,
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.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.1",
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.1",
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",
@@ -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.
@@ -1,54 +1,36 @@
1
1
  #!/usr/bin/env node
2
- // Rotate resolved issues from docs/ai/known_issues.md → docs/ai/history/issues-resolved.md.
3
- //
4
- // The file is read through the shared block tokenizer (markdown-blocks.mjs). The section model:
5
- // H2 and H3 heading tokens bound chunks; an H3 chunk is a SECTION, everything else — the preamble,
6
- // category H2s (## 🔴 Open / ## 🟢 Resolved) and the trailing `---` + blockquote footer — is a
7
- // FILE-structural chunk that survives every rotation untouched. A section contains only its own
8
- // issue. Rewrites are VERBATIM: kept chunks re-emit byte-exact, archived sections land in the
9
- // archive byte-exact, so kept + archive conserve the input line for line.
10
- //
11
- // Archivability (Decision 7): a recognised, line-leading, dated resolution marker decides ALONE —
12
- // strikethrough on the heading is cosmetic. The marker is the FIRST `**Status:**` / `**Resolved:**`
13
- // field line (list-item prefix optional, fenced samples ignored):
14
- // - **Resolved:** <date> … the taught shape (see the template)
15
- // - **Status:** ✅ FIXED (<date>) … legacy
16
- // - **Status:** **Resolved** (FIXED <date>, …) …
17
- // Both separators (YYYY-MM-DD / YYYY.MM.DD) read, with a strict calendar round-trip. Arm C: a
18
- // resolution claim with NO recognisable date, or a malformed/impossible date, REFUSES loudly with
19
- // file:line in every mode — never a silent skip. An explicit non-resolved Status (Open, Mitigated)
20
- // classifies open; a later stray date never overrides it.
21
- //
22
- // Modes:
23
- // (default) append archivable sections to history/issues-resolved.md, remove from known_issues.md
24
- // --dry-run print plan, no file changes
25
- // --check exit 1 if known_issues.md still has archivable issues
26
- //
27
- // Every mode parses and classifies BEFORE any write, so a refusal fires identically for the
28
- // default run, --dry-run and --check, and nothing is written on a refused input.
29
- //
30
- // CLI:
31
- // --cutoff-days=N (default 14)
32
- // --today=YYYY-MM-DD (default UTC today)
2
+ // The issues rotation (spec archive-rotations).
33
3
 
34
- import { readFileSync, writeFileSync, mkdirSync, existsSync, realpathSync } from 'node:fs';
4
+ import { readFileSync, mkdirSync, existsSync, realpathSync } from 'node:fs';
35
5
  import { resolve, basename } from 'node:path';
36
6
  import { fileURLToPath } from 'node:url';
37
- import { tokenizeMarkdown, fail, findProjectRoot } from '../shared/index.mjs';
7
+ import { tokenizeMarkdown, fail, findProjectRoot, composeRedBlock, composeUsageRefusal, guardChecker } from '../shared/index.mjs';
8
+ import { fsIo, writeWhole } from './whole-write.mjs';
9
+ import { trimmedLines, sectionsToAppend } from './rotation-conservation.mjs';
38
10
 
39
11
  const ROOT = findProjectRoot(import.meta.url);
40
-
12
+ const CHECKER_NAME = 'archive-issues';
13
+ const PACKAGE_REL = 'package.json';
14
+ const GUARD = Object.freeze({ name: CHECKER_NAME, exitCode: 1, remedy: 'fix the cause the stack below names, then re-run' });
15
+ const shown = (text) => text.replace(/\r/g, '\\r').replace(/\n/g, '\\n');
16
+ const composeFailure = (failed, findings, remedy) => ({
17
+ exitCode: 1,
18
+ lines: composeRedBlock({ name: CHECKER_NAME, failed: shown(failed),
19
+ findings: findings.map(({ place, text }) => ({ place, text: shown(text) })), remedies: [shown(remedy)] }),
20
+ });
41
21
  export const readProjectName = (root) => {
42
22
  try {
43
- const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));
44
- if (pkg.name) return pkg.name;
45
- } catch {
46
- /* no package.json — fall back to repo dir basename */
23
+ const text = readFileSync(resolve(root, PACKAGE_REL), 'utf8');
24
+ try {
25
+ return JSON.parse(text)?.name || basename(root);
26
+ } catch {
27
+ return basename(root);
28
+ }
29
+ } catch (error) {
30
+ if (error.code !== 'ENOENT') throw error;
31
+ return basename(root);
47
32
  }
48
- return basename(root);
49
33
  };
50
- const PROJECT_NAME = readProjectName(ROOT);
51
-
52
34
  const KNOWN_REL = 'docs/ai/known_issues.md';
53
35
  const HISTORY_REL = 'docs/ai/history';
54
36
  const RESOLVED_REL = 'docs/ai/history/issues-resolved.md';
@@ -114,15 +96,12 @@ const parseArgs = (argv) => {
114
96
  else if (arg === '--help' || arg === '-h') flags.help = true;
115
97
  else if (arg.startsWith('--cutoff-days=')) opts.cutoffDays = Number(arg.slice('--cutoff-days='.length));
116
98
  else if (arg.startsWith('--today=')) opts.today = arg.slice('--today='.length);
117
- else throw fail(2, `unknown argument: ${arg}\n${USAGE}`);
99
+ else return { unknown: arg };
118
100
  }
119
101
  return { flags, opts };
120
102
  };
121
103
 
122
- // Parse → { frontmatter, frontLines, sections }. A chunk's `heading` is the trailing-whitespace-free
123
- // token text (null for the preamble and the footer); `structural` marks chunks that belong to the
124
- // FILE; `lines` stay byte-exact for re-emission; `start` is the chunk's body-line index; `fenced`
125
- // holds chunk-relative indexes of fenced lines so classification never reads a fenced sample.
104
+ // Sections retain byte-exact lines, body-relative starts and section-relative fenced indexes.
126
105
  export const parseKnownIssues = (text, label = KNOWN_REL) => {
127
106
  const { frontmatter, frontLines, lines, headings, fencedLines } = tokenizeMarkdown(text, label);
128
107
 
@@ -135,13 +114,13 @@ export const parseKnownIssues = (text, label = KNOWN_REL) => {
135
114
  'canonical issue heading — expected `### Issue-NNN — title` (level 3, column 0, exactly ' +
136
115
  'one space, ~~strikethrough~~ optional). It would previously have been silently glued ' +
137
116
  'into the section above it or declassified to prose; fix the heading, then re-run.',
117
+ `${label}:${frontLines + heading.index + 1}`,
138
118
  );
139
119
  }
140
120
  if (heading.level === 2 || heading.level === 3) boundaries.set(heading.index, heading);
141
121
  }
142
122
 
143
- // The trailing footer belongs to the FILE: a terminal run of blank / blockquote lines introduced
144
- // by a `---` thematic break (outside any fence), whose quote text IS the canonical closing note.
123
+ // Only an unfenced terminal `---` + canonical quote run belongs to the file, not the issue.
145
124
  let footerStart = -1;
146
125
  let tail = lines.length - 1;
147
126
  while (tail >= 0 && !fencedLines.has(tail) && (matchable(lines[tail]) === '' || FOOTER_QUOTE_RE.test(lines[tail]))) tail -= 1;
@@ -183,10 +162,8 @@ export const parseKnownIssues = (text, label = KNOWN_REL) => {
183
162
  return { frontmatter, frontLines, sections };
184
163
  };
185
164
 
186
- // Partition tripwire: the concatenated chunks must reproduce the body EXACTLY — element-wise, in
187
- // order — or nothing proceeds. Unreachable through a correct chunk loop by construction — it
188
- // exists so a future edit that drops, duplicates or reorders lines (an equal-cardinality
189
- // corruption included) refuses BEFORE any write instead of silently losing data.
165
+ // Refuse before any write if chunks fail to reproduce the body element-wise and in order,
166
+ // including equal-cardinality corruption a future edit to the chunk loop might introduce.
190
167
  export const verifySectionPartition = (sections, bodyLines, label = KNOWN_REL) => {
191
168
  const rebuilt = sections.flatMap((s) => s.lines);
192
169
  const exact = rebuilt.length === bodyLines.length && rebuilt.every((line, i) => line === bodyLines[i]);
@@ -195,6 +172,7 @@ export const verifySectionPartition = (sections, bodyLines, label = KNOWN_REL) =
195
172
  1,
196
173
  `${label}: internal section-model error — the ${rebuilt.length}-line section partition does ` +
197
174
  `not reproduce the ${bodyLines.length}-line body; refusing before any write.`,
175
+ label,
198
176
  );
199
177
  }
200
178
  };
@@ -264,41 +242,44 @@ export const classifySection = (section, cutoffDate) => {
264
242
  return { kind: ISSUE_TITLE_RE.test(title) ? 'open' : 'other' };
265
243
  };
266
244
 
267
- export const buildResolvedFile = (existing, newSections, todayStr) => {
245
+ export const buildResolvedFile = (existing, newSections, todayStr, projectName = readProjectName(ROOT)) => {
268
246
  const header = existing
269
247
  ? existing
270
- : `---\ntype: history\nlastUpdated: ${todayStr}\nscope: permanent\nstaleAfter: never\nowner: none\nmaxLines: 3500\n---\n\n# Resolved Issues — ${PROJECT_NAME}\n\n> Append-only archive of issues closed > 14 days ago. Sourced from \`../known_issues.md\`.\n\n---\n`;
248
+ : `---\ntype: history\nlastUpdated: ${todayStr}\nscope: permanent\nstaleAfter: never\nowner: none\nmaxLines: 3500\n---\n\n# Resolved Issues — ${projectName}\n\n> Append-only archive of issues closed > 14 days ago. Sourced from \`../known_issues.md\`.\n\n---\n`;
271
249
  if (newSections.length === 0) return header;
272
- // Sections are appended VERBATIM — every archived CONTENT line lands in the archive byte-exact.
273
- // Only the trailing blank run (the source's section separator) is normalised to exactly one
274
- // blank line, the same droppable-decoration accounting the changelog conservation harness uses.
275
- // Blank trimming is per-ELEMENT (trim() eats a CR), and the separator follows the block's own
276
- // line-ending flavor — a CRLF corpus gets exact `\r\n\r\n` separators, never mixed EOL runs.
250
+ // Preserve content verbatim; trim only trailing blank elements (trim() eats a CR).
251
+ // One blank separator follows each block's EOL flavor, as the conservation harness allows.
277
252
  const blocks = newSections
278
253
  .map((s) => {
279
- const kept = [...s.lines];
280
- while (kept.length > 0 && kept[kept.length - 1].trim() === '') kept.pop();
254
+ const kept = trimmedLines(s);
281
255
  const separator = kept.length > 0 && kept[kept.length - 1].endsWith('\r') ? '\n\r\n' : '\n\n';
282
256
  return kept.join('\n') + separator;
283
257
  })
284
258
  .join('');
285
- // The header/blocks separator follows the HEADER's own EOL flavor, and the trailing run
286
- // collapses to ONE terminator of its own flavor — an existing CRLF archive never gains a
287
- // mixed `\r\n\n` run on append. (An archive whose existing content and new blocks use
288
- // different flavors stays mixed at that boundary by nature; only runs are guaranteed pure.)
259
+ // Header separators and the single final terminator retain their own EOL flavors.
260
+ // Only runs stay pure; differing header/block flavors remain mixed at their boundary.
289
261
  const headerEndsBlank = /(\r?\n){2}$/.test(header);
290
262
  const headerEol = header.endsWith('\r\n') ? '\r\n' : '\n';
291
263
  return (header + (headerEndsBlank ? '' : headerEol) + blocks).replace(/(\r?\n)+$/, '$1');
292
264
  };
293
-
294
- export const runCli = (argv, deps = {}) => {
295
- const { root = ROOT, log = console.log, logError = console.error } = deps;
265
+ const rotate = (argv, root, log, io) => {
296
266
  try {
297
- const { flags, opts } = parseArgs(argv);
267
+ const { flags, opts, unknown } = parseArgs(argv);
268
+ if (unknown !== undefined) return { exitCode: 2, lines: composeUsageRefusal({
269
+ name: CHECKER_NAME, failed: shown('unknown argument: ' + unknown), usage: USAGE,
270
+ }) };
298
271
  if (flags.help) {
299
272
  log(USAGE);
300
273
  return 0;
301
274
  }
275
+ const project = {};
276
+ try {
277
+ project.name = readProjectName(root);
278
+ } catch (error) {
279
+ return composeFailure(`cannot read ${PACKAGE_REL}: ${error.message.split(/\r\n|[\r\n]/)[0]}`,
280
+ [{ place: PACKAGE_REL, text: "the project's name cannot be read from it" }],
281
+ 'make package.json a readable file, or remove it, then re-run');
282
+ }
302
283
  const today = opts.today
303
284
  ? new Date(`${opts.today}T00:00:00Z`)
304
285
  : new Date(new Date().toISOString().slice(0, 10) + 'T00:00:00Z');
@@ -311,38 +292,33 @@ export const runCli = (argv, deps = {}) => {
311
292
  const resolvedPath = resolve(root, RESOLVED_REL);
312
293
 
313
294
  if (!existsSync(knownIssuesPath)) {
314
- logError(`[archive-issues] ${KNOWN_REL} not found — nothing to do.`);
315
- return 1;
295
+ return composeFailure(`${KNOWN_REL} not found`,
296
+ [{ place: KNOWN_REL, text: 'the file this rotation reads does not exist' }],
297
+ `create ${KNOWN_REL}, then re-run`);
316
298
  }
317
-
318
299
  const { frontmatter, frontLines, sections } = parseKnownIssues(readFileSync(knownIssuesPath, 'utf8'), KNOWN_REL);
319
300
  const classified = sections.map((s) => ({ section: s, ...classifySection(s, cutoffDate) }));
320
301
 
321
- // Arm C: a resolution claim the parser cannot date — or contradictory open/resolved state —
322
- // is a refusal in EVERY mode, before any write.
323
302
  const loud = classified.filter((c) => c.kind === 'fixed-undated' || c.kind === 'bad-date' || c.kind === 'conflict');
324
303
  if (loud.length > 0) {
325
- for (const c of loud) {
304
+ const findings = loud.map((c) => {
326
305
  const line = frontLines + c.section.start + (c.markerLine ?? 0) + 1;
306
+ const place = `${KNOWN_REL}:${line}`;
327
307
  if (c.kind === 'conflict') {
328
308
  const openLine = frontLines + c.section.start + c.openLine + 1;
329
- logError(
330
- `[archive-issues] ${KNOWN_REL}:${line}: "${c.marker.trim()}" contradicts the explicit open status ` +
309
+ return { place, text: `"${c.marker.trim()}" contradicts the explicit open status ` +
331
310
  `"${c.openMarker.trim()}" (line ${openLine}) — an issue is either open or resolved; delete the ` +
332
- 'stale line, then re-run.',
333
- );
334
- } else {
335
- logError(
336
- c.kind === 'bad-date'
337
- ? `[archive-issues] ${KNOWN_REL}:${line}: resolution marker date "${c.raw}" in "${c.marker.trim()}" ` +
311
+ 'stale line, then re-run.' };
312
+ }
313
+ return { place, text: c.kind === 'bad-date'
314
+ ? `resolution marker date "${c.raw}" in "${c.marker.trim()}" ` +
338
315
  'is not a valid calendar date in one separator form (YYYY-MM-DD or YYYY.MM.DD) — fix the date, then re-run.'
339
- : `[archive-issues] ${KNOWN_REL}:${line}: "${(c.marker ?? c.section.heading).trim()}" claims resolution ` +
316
+ : `"${(c.marker ?? c.section.heading).trim()}" claims resolution ` +
340
317
  'but carries no recognisable date — add a line-leading `- **Resolved:** YYYY-MM-DD` (or ' +
341
- '`- **Status:** … FIXED (YYYY-MM-DD)`). Previously this section was silently skipped forever.',
342
- );
343
- }
344
- }
345
- return 1;
318
+ '`- **Status:** … FIXED (YYYY-MM-DD)`). Previously this section was silently skipped forever.' };
319
+ });
320
+ return composeFailure(`sections claiming a resolution the rotation cannot accept in ${KNOWN_REL}: ${loud.length}`,
321
+ findings, 'fix each section named above, then re-run');
346
322
  }
347
323
 
348
324
  const archivable = classified.filter((c) => c.kind === 'archivable');
@@ -358,13 +334,10 @@ export const runCli = (argv, deps = {}) => {
358
334
 
359
335
  if (flags.check) {
360
336
  if (archivable.length > 0) {
361
- logError(`[archive-issues] FAIL: ${archivable.length} archivable issues found in ${KNOWN_REL}.`);
362
- for (const c of archivable) logError(` - ${c.section.heading.trim()}`);
363
- logError('Run the issues archive script (without --check) to rotate.');
364
- return 1;
337
+ return composeFailure(`archivable issues in ${KNOWN_REL}: ${archivable.length}`,
338
+ archivable.map((c) => ({ place: `${KNOWN_REL}:${frontLines + c.section.start + 1}`, text: c.section.heading.trim() })),
339
+ 'archive them with node scripts/agent-workflow/run.mjs archive-issues');
365
340
  }
366
- // The verdict names what it acted on — with the loud path in the parser, a low section
367
- // count can only mean the sections are genuinely absent, never a file that failed to parse.
368
341
  log(
369
342
  `[archive-issues] OK — ${KNOWN_REL}: ${issueSectionCount} issue sections (${countLine || 'none'}), ` +
370
343
  `0 archivable with a recognised date older than ${cutoffStr} (cutoff ${opts.cutoffDays} days, relative to ${todayStr}).`,
@@ -387,32 +360,32 @@ export const runCli = (argv, deps = {}) => {
387
360
  return 0;
388
361
  }
389
362
 
390
- mkdirSync(historyDir, { recursive: true });
391
363
  const existing = existsSync(resolvedPath) ? readFileSync(resolvedPath, 'utf8') : '';
392
- const updatedResolved = buildResolvedFile(existing, archivable.map((c) => c.section), todayStr);
393
- writeFileSync(resolvedPath, updatedResolved, 'utf8');
394
-
395
- // VERBATIM rebuild: the kept chunks re-emit byte-exact in original order — structural chunks
396
- // (preamble, category H2s, the footer) survive by construction, nothing is re-flowed.
397
- const rebuilt =
398
- frontmatter +
399
- classified
400
- .filter((c) => c.kind !== 'archivable')
401
- .flatMap((c) => c.section.lines)
402
- .join('\n');
403
- writeFileSync(knownIssuesPath, rebuilt, 'utf8');
364
+ const bare = (section) => (section.structural ? section : parseKnownIssues(section.lines.join('\n'), RESOLVED_REL).sections[0]);
365
+ const pending = sectionsToAppend(parseKnownIssues(existing, RESOLVED_REL).sections, archivable.map((c) => c.section), bare);
366
+ const updatedResolved = buildResolvedFile(existing, pending, todayStr, project.name);
367
+ const rebuilt = frontmatter + classified.filter((c) => c.kind !== 'archivable').flatMap((c) => c.section.lines).join('\n');
368
+ mkdirSync(historyDir, { recursive: true });
369
+ writeWhole(io, resolvedPath, updatedResolved);
370
+ writeWhole(io, knownIssuesPath, rebuilt);
404
371
 
405
372
  log(`[archive-issues] archived ${archivable.length} issue(s) to ${RESOLVED_REL}`);
406
373
  return 0;
407
374
  } catch (err) {
408
- logError(`[archive-issues] ${err.message}`);
409
- return err.exitCode ?? 1;
375
+ if (err.exitCode && err.place) return composeFailure(`cannot parse ${err.place.replace(/:\d+$/, '')}`,
376
+ [{ place: err.place, text: err.message.slice(err.place.length + 2) }], 'fix the place named above, then re-run');
377
+ throw err;
410
378
  }
411
379
  };
412
-
413
- // Run main() only when executed directly, never on import. Compare by REAL path: an entry point
414
- // reached through a symlink resolves to its target, so a raw string compare reads the two as
415
- // different and the CLI never runs. realpathSync collapses the link so both sides match.
380
+ export const runCli = (argv, deps = {}) => {
381
+ const { root = ROOT, log = console.log } = deps;
382
+ const io = fsIo(deps);
383
+ const answer = guardChecker(GUARD, () => rotate(argv, root, log, io));
384
+ if (typeof answer === 'number') return answer;
385
+ for (const line of answer.lines) log(line);
386
+ return answer.exitCode;
387
+ };
388
+ // Run only directly; realpathSync makes a symlinked entry match its target too.
416
389
  const isDirectRun = (() => {
417
390
  const invoked = process.argv[1];
418
391
  if (!invoked) return false;
@@ -0,0 +1,45 @@
1
+ // Rotation conservation (spec rotation-conservation).
2
+
3
+ import { readFileSync } from 'node:fs';
4
+ import { resolve } from 'node:path';
5
+
6
+ export const CARRY_REL = 'docs/ai/history/changelog.carry';
7
+
8
+ export const readCarry = (root) => {
9
+ try {
10
+ return readFileSync(resolve(root, CARRY_REL), 'utf8');
11
+ } catch (error) {
12
+ if (error.code === 'ENOENT') return null;
13
+ throw error;
14
+ }
15
+ };
16
+
17
+ export const renderCarry = (entries) => entries.map((entry) => entry.block).join('\n\n---\n\n');
18
+
19
+ export const unionEntries = (sources) => {
20
+ const seen = new Set();
21
+ const entries = [];
22
+ const lastOnly = [];
23
+ for (const [index, source] of sources.entries()) {
24
+ for (const entry of source) {
25
+ const identity = `${entry.dateStr}|${entry.title}`;
26
+ if (seen.has(identity)) continue;
27
+ seen.add(identity);
28
+ entries.push(entry);
29
+ if (index === sources.length - 1) lastOnly.push(entry);
30
+ }
31
+ }
32
+ return { entries, lastOnly };
33
+ };
34
+
35
+ export const trimmedLines = (section) => {
36
+ const lines = [...section.lines];
37
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '') lines.pop();
38
+ return lines;
39
+ };
40
+
41
+ export const sectionsToAppend = (archiveSections, sections, bare) => {
42
+ const key = (section) => JSON.stringify(trimmedLines(bare(section)));
43
+ const archived = new Set(archiveSections.map(key));
44
+ return sections.filter((section) => !archived.has(key(section)));
45
+ };
@@ -0,0 +1,63 @@
1
+ // The whole-file write (spec rotation-conservation).
2
+
3
+ import { writeFileSync, renameSync, rmSync, openSync, fsyncSync, closeSync } from 'node:fs';
4
+ import { dirname } from 'node:path';
5
+ import { randomBytes } from 'node:crypto';
6
+
7
+ // The fs seams: every file the rotator writes goes through deps.writeFileSync, every rename through
8
+ // deps.renameSync, every removal through deps.rmSync, every sync through deps.fsyncSync. onChange fires once a
9
+ // project file has changed.
10
+ export const fsIo = (deps = {}, onChange = () => {}) => {
11
+ const rename = deps.renameSync ?? renameSync;
12
+ const remove = deps.rmSync ?? rmSync;
13
+ return {
14
+ write: deps.writeFileSync ?? writeFileSync,
15
+ fsync: deps.fsyncSync ?? fsyncSync,
16
+ remove,
17
+ rename: (from, to) => {
18
+ rename(from, to);
19
+ onChange();
20
+ },
21
+ removeFile: (path) => {
22
+ remove(path);
23
+ onChange();
24
+ },
25
+ };
26
+ };
27
+
28
+ const fsyncPath = (io, path, flags = 'r') => {
29
+ const fd = openSync(path, flags);
30
+ try {
31
+ io.fsync(fd);
32
+ } finally {
33
+ closeSync(fd);
34
+ }
35
+ };
36
+ const DIRECTORY_FSYNC_UNSUPPORTED = ['EINVAL', 'ENOTSUP', 'EOPNOTSUPP', 'EPERM', 'EISDIR'];
37
+
38
+ // An interruption leaves the target whole — its old bytes or its new ones: the temporary file, named per run
39
+ // so no earlier run's leftover meets the exclusive create, is created exclusively, synced, then renamed over
40
+ // the target. A failed write removes it, never a name another writer holds; its name never ends in .md, so no
41
+ // reader of the store takes a leftover for a document.
42
+ export const writeWhole = (io, path, content) => {
43
+ const temp = `${path}.${process.pid}-${randomBytes(4).toString('hex')}.tmp`;
44
+ try {
45
+ io.write(temp, content, { encoding: 'utf8', flag: 'wx' });
46
+ fsyncPath(io, temp, 'r+'); // Windows flushes a file only through a handle open for writing
47
+ io.rename(temp, path);
48
+ } catch (err) {
49
+ if (err?.code !== 'EEXIST') {
50
+ try {
51
+ io.remove(temp, { force: true });
52
+ } catch (cleanupErr) {
53
+ err.message += ` (its temporary file ${temp} was left: ${cleanupErr.message})`;
54
+ }
55
+ }
56
+ throw err;
57
+ }
58
+ try {
59
+ fsyncPath(io, dirname(path));
60
+ } catch (err) {
61
+ if (!DIRECTORY_FSYNC_UNSUPPORTED.includes(err?.code)) throw err; // the rename is complete either way
62
+ }
63
+ };
@@ -17,12 +17,15 @@
17
17
  { "path": "archives/archive-issues.mjs", "role": "deployed", "seed": false },
18
18
  { "path": "archives/archive-decisions.mjs", "role": "deployed", "seed": true },
19
19
  { "path": "archives/archive-caps.mjs", "role": "deployed", "seed": false },
20
+ { "path": "archives/whole-write.mjs", "role": "deployed", "seed": true },
21
+ { "path": "archives/rotation-conservation.mjs", "role": "deployed", "seed": false },
20
22
  { "path": "archives/index.mjs", "role": "support" },
21
23
  { "path": "archives/archive-changelog.test.mjs", "role": "suite" },
22
24
  { "path": "archives/archive-issues.test.mjs", "role": "suite" },
23
25
  { "path": "archives/archive-decisions.test.mjs", "role": "suite" },
24
26
  { "path": "archives/archive-caps.test.mjs", "role": "suite" },
25
27
  { "path": "archives/archive-conservation.test.mjs", "role": "suite" },
28
+ { "path": "archives/rotation-faults.test.mjs", "role": "suite" },
26
29
  { "path": "archives/archiver-structure.test.mjs", "role": "suite" },
27
30
  { "path": "git-hooks/install-git-hooks.mjs", "role": "deployed", "seed": false },
28
31
  { "path": "git-hooks/install-git-hooks.test.mjs", "role": "suite" },
@@ -34,9 +37,11 @@
34
37
  { "path": "gates/kit-command-gates.test.mjs", "role": "suite" },
35
38
  { "path": "shared/markdown-blocks.mjs", "role": "deployed", "seed": true },
36
39
  { "path": "shared/project-root.mjs", "role": "deployed", "seed": true },
40
+ { "path": "shared/verdict-block.mjs", "role": "deployed", "seed": true },
37
41
  { "path": "shared/index.mjs", "role": "deployed", "seed": true },
38
42
  { "path": "shared/markdown-blocks.test.mjs", "role": "suite" },
39
43
  { "path": "shared/project-root.test.mjs", "role": "suite" },
44
+ { "path": "shared/verdict-block.test.mjs", "role": "suite" },
40
45
  { "path": "test-reporter/reporter.mjs", "role": "deployed", "seed": false },
41
46
  { "path": "test-reporter/reporter.test.mjs", "role": "suite" },
42
47
  { "path": "test-support/_expect-shim.mjs", "role": "support" },
@@ -1,3 +1,4 @@
1
- // The shared module's one door (spec script-family): the block model and the project-root finder.
1
+ // The shared module's one door (spec script-family).
2
2
  export { tokenizeMarkdown, findParagraphBreak, fail } from './markdown-blocks.mjs';
3
3
  export { findProjectRoot } from './project-root.mjs';
4
+ export { composeRedBlock, composeUsageRefusal, guardChecker } from './verdict-block.mjs';
@@ -20,7 +20,8 @@
20
20
  // Line content is returned BYTE-EXACT. Normalisation applies only to the view used for matching, so
21
21
  // re-emitting a block reproduces the file. Dependency-free, Node >= 22. No side effects on import.
22
22
 
23
- export const fail = (exitCode, message) => Object.assign(new Error(message), { exitCode });
23
+ export const fail = (exitCode, message, place) =>
24
+ Object.assign(new Error(message), { exitCode }, place === undefined ? {} : { place });
24
25
 
25
26
  const FRONTMATTER_RE = /^(---\r?\n[\s\S]*?\r?\n---\r?\n)/;
26
27
  // Up to three leading spaces, then a run of at least three backticks or tildes (CommonMark).
@@ -83,6 +84,7 @@ export const tokenizeMarkdown = (text, label = 'document') => {
83
84
  'so it is either frontmatter holding a heading or fence, or a thematic break whose closing `---` ' +
84
85
  'belongs to the body — and the two are indistinguishable here. Separate them: keep frontmatter ' +
85
86
  'free of `#` and fence lines, or put a blank line and prose before the first `---`.',
87
+ `${label}:${suspectAt + 1}`,
86
88
  );
87
89
  }
88
90
  }
@@ -125,6 +127,7 @@ export const tokenizeMarkdown = (text, label = 'document') => {
125
127
  `${label}:${frontLines + open.index + 1}: "${lines[open.index]}" opens a code fence that is ` +
126
128
  'never closed, so every heading after it is invisible and its text is silently absorbed. ' +
127
129
  `Close it with a bare \`${open.char.repeat(open.length)}\`, then re-run.`,
130
+ `${label}:${frontLines + open.index + 1}`,
128
131
  );
129
132
  }
130
133
 
@@ -0,0 +1,123 @@
1
+ // verdict-block: the red block composer (spec verdict-block).
2
+ const LINE_BREAK = /[\r\n]/;
3
+ const LINE_SEPARATOR = /\r\n|[\r\n]/;
4
+ const KEBAB_WORD = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
5
+ const LINE_NUMBER = /^[1-9][0-9]*$/;
6
+ const FINDING_SEPARATOR = ': ';
7
+ const DETAIL_PREFIX = ' ';
8
+ const VERDICT_WORD = 'FAIL';
9
+ const REMEDY_WORD = 'REMEDY';
10
+ const NO_MESSAGE = 'no message';
11
+ const MIN_EXIT_CODE = 1;
12
+ const MAX_EXIT_CODE = 255;
13
+ const NOT_FOUND = -1;
14
+
15
+ const refuseField = (field) => { throw new TypeError(`Invalid ${field}`); };
16
+
17
+ const validateName = (name) => {
18
+ if (typeof name !== 'string' || KEBAB_WORD.exec(name)?.[0] !== name) refuseField('name');
19
+ };
20
+
21
+ const validateLine = (line, field, allowEmpty = false, allowIndent = false) => {
22
+ if (typeof line !== 'string' || LINE_BREAK.test(line)
23
+ || (!allowEmpty && !line.length) || (!allowIndent && line.startsWith(' '))) refuseField(field);
24
+ return line;
25
+ };
26
+
27
+ const validateList = (list, field) => {
28
+ if (!Array.isArray(list)) refuseField(field);
29
+ return Array.from(list);
30
+ };
31
+
32
+ const formatNamedLine = (name, word, text) => `${name}: ${word} — ${text}`;
33
+
34
+ const judgeNamedLine = (line, name, word) => {
35
+ const prefix = formatNamedLine(name, word, '');
36
+ return line.startsWith(prefix) && line.length > prefix.length && line[prefix.length] !== ' ';
37
+ };
38
+
39
+ const validatePlace = (place) => {
40
+ validateLine(place, 'place');
41
+ const colonIndex = place.lastIndexOf(':');
42
+ const path = colonIndex === NOT_FOUND ? place : place.slice(0, colonIndex);
43
+ const lineNumber = place.slice(colonIndex + 1);
44
+ if (!path.length || path.includes('\\') || path.startsWith('./') || path.split('/').includes('..')
45
+ || (colonIndex !== NOT_FOUND && LINE_NUMBER.exec(lineNumber)?.[0] !== lineNumber)) refuseField('place');
46
+ };
47
+
48
+ const composeFinding = (finding, name) => {
49
+ if (finding === null || typeof finding !== 'object') refuseField('findings');
50
+ validatePlace(finding.place);
51
+ validateLine(finding.text, 'text');
52
+ const line = `${finding.place}${FINDING_SEPARATOR}${finding.text}`;
53
+ if ([VERDICT_WORD, REMEDY_WORD].some((word) => judgeNamedLine(line, name, word))) refuseField('findings');
54
+ const detail = validateList(finding.detail === undefined ? [] : finding.detail, 'detail');
55
+ return [line, ...detail.map((text) => `${DETAIL_PREFIX}${validateLine(text, 'detail', false, true)}`)];
56
+ };
57
+
58
+ const validateLateLine = (line, places, field) => {
59
+ if (places.some((place) => line.startsWith(`${place}${FINDING_SEPARATOR}`))) refuseField(field);
60
+ return line;
61
+ };
62
+
63
+ export const composeRedBlock = ({ name, failed, findings = [], remedies, after = [] }) => {
64
+ validateName(name);
65
+ validateLine(failed, 'failed');
66
+ const findingList = validateList(findings, 'findings');
67
+ const findingLines = findingList.flatMap((finding) => composeFinding(finding, name));
68
+ const places = findingList.map((finding) => finding.place);
69
+ const remedyList = validateList(remedies, 'remedies');
70
+ if (!remedyList.length) refuseField('remedies');
71
+ const remedyLines = remedyList.map((remedy, index) => {
72
+ const line = formatNamedLine(name, REMEDY_WORD, validateLine(remedy, 'remedies'));
73
+ return index === 0 ? line : validateLateLine(line, places, 'remedies');
74
+ });
75
+ const afterLines = validateList(after, 'after').map((line) =>
76
+ validateLateLine(validateLine(line, 'after', true, true), places, 'after'));
77
+ return Object.freeze([formatNamedLine(name, VERDICT_WORD, failed), ...findingLines, ...remedyLines, ...afterLines]);
78
+ };
79
+
80
+ export const composeUsageRefusal = ({ name, failed, usage }) => {
81
+ validateName(name);
82
+ validateLine(failed, 'failed');
83
+ if (typeof usage !== 'string' || !usage.length) refuseField('usage');
84
+ return Object.freeze([formatNamedLine(name, VERDICT_WORD, failed), ...usage.split(LINE_SEPARATOR)]);
85
+ };
86
+
87
+ const readFirstLine = (value) => String(value).split(LINE_SEPARATOR)[0];
88
+
89
+ const readErrorLine = (error) => {
90
+ try {
91
+ return (error instanceof Error
92
+ ? readFirstLine(error.message) || readFirstLine(error.name)
93
+ : readFirstLine(error)) || NO_MESSAGE;
94
+ } catch {
95
+ return NO_MESSAGE;
96
+ }
97
+ };
98
+
99
+ const composeErrorAnswer = ({ name, exitCode, remedy }, error) => {
100
+ const stack = error instanceof Error && typeof error.stack === 'string' && error.stack.length
101
+ ? error.stack.split(LINE_SEPARATOR) : [];
102
+ return {
103
+ exitCode,
104
+ lines: Object.freeze([
105
+ formatNamedLine(name, VERDICT_WORD, `unexpected error: ${readErrorLine(error)}`),
106
+ formatNamedLine(name, REMEDY_WORD, remedy),
107
+ ...stack,
108
+ ]),
109
+ };
110
+ };
111
+
112
+ export const guardChecker = ({ name, exitCode, remedy }, run) => {
113
+ validateName(name);
114
+ validateLine(remedy, 'remedy');
115
+ if (!Number.isInteger(exitCode) || exitCode < MIN_EXIT_CODE || exitCode > MAX_EXIT_CODE) refuseField('exitCode');
116
+ const answerError = (error) => composeErrorAnswer({ name, exitCode, remedy }, error);
117
+ try {
118
+ const answer = run();
119
+ return answer instanceof Promise ? answer.catch(answerError) : answer;
120
+ } catch (error) {
121
+ return answerError(error);
122
+ }
123
+ };
@@ -88,6 +88,7 @@ export const SCRIPT_PRIORS = Object.freeze([
88
88
  prior('migrate-gates.mjs', '8.1.5', '9.0.0', 'd9c3f9da27397dd94ad866c3cbac72e529ad2e6311ffa15de7478a960800cdfa'),
89
89
  prior('migrate-gates.test.mjs', '8.1.5', '9.0.0', '8f99a2f65f1f3db0eb3464a0382c208ca5076388b6df0596cf099d53ab2a1f86'),
90
90
  prior('spec-schema.test.mjs', '8.7.0', '9.0.0', '6a602a93e9f9f21f0bc10c50e356de693936d3e204987efbab1a1d7674030498'),
91
+ prior('markdown-blocks.mjs', '4.0.0', '9.0.0', '5a9fb45d4248c53dee9694b2d95c1cf98fe08a55c41429cf72826aa218f0ad2d'),
91
92
  ]);
92
93
 
93
94
  export const digestOf = (bytes) => createHash('sha256').update(bytes).digest('hex');