pi-spine 1.2.0 → 1.3.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.
Files changed (60) hide show
  1. package/README.md +4 -4
  2. package/bin/spine-cli/verify.mjs +3 -0
  3. package/bin/spine-plan.mjs +49 -1
  4. package/bin/spine-worker-runner.mjs +136 -4
  5. package/package.json +1 -1
  6. package/skills/create-spine-tasks/SKILL.md +7 -2
  7. package/skills/create-spine-tasks/references/contract-template.md +95 -3
  8. package/src/batch/attached-runner.mjs +81 -5
  9. package/src/batch/contract-stub-delivery.mjs +110 -0
  10. package/src/batch/contract-task-start.mjs +204 -0
  11. package/src/batch/contract-verify.mjs +55 -8
  12. package/src/batch/detached-start.mjs +72 -2
  13. package/src/batch/diagnosis-launch-failure.mjs +114 -0
  14. package/src/batch/diagnosis-primary-failure.mjs +89 -0
  15. package/src/batch/diagnosis-tail-state.mjs +57 -0
  16. package/src/batch/diagnosis.mjs +22 -113
  17. package/src/batch/engine-lanes/commit.mjs +145 -0
  18. package/src/batch/engine-lanes/review.mjs +67 -87
  19. package/src/batch/engine-lanes.mjs +21 -79
  20. package/src/batch/engine.mjs +46 -0
  21. package/src/batch/heartbeat.mjs +2 -2
  22. package/src/batch/integrate-assert.mjs +69 -0
  23. package/src/batch/integrate-worktree.mjs +354 -0
  24. package/src/batch/integrate.mjs +195 -102
  25. package/src/batch/journal-rebuild.mjs +48 -2
  26. package/src/batch/journal.mjs +63 -0
  27. package/src/batch/lane-dirty-check.mjs +437 -0
  28. package/src/batch/limbo-detect.mjs +34 -0
  29. package/src/batch/macro-phase.mjs +76 -0
  30. package/src/batch/metrics.mjs +2 -0
  31. package/src/batch/pause.mjs +18 -7
  32. package/src/batch/post-merge-limbo.mjs +3 -28
  33. package/src/batch/reconcile.mjs +79 -9
  34. package/src/batch/resume-common.mjs +27 -0
  35. package/src/batch/resume-multi-lanes.mjs +11 -0
  36. package/src/batch/resume-multi.mjs +2 -0
  37. package/src/batch/resume.mjs +8 -1
  38. package/src/batch/retry.mjs +41 -10
  39. package/src/batch/rules-manifest-drift.mjs +43 -2
  40. package/src/batch/sequence-state.mjs +290 -0
  41. package/src/batch/sequence.mjs +113 -51
  42. package/src/batch/state.mjs +16 -0
  43. package/src/batch/worker-host.mjs +1 -0
  44. package/src/cli/sequence.mjs +14 -1
  45. package/src/cli/settings-set.mjs +33 -3
  46. package/src/config/model-id.mjs +103 -0
  47. package/src/config/spine-init-constants.mjs +1 -0
  48. package/src/config/spine-preflight-lib.mjs +23 -1
  49. package/src/dashboard/public/dashboard.js +14 -3
  50. package/src/dashboard/running-tail-state.mjs +31 -0
  51. package/src/dashboard/server.mjs +4 -0
  52. package/src/dashboard/snapshot.mjs +260 -28
  53. package/src/dashboard/view.mjs +112 -2
  54. package/src/doctor/agent-models.mjs +53 -0
  55. package/src/doctor/batch-size-guidance.mjs +30 -2
  56. package/src/doctor/pi-extension-conflict.mjs +169 -0
  57. package/src/doctor/run-doctor-checks.mjs +6 -0
  58. package/src/planner/scope.mjs +5 -1
  59. package/src/tasks/packet/parse-prompt.mjs +31 -1
  60. package/src/tasks/packet/validate-contract.mjs +108 -0
@@ -5,8 +5,13 @@
5
5
  import { execFileSync } from "node:child_process";
