@sabaiway/agent-workflow-kit 23.4.1 → 23.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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