6
6
  import { gitExec } from "./git-exec.mjs";
7
7
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
8
- import { tryAutoResolveRulesManifestMergeConflict } from "./engine-lanes.mjs";
9
- import { resolveRulesManifestIntegrateDrift } from "./rules-manifest-drift.mjs";
8
+ import { mergeOrchIntoBaseIsolated, isBranchCheckedOutInWorktree, syncPlumbingMergePathsToWorktree } from "./integrate-worktree.mjs";
9
+ import {
10
+ isFastForwardCapableIntegrate,
11
+ resolveRulesManifestIntegrateDrift,
12
+ } from "./rules-manifest-drift.mjs";
13
+ import { assertOrchIntegratable } from "./integrate-assert.mjs";
14
+ export { assertOrchIntegratable } from "./integrate-assert.mjs";
10
15
  import { checkIntegrateGate } from "./gate.mjs";
11
16
  import { appendJournalEvent } from "./journal.mjs";
12
17
  import { countCommitsAhead } from "./lane-commit.mjs";
@@ -21,69 +26,113 @@ function git(projectRoot, args) {
21
26
  }
22
27
 
23
28
  /**
24
- * Validates orch branch state before `spine batch complete` (FR-BATCH-16).
25
- *
26
- * @param {string} projectRoot
27
- * @param {object} ctx
28
- * @param {string} ctx.baseBranch
29
- * @param {string|null} ctx.orchBranch
30
- * @param {boolean} ctx.mergeResultsEmpty
31
- * @param {boolean} ctx.orchMergedToBase
29
+ * @param {string} output
32
30
  */
33
- export function assertOrchIntegratable(projectRoot, ctx) {
34
- const { baseBranch, orchBranch, mergeResultsEmpty, orchMergedToBase } = ctx;
35
-
36
- if (orchMergedToBase) {
37
- return { ok: true, reason: "orch_merged_to_base" };
38
- }
39
-
40
- if (mergeResultsEmpty) {
41
- return { ok: true, reason: "no_merge_claimed" };
42
- }
31
+ function mergeTreeOutputHasConflict(output) {
32
+ return /CONFLICT/i.test(output);
33
+ }
43
34
 
44
- if (!orchBranch) {
45
- return {
46
- ok: false,
47
- failureClass: "EmptyMerge",
48
- error: "Batch mergeResults claim success but no orch branch is recorded",
49
- suggestedCommand: "spine status --diagnose",
50
- };
51
- }
35
+ /**
36
+ * Ref-only merge when base is not checked out in projectRoot (avoids worktree git merge).
37
+ *
38
+ * @param {object} params
39
+ * @param {string} params.projectRoot
40
+ * @param {string} params.baseBranch
41
+ * @param {string} params.orchBranch
42
+ * @param {string} params.mergeMessage
43
+ */
44
+ function mergeOrchIntoBaseViaRefs({ projectRoot, baseBranch, orchBranch, mergeMessage }) {
45
+ const baseSha = git(projectRoot, ["rev-parse", baseBranch]);
46
+ const orchSha = git(projectRoot, ["rev-parse", orchBranch]);
52
47
 
53
- let commitsAhead = 0;
48
+ let mergeTreeOutput = "";
49
+ let treeSha = "";
54
50
  try {
55
- commitsAhead = countCommitsAhead(projectRoot, baseBranch, orchBranch);
51
+ mergeTreeOutput = execFileSync(
52
+ "git",
53
+ ["merge-tree", "--write-tree", baseBranch, orchBranch],
54
+ {
55
+ cwd: projectRoot,
56
+ encoding: "utf-8",
57
+ stdio: ["ignore", "pipe", "pipe"],
58
+ env: { ...process.env },
59
+ },
60
+ ).trim();
61
+ treeSha = mergeTreeOutput.split("\n").pop()?.trim() ?? "";
56
62
  } catch (err) {
63
+ const stdout = err && typeof err === "object" && "stdout" in err ? String(err.stdout ?? "") : "";
64
+ const stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr ?? "") : "";
65
+ mergeTreeOutput = `${stdout}\n${stderr}`.trim();
66
+ if (mergeTreeOutputHasConflict(mergeTreeOutput)) {
67
+ return {
68
+ ok: false,
69
+ failureClass: "MergeConflict",
70
+ error: mergeTreeOutput.split("\n").slice(-3).join(" ") || "merge conflict",
71
+ };
72
+ }
57
73
  const message = err instanceof Error ? err.message : String(err);
58
74
  return {
59
75
  ok: false,
60
- failureClass: "EmptyMerge",
61
- error: `Cannot compare ${orchBranch} to ${baseBranch}: ${message}`,
62
- suggestedCommand: "spine status --diagnose",
76
+ failureClass: "IntegrateFailed",
77
+ error: message,
63
78
  };
64
79
  }
65
80
 
66
- if (commitsAhead === 0) {
81
+ if (!treeSha || mergeTreeOutputHasConflict(mergeTreeOutput)) {
67
82
  return {
68
83
  ok: false,
69
- failureClass: "EmptyMerge",
70
- error:
71
- `Orch branch ${orchBranch} has no commits ahead of ${baseBranch} but mergeResults claim success. ` +
72
- `Re-run the batch or land lane work on the orch branch before completing.`,
73
- suggestedCommand: "spine status --diagnose",
84
+ failureClass: "MergeConflict",
85
+ error: mergeTreeOutput || `merge conflict integrating ${orchBranch} into ${baseBranch}`,
74
86
  };
75
87
  }
76
88
 
89
+ const mergeCommit = git(
90
+ projectRoot,
91
+ ["commit-tree", treeSha, "-p", baseSha, "-p", orchSha, "-m", mergeMessage],
92
+ );
93
+ git(projectRoot, ["update-ref", `refs/heads/${baseBranch}`, mergeCommit]);
94
+
95
+ return { ok: true, mergeCommit, mode: "plumbing" };
96
+ }
97
+
98
+ /**
99
+ * Fast-forward base to orch tip without checking out base in projectRoot.
100
+ *
101
+ * @param {object} params
102
+ * @param {string} params.projectRoot
103
+ * @param {string} params.baseBranch
104
+ * @param {string} params.orchBranch
105
+ */
106
+ function fastForwardOrchIntoBase({ projectRoot, baseBranch, orchBranch }) {
107
+ const baseShaBefore = git(projectRoot, ["rev-parse", baseBranch]);
108
+ const orchSha = git(projectRoot, ["rev-parse", orchBranch]);
109
+ git(projectRoot, ["update-ref", `refs/heads/${baseBranch}`, orchSha]);
77
110
  return {
78
- ok: false,
79
- failureClass: "NeedsIntegrate",
80
- error:
81
- `Orch branch ${orchBranch} is ${commitsAhead} commit(s) ahead of ${baseBranch} — run integrate before completing the batch record.`,
82
- suggestedCommand: "spine integrate",
83
- commitsAhead,
111
+ ok: true,
112
+ mergeCommit: orchSha,
113
+ mode: "fast-forward",
114
+ baseShaBefore,
84
115
  };
85
116
  }
86
117
 
118
+ /**
119
+ * @param {object} params
120
+ * @param {string} params.projectRoot
121
+ * @param {string} params.baseBranch
122
+ * @param {string} params.orchBranch
123
+ * @param {string} params.batchId
124
+ */
125
+ function runIntegrateMerge({ projectRoot, baseBranch, orchBranch, batchId }) {
126
+ const mergeMessage = `integrate ${orchBranch} into ${baseBranch}`;
127
+ if (isFastForwardCapableIntegrate({ projectRoot, baseBranch, orchBranch })) {
128
+ return fastForwardOrchIntoBase({ projectRoot, baseBranch, orchBranch });
129
+ }
130
+ if (isBranchCheckedOutInWorktree(projectRoot, baseBranch)) {
131
+ return mergeOrchIntoBaseIsolated({ projectRoot, baseBranch, orchBranch, batchId });
132
+ }
133
+ return mergeOrchIntoBaseViaRefs({ projectRoot, baseBranch, orchBranch, mergeMessage });
134
+ }
135
+
87
136
  /**
88
137
  * @param {object} ctx
89
138
  * @param {string} ctx.projectRoot
@@ -274,7 +323,11 @@ export function integrateOrchToBase(ctx) {
274
323
  ? `Would merge ${orchBranch} → ${baseBranch} after gate approval (${commitsAhead ?? "?"} commit(s))`
275
324
  : `Would merge ${orchBranch} → ${baseBranch} (${commitsAhead ?? "?"} commit(s))`,
276
325
  suggestedCommand: gatePending ? "spine gate approve" : "spine integrate",
277
- mergePlan: `git checkout ${baseBranch} && git merge --no-ff ${orchBranch}`,
326
+ mergePlan: isFastForwardCapableIntegrate({ projectRoot, baseBranch, orchBranch })
327
+ ? `isolated fast-forward ${orchBranch} → ${baseBranch} (ref update, no checkout in projectRoot)`
328
+ : isBranchCheckedOutInWorktree(projectRoot, baseBranch)
329
+ ? `isolated plumbing merge ${orchBranch} → ${baseBranch} (no checkout in projectRoot)`
330
+ : `isolated ref merge ${orchBranch} → ${baseBranch} (merge-tree, no checkout in projectRoot)`,
278
331
  };
279
332
  }
280
333
 
@@ -287,8 +340,14 @@ export function integrateOrchToBase(ctx) {
287
340
  });
288
341
 
289
342
  const previous = git(projectRoot, ["rev-parse", "--abbrev-ref", "HEAD"]);
343
+ const baseCheckedOutAtStart = isBranchCheckedOutInWorktree(projectRoot, baseBranch);
290
344
  try {
291
- const drift = resolveRulesManifestIntegrateDrift({ projectRoot, baseBranch, orchBranch });
345
+ const drift = resolveRulesManifestIntegrateDrift({
346
+ projectRoot,
347
+ baseBranch,
348
+ orchBranch,
349
+ isolatedMerge: true,
350
+ });
292
351
  if (!drift.ok) {
293
352
  return {
294
353
  ok: false,
@@ -300,61 +359,104 @@ export function integrateOrchToBase(ctx) {
300
359
  batchId,
301
360
  };
302
361
  }
362
+ if (drift.resolved) {
363
+ appendJournalEvent(projectRoot, batchId, "integrate.drift_resolved", {
364
+ baseBranch,
365
+ orchBranch,
366
+ action: drift.action ?? "restored_head",
367
+ });
368
+ }
303
369
 
304
- git(projectRoot, ["checkout", baseBranch]);
305
- let mergeInProgress = false;
306
- try {
307
- git(projectRoot, [
308
- "merge",
309
- "--no-ff",
370
+ const mergeResult = runIntegrateMerge({ projectRoot, baseBranch, orchBranch, batchId });
371
+
372
+ if (!mergeResult.ok) {
373
+ const message = mergeResult.error ?? "merge conflict";
374
+ const conflict = mergeResult.failureClass === "MergeConflict";
375
+ appendJournalEvent(projectRoot, batchId, "integrate.failed", {
376
+ baseBranch,
310
377
  orchBranch,
311
- "-m",
312
- `integrate ${orchBranch} into ${baseBranch}`,
313
- ]);
314
- } catch {
315
- mergeInProgress = true;
316
- const autoResolved = tryAutoResolveRulesManifestMergeConflict(projectRoot);
317
- if (!autoResolved.ok) {
318
- try {
319
- execFileSync("git", ["merge", "--abort"], {
320
- cwd: projectRoot,
321
- stdio: ["ignore", "pipe", "pipe"],
322
- });
323
- } catch {
324
- // best-effort abort
325
- }
326
- const message = autoResolved.error ?? "merge conflict";
327
- appendJournalEvent(projectRoot, batchId, "integrate.failed", {
328
- baseBranch,
329
- orchBranch,
330
- error: message.slice(0, 500),
331
- conflict: true,
332
- });
333
- try {
334
- git(projectRoot, ["checkout", previous || baseBranch]);
335
- } catch {
336
- // leave operator on base for manual recovery
337
- }
338
- return {
339
- ok: false,
340
- exitCode: 1,
341
- error: message,
342
- failureClass: autoResolved.failureClass ?? "MergeConflict",
343
- headline: `Merge conflict integrating ${orchBranch} into ${baseBranch} — resolve manually`,
344
- suggestedCommand: "spine status --diagnose",
345
- batchId,
346
- alternatives: ["/spine-gate"],
347
- };
378
+ error: message.slice(0, 500),
379
+ conflict,
380
+ });
381
+ try {
382
+ git(projectRoot, ["checkout", previous || baseBranch]);
383
+ } catch {
384
+ // leave operator on current branch for manual recovery
385
+ }
386
+ return {
387
+ ok: false,
388
+ exitCode: 1,
389
+ error: message,
390
+ failureClass: mergeResult.failureClass ?? (conflict ? "MergeConflict" : "IntegrateFailed"),
391
+ headline: conflict
392
+ ? `Merge conflict integrating ${orchBranch} into ${baseBranch} — resolve manually`
393
+ : `Integrate failed: ${message}`,
394
+ suggestedCommand: "spine status --diagnose",
395
+ batchId,
396
+ alternatives: ["/spine-gate"],
397
+ };
398
+ }
399
+
400
+ const mergeCommit = mergeResult.mergeCommit;
401
+
402
+ /** @type {{ ok: boolean, timedOut?: boolean, error?: string } | null} */
403
+ let syncResult = null;
404
+ if (mergeResult.mode === "fast-forward") {
405
+ syncResult = syncPlumbingMergePathsToWorktree(
406
+ projectRoot,
407
+ mergeResult.baseShaBefore,
408
+ mergeCommit,
409
+ );
410
+ } else if (mergeResult.mode === "plumbing") {
411
+ const baseSha = git(projectRoot, ["rev-parse", `${mergeCommit}^1`]);
412
+ syncResult = syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeCommit);
413
+ } else if (!baseCheckedOutAtStart) {
414
+ try {
415
+ git(projectRoot, ["checkout", baseBranch]);
416
+ git(projectRoot, ["reset", "--hard", "HEAD"]);
417
+ } catch {
418
+ // Dirty tree may block checkout after isolated land — operator syncs manually.
348
419
  }
349
- git(projectRoot, ["commit", "--no-edit"]);
350
420
  }
351
- const mergeCommit = git(projectRoot, ["rev-parse", "HEAD"]);
421
+
422
+ if (syncResult && !syncResult.ok) {
423
+ appendJournalEvent(projectRoot, batchId, "integrate.failed", {
424
+ baseBranch,
425
+ orchBranch,
426
+ timeout: Boolean(syncResult.timedOut),
427
+ error: (syncResult.error ?? "sync failed").slice(0, 500),
428
+ mergeCommitLanded: true,
429
+ mergeCommit,
430
+ });
431
+
432
+ try {
433
+ git(projectRoot, ["checkout", previous || baseBranch]);
434
+ } catch {
435
+ // Leave operator on current branch for manual recovery.
436
+ }
437
+
438
+ return {
439
+ ok: false,
440
+ exitCode: 1,
441
+ error: syncResult.error ?? "post-merge sync failed",
442
+ failureClass: syncResult.timedOut ? "IntegrateTimeout" : "IntegrateFailed",
443
+ headline: syncResult.timedOut
444
+ ? `Integrate sync timed out after merge landed — ${orchBranch} into ${baseBranch}`
445
+ : `Integrate post-merge sync failed — ${syncResult.error}`,
446
+ suggestedCommand: "spine status --diagnose",
447
+ batchId,
448
+ mergeCommitLanded: true,
449
+ alternatives: ["spine integrate"],
450
+ };
451
+ }
352
452
 
353
453
  appendJournalEvent(projectRoot, batchId, "integrate.completed", {
354
454
  baseBranch,
355
455
  orchBranch,
356
456
  mergeCommit,
357
457
  commitsAhead,
458
+ isolated: true,
459
+ baseCheckedOutAtStart,
358
460
  });
359
461
 
360
462
  return {
@@ -381,19 +483,10 @@ export function integrateOrchToBase(ctx) {
381
483
  conflict,
382
484
  });
383
485
 
384
- try {
385
- execFileSync("git", ["merge", "--abort"], {
386
- cwd: projectRoot,
387
- stdio: ["ignore", "pipe", "pipe"],
388
- });
389
- } catch {
390
- // best-effort abort
391
- }
392
-
393
486
  try {
394
487
  git(projectRoot, ["checkout", previous || baseBranch]);
395
488
  } catch {
396
- // leave operator on base for manual recovery
489
+ // leave operator on current branch for manual recovery
397
490
  }
398
491
 
399
492
  return {
@@ -351,6 +351,15 @@ export function rebuildBatchStateFromDisk(projectRoot, batchId, seedState) {
351
351
 
352
352
  /** @typedef {{ taskId: string, field: string, cached: unknown, rebuilt: unknown }} DriftEntry */
353
353
 
354
+ const NON_TERMINAL_CACHE_STATUSES = new Set(["pending", "running"]);
355
+ const JOURNAL_TERMINAL_LIFECYCLE = new Set([
356
+ "task.completed",
357
+ "task.skipped",
358
+ "task.skipped_done_on_disk",
359
+ "task.failed",
360
+ "task.prompt_parse_failed",
361
+ ]);
362
+
354
363
  function lastLifecycleEventForTask(events, taskId) {
355
364
  const taskEvents = events.filter(
356
365
  (event) => event?.taskId === taskId && TASK_LIFECYCLE_EVENT_TYPES.has(String(event?.type ?? "")),
@@ -358,19 +367,56 @@ function lastLifecycleEventForTask(events, taskId) {
358
367
  return taskEvents.length > 0 ? taskEvents[taskEvents.length - 1] : null;
359
368
  }
360
369
 
361
- export function detectBatchStateDrift(cachedState, rebuiltState, events = []) {
370
+ function hasJournalTerminalLifecycle(lastEvent) {
371
+ if (!lastEvent) return false;
372
+ return JOURNAL_TERMINAL_LIFECYCLE.has(String(lastEvent.type ?? ""));
373
+ }
374
+
375
+ /**
376
+ * @param {object|null|undefined} classified
377
+ */
378
+ function classifiedShowsDoneInLaneDrift(classified) {
379
+ if (!classified || typeof classified !== "object") return false;
380
+ if (classified.doneInLane === true) return true;
381
+ return (
382
+ classified.classification === "terminal-success" &&
383
+ !["succeeded", "skipped"].includes(String(classified.status ?? "").toLowerCase())
384
+ );
385
+ }
386
+
387
+ export function detectBatchStateDrift(cachedState, rebuiltState, events = [], classifiedTasks = null) {
362
388
  /** @type {DriftEntry[]} */
363
389
  const entries = [];
364
390
  const rebuiltById = new Map((rebuiltState?.tasks ?? []).map((task) => [String(task?.taskId), task]));
391
+ const classifiedById = Array.isArray(classifiedTasks)
392
+ ? new Map(classifiedTasks.map((task) => [String(task?.taskId), task]))
393
+ : null;
365
394
 
366
395
  for (const cached of cachedState?.tasks ?? []) {
367
396
  if (!cached?.taskId) continue;
368
397
  const taskId = String(cached.taskId);
369
398
  const rebuilt = rebuiltById.get(taskId);
370
399
  if (!rebuilt) continue;
400
+ const classified = classifiedById?.get(taskId) ?? null;
401
+ const cachedStatus = String(cached.status ?? "").toLowerCase();
371
402
  const lastEvent = lastLifecycleEventForTask(events, taskId);
403
+ const lastType = lastEvent ? String(lastEvent.type ?? "") : "";
404
+
405
+ if (
406
+ NON_TERMINAL_CACHE_STATUSES.has(cachedStatus) &&
407
+ classifiedShowsDoneInLaneDrift(classified) &&
408
+ !hasJournalTerminalLifecycle(lastEvent)
409
+ ) {
410
+ entries.push({
411
+ taskId,
412
+ field: "doneInLane",
413
+ cached: cached.status,
414
+ rebuilt: classified?.classification ?? "terminal-success",
415
+ });
416
+ continue;
417
+ }
418
+
372
419
  if (!lastEvent) continue;
373
- const lastType = String(lastEvent.type ?? "");
374
420
 
375
421
  if (lastType === "task.completed" && cached.status !== "succeeded") {
376
422
  entries.push({ taskId, field: "status", cached: cached.status, rebuilt: rebuilt.status });
@@ -242,6 +242,69 @@ export function readJournalEvents(projectRoot, batchId) {
242
242
  .map((line) => normalizeJournalEvent(JSON.parse(line)));
243
243
  }
244
244
 
245
+ /**
246
+ * Module-level mtime-keyed journal read cache.
247
+ * Shared across collectProgressSignals, attached milestone reporter, and dashboard snapshot.
248
+ * @type {{ filePath: string | null, mtimeMs: number | null, events: object[] }}
249
+ */
250
+ const _journalCache = { filePath: null, mtimeMs: null, events: [] };
251
+
252
+ /**
253
+ * Read journal events with mtime-based cache invalidation.
254
+ * Returns cached events when the journal file mtime has not changed, avoiding
255
+ * redundant disk reads during idle orchestrator monitoring loops.
256
+ *
257
+ * @param {string} projectRoot
258
+ * @param {string} batchId
259
+ * @returns {object[]}
260
+ */
261
+ export function readJournalEventsCached(projectRoot, batchId) {
262
+ const filePath = journalPath(projectRoot, batchId);
263
+ if (!fs.existsSync(filePath)) {
264
+ _journalCache.filePath = null;
265
+ _journalCache.mtimeMs = null;
266
+ _journalCache.events = [];
267
+ return [];
268
+ }
269
+
270
+ const stat = fs.statSync(filePath);
271
+ if (filePath === _journalCache.filePath && stat.mtimeMs === _journalCache.mtimeMs) {
272
+ return _journalCache.events;
273
+ }
274
+
275
+ const events = fs
276
+ .readFileSync(filePath, "utf-8")
277
+ .split("\n")
278
+ .filter(Boolean)
279
+ .map((line) => normalizeJournalEvent(JSON.parse(line)));
280
+
281
+ _journalCache.filePath = filePath;
282
+ _journalCache.mtimeMs = stat.mtimeMs;
283
+ _journalCache.events = events;
284
+
285
+ return events;
286
+ }
287
+
288
+ /** Clear the journal read cache. Useful for test isolation. */
289
+ export function clearJournalCache() {
290
+ _journalCache.filePath = null;
291
+ _journalCache.mtimeMs = null;
292
+ _journalCache.events = [];
293
+ }
294
+
295
+ /**
296
+ * Invalidate the journal cache for a specific file path.
297
+ * Forces the next readJournalEventsCached call to re-read from disk.
298
+ *
299
+ * @param {string} [filePath] If provided, only invalidate when matching. Otherwise clears unconditionally.
300
+ */
301
+ export function invalidateJournalCache(filePath) {
302
+ if (filePath && _journalCache.filePath !== filePath) return;
303
+ _journalCache.filePath = null;
304
+ _journalCache.mtimeMs = null;
305
+ _journalCache.events = [];
306
+ }
307
+
245
308
  /**
246
309
  * @param {object[]} events
247
310
  * @param {number} [limit]