pi-spine 2.24.0 → 2.26.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 (53) hide show
  1. package/bin/spine-worker-runner.mjs +2 -1
  2. package/package.json +1 -1
  3. package/src/batch/abort.mjs +74 -38
  4. package/src/batch/attached-engine-handoff.mjs +2 -2
  5. package/src/batch/attached-runner-promote.mjs +15 -1
  6. package/src/batch/attached-runner-reconcile.mjs +1 -1
  7. package/src/batch/batch-meta-reconstruct.mjs +6 -1
  8. package/src/batch/batch-state-io.mjs +120 -45
  9. package/src/batch/batch-state-lock.mjs +173 -31
  10. package/src/batch/contract-exec.mjs +46 -45
  11. package/src/batch/contract-spawn.mjs +225 -0
  12. package/src/batch/contract-verify.mjs +2 -1
  13. package/src/batch/detached-wait.mjs +1 -1
  14. package/src/batch/engine-crash-guard.mjs +143 -0
  15. package/src/batch/engine-lanes/matrix-run.mjs +34 -8
  16. package/src/batch/engine-lanes/matrix.mjs +143 -8
  17. package/src/batch/engine-lanes/merge.mjs +135 -34
  18. package/src/batch/engine-lanes/review-final.mjs +1 -1
  19. package/src/batch/engine-lanes.mjs +11 -9
  20. package/src/batch/engine.mjs +10 -10
  21. package/src/batch/integrate-dirty-overlap.mjs +35 -0
  22. package/src/batch/integrate-worktree.mjs +106 -13
  23. package/src/batch/integrate.mjs +34 -93
  24. package/src/batch/journal-checksum.mjs +26 -0
  25. package/src/batch/journal.mjs +32 -13
  26. package/src/batch/lifecycle-archive.mjs +84 -3
  27. package/src/batch/lifecycle-cleanup.mjs +110 -0
  28. package/src/batch/lifecycle.mjs +100 -72
  29. package/src/batch/parent-session-monitor.mjs +77 -70
  30. package/src/batch/pause.mjs +92 -25
  31. package/src/batch/post-merge-limbo.mjs +35 -5
  32. package/src/batch/reconcile-batch.mjs +13 -1
  33. package/src/batch/resume-gate-reopen.mjs +24 -8
  34. package/src/batch/resume-multi.mjs +1 -1
  35. package/src/batch/resume.mjs +1 -1
  36. package/src/batch/salvage-batch-integrate.mjs +13 -17
  37. package/src/batch/sequence-run.mjs +26 -8
  38. package/src/batch/sequence-wait.mjs +87 -8
  39. package/src/batch/state-guards.mjs +39 -7
  40. package/src/batch/state-io.mjs +131 -17
  41. package/src/batch/state.mjs +23 -1
  42. package/src/batch/worker-heartbeat.mjs +29 -8
  43. package/src/batch/worker-host.mjs +61 -8
  44. package/src/batch/worker-output.mjs +9 -6
  45. package/src/batch/worker-prompt.mjs +4 -2
  46. package/src/batch/worker-spawn.mjs +99 -12
  47. package/src/config/defaults.mjs +15 -1
  48. package/src/config/preflight/discovery.mjs +20 -12
  49. package/src/config/preflight/git-batch.mjs +47 -0
  50. package/src/config/spine-config-schema.mjs +67 -1
  51. package/src/fs/atomic-write.mjs +37 -1
  52. package/src/planner/scope.mjs +3 -1
  53. package/src/tasks/packet/discover.mjs +59 -3
@@ -11,6 +11,7 @@ import { gitExec } from "./git-exec.mjs";
11
11
  import { resolveGitCommitEnv } from "./git-commit-env.mjs";
12
12
  import { tryAutoResolveRulesManifestMergeConflict } from "./engine-lanes/merge.mjs";
13
13
  import { appendJournalEvent } from "./journal.mjs";
14
+ import { listIntegrateDirtyPaths } from "./rules-manifest-drift.mjs";
14
15
 
15
16
  export const DEFAULT_SYNC_TIMEOUT_MS = 60_000;
16
17
 
@@ -115,13 +116,49 @@ function mergeTreeOutputHasConflict(output) {
115
116
  }
116
117
 
117
118
  /**
119
+ * Move a branch ref to newSha only if it still points at expectedOldSha (compare-and-swap).
120
+ * Prevents a concurrent commit on base from being silently orphaned mid-integrate (#298).
121
+ *
122
+ * @param {object} params
123
+ * @param {string} params.projectRoot
124
+ * @param {string} params.baseBranch
125
+ * @param {string} params.newSha
126
+ * @param {string} params.expectedOldSha
127
+ * @returns {{ ok: boolean, failureClass?: string, error?: string }}
128
+ */
129
+ export function casUpdateBaseRef({ projectRoot, baseBranch, newSha, expectedOldSha }) {
130
+ try {
131
+ gitExec(projectRoot, ["update-ref", `refs/heads/${baseBranch}`, newSha, expectedOldSha], {
132
+ projectRoot,
133
+ });
134
+ return { ok: true };
135
+ } catch {
136
+ let current = "unknown";
137
+ try {
138
+ current = gitExec(projectRoot, ["rev-parse", `refs/heads/${baseBranch}`], { projectRoot });
139
+ } catch {
140
+ // keep "unknown" — the branch may have been deleted mid-integrate
141
+ }
142
+ return {
143
+ ok: false,
144
+ failureClass: "BaseMoved",
145
+ error: `${baseBranch} moved during integrate (expected ${expectedOldSha}, found ${current}) — re-run spine integrate`,
146
+ };
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Plumbing merge of orch into base without touching any worktree.
152
+ * Shared implementation for integrate and salvage paths; merge-tree runs on captured SHAs
153
+ * and the base ref update is compare-and-swap so a mid-integrate base move fails loudly (#298).
154
+ *
118
155
  * @param {object} params
119
156
  * @param {string} params.projectRoot
120
157
  * @param {string} params.baseBranch
121
158
  * @param {string} params.orchBranch
122
159
  * @param {string} params.mergeMessage
123
160
  */
124
- function plumbingMergeOrchIntoBase({ projectRoot, baseBranch, orchBranch, mergeMessage }) {
161
+ export function plumbingMergeOrchIntoBase({ projectRoot, baseBranch, orchBranch, mergeMessage }) {
125
162
  const baseSha = git(projectRoot, ["rev-parse", baseBranch]);
126
163
  const orchSha = git(projectRoot, ["rev-parse", orchBranch]);
127
164
 
@@ -130,7 +167,7 @@ function plumbingMergeOrchIntoBase({ projectRoot, baseBranch, orchBranch, mergeM
130
167
  try {
131
168
  mergeTreeOutput = execFileSync(
132
169
  "git",
133
- ["merge-tree", "--write-tree", baseBranch, orchBranch],
170
+ ["merge-tree", "--write-tree", baseSha, orchSha],
134
171
  {
135
172
  cwd: projectRoot,
136
173
  encoding: "utf-8",
@@ -170,7 +207,10 @@ function plumbingMergeOrchIntoBase({ projectRoot, baseBranch, orchBranch, mergeM
170
207
  projectRoot,
171
208
  ["commit-tree", treeSha, "-p", baseSha, "-p", orchSha, "-m", mergeMessage],
172
209
  );
173
- git(projectRoot, ["update-ref", `refs/heads/${baseBranch}`, mergeCommit]);
210
+ const cas = casUpdateBaseRef({ projectRoot, baseBranch, newSha: mergeCommit, expectedOldSha: baseSha });
211
+ if (!cas.ok) {
212
+ return cas;
213
+ }
174
214
 
175
215
  return { ok: true, mergeCommit, mode: "plumbing" };
176
216
  }
@@ -242,16 +282,17 @@ function pathExistsInTree(cwd, treeRef, filePath, { timeoutMs } = {}) {
242
282
  }
243
283
 
244
284
  /**
245
- * Materialize paths introduced/changed by a plumbing merge without resetting human edits.
246
- * Returns a result object so callers can detect timeout and emit integrate.failed.
285
+ * Materialize paths changed by a plumbing merge; dirty paths (uncommitted local edits) are
286
+ * skipped and reported via skippedDirtyPaths (SP-784 / #298). Capture dirtyPaths BEFORE the
287
+ * merge moves the base ref: afterwards git status reports unmaterialized paths as deleted.
247
288
  *
248
289
  * @param {string} projectRoot
249
290
  * @param {string} baseSha
250
291
  * @param {string} mergeCommit
251
- * @param {{ timeoutMs?: number }} [options]
252
- * @returns {{ ok: boolean, timedOut?: boolean, error?: string, processedPaths?: number, totalPaths?: number }}
292
+ * @param {{ timeoutMs?: number, dirtyPaths?: string[] }} [options]
293
+ * @returns {{ ok: boolean, timedOut?: boolean, error?: string, processedPaths?: number, totalPaths?: number, skippedDirtyPaths?: string[] }}
253
294
  */
254
- export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeCommit, { timeoutMs = DEFAULT_SYNC_TIMEOUT_MS } = {}) {
295
+ export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeCommit, { timeoutMs = DEFAULT_SYNC_TIMEOUT_MS, dirtyPaths } = {}) {
255
296
  const envTimeoutMs = process.env.SPINE_SYNC_TIMEOUT_MS
256
297
  ? Number(process.env.SPINE_SYNC_TIMEOUT_MS)
257
298
  : null;
@@ -272,14 +313,20 @@ export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeComm
272
313
  }
273
314
 
274
315
  const paths = output.split("\n").map((line) => line.trim()).filter(Boolean);
316
+ const dirtyPathSet = new Set(dirtyPaths ?? listIntegrateDirtyPaths(projectRoot));
317
+ const skippedDirtyPaths = [];
275
318
  let processedCount = 0;
276
319
 
277
320
  for (const filePath of paths) {
278
- let existsInMerge = false;
321
+ // Dirty entry = local edit only when the file is in the worktree (modified/untracked) or
322
+ // tracked at baseSha (operator deleted); missing from both = merge output to restore (SP-784).
323
+ let existsInMerge = false, operatorTouched = false;
279
324
  try {
280
325
  existsInMerge = pathExistsInTree(projectRoot, mergeCommit, filePath, {
281
326
  timeoutMs: effectiveTimeout,
282
327
  });
328
+ if (dirtyPathSet.has(filePath)) operatorTouched = fs.existsSync(path.join(projectRoot, filePath)) ||
329
+ pathExistsInTree(projectRoot, baseSha, filePath, { timeoutMs: effectiveTimeout });
283
330
  } catch (err) {
284
331
  if (isTimeoutError(err)) {
285
332
  return {
@@ -300,6 +347,11 @@ export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeComm
300
347
  continue;
301
348
  }
302
349
 
350
+ if (dirtyPathSet.has(filePath) && operatorTouched) {
351
+ skippedDirtyPaths.push(filePath);
352
+ continue;
353
+ }
354
+
303
355
  try {
304
356
  gitWithTimeout(
305
357
  projectRoot,
@@ -330,7 +382,35 @@ export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeComm
330
382
  processedCount++;
331
383
  }
332
384
 
333
- return { ok: true, processedPaths: processedCount, totalPaths: paths.length };
385
+ return { ok: true, processedPaths: processedCount, totalPaths: paths.length, skippedDirtyPaths };
386
+ }
387
+
388
+ /**
389
+ * Post-merge path sync gated on baseBranch being checked out right now (SP-784 / #298);
390
+ * returns null (no sync) otherwise. Options forward to syncPlumbingMergePathsToWorktree.
391
+ * @param {string} projectRoot
392
+ * @param {string} baseBranch
393
+ */
394
+ export function syncMergePathsToCheckedOutBase(projectRoot, baseBranch, baseSha, mergeCommit, options) {
395
+ if (!isBranchCheckedOutInWorktree(projectRoot, baseBranch)) return null;
396
+ return syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeCommit, options);
397
+ }
398
+
399
+ /**
400
+ * Sync a landed merge into projectRoot when base is checked out. Pre-merge base: `baseShaBefore`
401
+ * (fast-forward) or the merge's first parent (plumbing); worktree merges imply no checkout (null).
402
+ * @param {{ mode?: string, mergeCommit: string, baseShaBefore?: string }} mergeResult
403
+ */
404
+ export function syncMergeResultToCheckedOutBase(projectRoot, baseBranch, mergeResult, options) {
405
+ const { mode, mergeCommit } = mergeResult;
406
+ if (mode === "fast-forward") {
407
+ return syncMergePathsToCheckedOutBase(projectRoot, baseBranch, mergeResult.baseShaBefore, mergeCommit, options);
408
+ }
409
+ if (mode === "plumbing") {
410
+ const baseSha = git(projectRoot, ["rev-parse", `${mergeCommit}^1`]);
411
+ return syncMergePathsToCheckedOutBase(projectRoot, baseBranch, baseSha, mergeCommit, options);
412
+ }
413
+ return null;
334
414
  }
335
415
 
336
416
  /**
@@ -342,6 +422,10 @@ export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeComm
342
422
  * @param {string} params.mergeMessage
343
423
  */
344
424
  function mergeInIntegrateWorktree({ projectRoot, worktreePath, baseBranch, orchBranch, mergeMessage }) {
425
+ // The worktree has baseBranch checked out, so the merge itself advances the shared ref.
426
+ // Capture the base tip before the merge and verify the merge commit's first parent matches
427
+ // so a base move between provisioning and merge fails loudly instead of being clobbered (#298).
428
+ const baseShaBefore = git(projectRoot, ["rev-parse", baseBranch]);
345
429
  try {
346
430
  git(worktreePath, ["merge", "--no-ff", orchBranch, "-m", mergeMessage]);
347
431
  } catch {
@@ -365,9 +449,18 @@ function mergeInIntegrateWorktree({ projectRoot, worktreePath, baseBranch, orchB
365
449
  }
366
450
 
367
451
  const mergeCommit = git(worktreePath, ["rev-parse", "HEAD"]);
368
- const baseSha = git(projectRoot, ["rev-parse", baseBranch]);
369
- if (mergeCommit !== baseSha) {
370
- git(projectRoot, ["update-ref", `refs/heads/${baseBranch}`, mergeCommit]);
452
+ if (mergeCommit === baseShaBefore) {
453
+ // Merge was a no-op (orch already contained in base) — HEAD did not move, so there is
454
+ // no new merge commit whose first parent could be verified.
455
+ return { ok: true, mergeCommit, mode: "worktree" };
456
+ }
457
+ const firstParent = git(projectRoot, ["rev-parse", `${mergeCommit}^1`]);
458
+ if (firstParent !== baseShaBefore) {
459
+ return {
460
+ ok: false,
461
+ failureClass: "BaseMoved",
462
+ error: `${baseBranch} moved during integrate (expected ${baseShaBefore}, found ${firstParent}) — re-run spine integrate`,
463
+ };
371
464
  }
372
465
 
373
466
  return { ok: true, mergeCommit, mode: "worktree" };
@@ -3,12 +3,19 @@
3
3
  * Orch → base integration (FR-INT-01–05, TP-016).
4
4
  */
5
5
 
6
- import { execFileSync } from "node:child_process";
7
6
  import { gitExec } from "./git-exec.mjs";
8
7
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
- import { mergeOrchIntoBaseIsolated, isBranchCheckedOutInWorktree, syncPlumbingMergePathsToWorktree } from "./integrate-worktree.mjs";
8
+ import {
9
+ mergeOrchIntoBaseIsolated,
10
+ plumbingMergeOrchIntoBase,
11
+ casUpdateBaseRef,
12
+ isBranchCheckedOutInWorktree,
13
+ syncMergeResultToCheckedOutBase,
14
+ } from "./integrate-worktree.mjs";
15
+ import { reportDirtyOverlap } from "./integrate-dirty-overlap.mjs";
10
16
  import {
11
17
  isFastForwardCapableIntegrate,
18
+ listIntegrateDirtyPaths,
12
19
  resolveRulesManifestIntegrateDrift,
13
20
  } from "./rules-manifest-drift.mjs";
14
21
  import { assertOrchIntegratable } from "./integrate-assert.mjs";
@@ -28,78 +35,10 @@ function git(projectRoot, args) {
28
35
  return gitExec(projectRoot, args, { projectRoot });
29
36
  }
30
37
 
31
- /**
32
- * @param {string} output
33
- */
34
- function mergeTreeOutputHasConflict(output) {
35
- return /CONFLICT/i.test(output);
36
- }
37
-
38
- /**
39
- * Ref-only merge when base is not checked out in projectRoot (avoids worktree git merge).
40
- *
41
- * @param {object} params
42
- * @param {string} params.projectRoot
43
- * @param {string} params.baseBranch
44
- * @param {string} params.orchBranch
45
- * @param {string} params.mergeMessage
46
- */
47
- function mergeOrchIntoBaseViaRefs({ projectRoot, baseBranch, orchBranch, mergeMessage }) {
48
- const baseSha = git(projectRoot, ["rev-parse", baseBranch]);
49
- const orchSha = git(projectRoot, ["rev-parse", orchBranch]);
50
-
51
- let mergeTreeOutput = "";
52
- let treeSha = "";
53
- try {
54
- mergeTreeOutput = execFileSync(
55
- "git",
56
- ["merge-tree", "--write-tree", baseBranch, orchBranch],
57
- {
58
- cwd: projectRoot,
59
- encoding: "utf-8",
60
- stdio: ["ignore", "pipe", "pipe"],
61
- env: { ...process.env },
62
- },
63
- ).trim();
64
- treeSha = mergeTreeOutput.split("\n").pop()?.trim() ?? "";
65
- } catch (err) {
66
- const stdout = err && typeof err === "object" && "stdout" in err ? String(err.stdout ?? "") : "";
67
- const stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr ?? "") : "";
68
- mergeTreeOutput = `${stdout}\n${stderr}`.trim();
69
- if (mergeTreeOutputHasConflict(mergeTreeOutput)) {
70
- return {
71
- ok: false,
72
- failureClass: "MergeConflict",
73
- error: mergeTreeOutput.split("\n").slice(-3).join(" ") || "merge conflict",
74
- };
75
- }
76
- const message = err instanceof Error ? err.message : String(err);
77
- return {
78
- ok: false,
79
- failureClass: "IntegrateFailed",
80
- error: message,
81
- };
82
- }
83
-
84
- if (!treeSha || mergeTreeOutputHasConflict(mergeTreeOutput)) {
85
- return {
86
- ok: false,
87
- failureClass: "MergeConflict",
88
- error: mergeTreeOutput || `merge conflict integrating ${orchBranch} into ${baseBranch}`,
89
- };
90
- }
91
-
92
- const mergeCommit = git(
93
- projectRoot,
94
- ["commit-tree", treeSha, "-p", baseSha, "-p", orchSha, "-m", mergeMessage],
95
- );
96
- git(projectRoot, ["update-ref", `refs/heads/${baseBranch}`, mergeCommit]);
97
-
98
- return { ok: true, mergeCommit, mode: "plumbing" };
99
- }
100
-
101
38
  /**
102
39
  * Fast-forward base to orch tip without checking out base in projectRoot.
40
+ * The ref update is compare-and-swap on baseShaBefore so a commit landing on base
41
+ * mid-integrate fails loudly instead of being orphaned (#298).
103
42
  *
104
43
  * @param {object} params
105
44
  * @param {string} params.projectRoot
@@ -109,7 +48,10 @@ function mergeOrchIntoBaseViaRefs({ projectRoot, baseBranch, orchBranch, mergeMe
109
48
  function fastForwardOrchIntoBase({ projectRoot, baseBranch, orchBranch }) {
110
49
  const baseShaBefore = git(projectRoot, ["rev-parse", baseBranch]);
111
50
  const orchSha = git(projectRoot, ["rev-parse", orchBranch]);
112
- git(projectRoot, ["update-ref", `refs/heads/${baseBranch}`, orchSha]);
51
+ const cas = casUpdateBaseRef({ projectRoot, baseBranch, newSha: orchSha, expectedOldSha: baseShaBefore });
52
+ if (!cas.ok) {
53
+ return cas;
54
+ }
113
55
  return {
114
56
  ok: true,
115
57
  mergeCommit: orchSha,
@@ -133,7 +75,7 @@ function runIntegrateMerge({ projectRoot, baseBranch, orchBranch, batchId }) {
133
75
  if (isBranchCheckedOutInWorktree(projectRoot, baseBranch)) {
134
76
  return mergeOrchIntoBaseIsolated({ projectRoot, baseBranch, orchBranch, batchId });
135
77
  }
136
- return mergeOrchIntoBaseViaRefs({ projectRoot, baseBranch, orchBranch, mergeMessage });
78
+ return plumbingMergeOrchIntoBase({ projectRoot, baseBranch, orchBranch, mergeMessage });
137
79
  }
138
80
 
139
81
  /**
@@ -371,6 +313,9 @@ export function integrateOrchToBase(ctx) {
371
313
  });
372
314
  }
373
315
 
316
+ // Capture before the merge moves the base ref: afterwards git status reports
317
+ // not-yet-materialized merged paths as modified/deleted vs the new HEAD (SP-784).
318
+ const preMergeDirtyPaths = listIntegrateDirtyPaths(projectRoot);
374
319
  const mergeResult = runIntegrateMerge({ projectRoot, baseBranch, orchBranch, batchId });
375
320
 
376
321
  if (!mergeResult.ok) {
@@ -399,25 +344,11 @@ export function integrateOrchToBase(ctx) {
399
344
 
400
345
  const mergeCommit = mergeResult.mergeCommit;
401
346
 
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.
419
- }
420
- }
347
+ // No sync when base is not checked out right now (SP-784 / #298): the merge commit is
348
+ // already on the base ref and the checkout must stay untouched.
349
+ const syncResult = syncMergeResultToCheckedOutBase(projectRoot, baseBranch, mergeResult, {
350
+ dirtyPaths: preMergeDirtyPaths,
351
+ });
421
352
 
422
353
  if (syncResult && !syncResult.ok) {
423
354
  appendJournalEvent(projectRoot, batchId, "integrate.failed", {
@@ -446,6 +377,15 @@ export function integrateOrchToBase(ctx) {
446
377
  };
447
378
  }
448
379
 
380
+ const dirtyOverlapWarning = reportDirtyOverlap({
381
+ projectRoot,
382
+ batchId,
383
+ baseBranch,
384
+ orchBranch,
385
+ mergeCommit,
386
+ skippedDirtyPaths: syncResult?.skippedDirtyPaths,
387
+ });
388
+
449
389
  appendJournalEvent(projectRoot, batchId, "integrate.completed", {
450
390
  baseBranch,
451
391
  orchBranch,
@@ -467,6 +407,7 @@ export function integrateOrchToBase(ctx) {
467
407
  headline: `Integrated ${orchBranch} into ${baseBranch}`,
468
408
  suggestedCommand: "spine batch complete",
469
409
  alternatives: ["spine status --diagnose"],
410
+ ...(dirtyOverlapWarning ? { warnings: [dirtyOverlapWarning] } : {}),
470
411
  };
471
412
  } catch (err) {
472
413
  const message = err instanceof Error ? err.message : String(err);
@@ -46,6 +46,31 @@ export function verifyJournalChecksum(event) {
46
46
  return computeJournalChecksum(rest) === checksum;
47
47
  }
48
48
 
49
+ const NEWLINE_BYTE = 0x0a;
50
+
51
+ /**
52
+ * Isolate a torn tail before appending: when a previous append was torn by a
53
+ * crash or disk-full, the file can end mid-line without a trailing newline.
54
+ * Writing a newline first keeps the torn fragment on its own line so the new
55
+ * event stays parseable and the corruption stops propagating (SP-780).
56
+ * @param {string} filePath
57
+ */
58
+ function appendNewlineIfTornTail(filePath) {
59
+ if (!fs.existsSync(filePath)) return;
60
+ const stat = fs.statSync(filePath);
61
+ if (stat.size === 0) return;
62
+ const fd = fs.openSync(filePath, "r");
63
+ try {
64
+ const tail = Buffer.alloc(1);
65
+ fs.readSync(fd, tail, 0, 1, stat.size - 1);
66
+ if (tail[0] !== NEWLINE_BYTE) {
67
+ fs.appendFileSync(filePath, "\n", "utf-8");
68
+ }
69
+ } finally {
70
+ fs.closeSync(fd);
71
+ }
72
+ }
73
+
49
74
  /**
50
75
  * Append one jsonl line with fsync and bounded EBUSY/ENOENT retry.
51
76
  * Does not rewrite the journal file. In-process callers remain serialized
@@ -60,6 +85,7 @@ export function appendJsonlLineSync(filePath, line) {
60
85
  try {
61
86
  if (!appended) {
62
87
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
88
+ appendNewlineIfTornTail(filePath);
63
89
  fs.appendFileSync(filePath, line, "utf-8");
64
90
  appended = true;
65
91
  }
@@ -211,19 +211,38 @@ export function exportJournalJsonl(projectRoot, batchId) {
211
211
  }
212
212
 
213
213
  /**
214
- * Parse jsonl journal content into normalized events. Lines whose checksum is
215
- * present but mismatches are skipped (fail-closed per-line) without
216
- * discarding the rest of the file; legacy lines without checksum load as-is.
214
+ * Parse jsonl journal content into normalized events, tolerating torn lines.
215
+ * Each line is parsed in its own try/catch: a line that fails JSON.parse
216
+ * (torn write from a crash or disk-full) or whose present checksum mismatches
217
+ * is skipped (fail-closed per-line) without discarding the rest of the file;
218
+ * legacy lines without checksum load as-is. Alongside the events, returns
219
+ * skipped-line metadata (1-based lineNumber, byteOffset, reason) so diagnosis
220
+ * surfaces can report corruption instead of losing every valid event.
217
221
  * @param {string} content Raw jsonl content.
218
- * @returns {object[]}
222
+ * @returns {{ events: object[], skippedLines: Array<{ lineNumber: number, byteOffset: number, reason: string }> }}
219
223
  */
220
- function parseJournalLines(content) {
221
- return content
222
- .split("\n")
223
- .filter(Boolean)
224
- .map((line) => JSON.parse(line))
225
- .filter((parsed) => verifyJournalChecksum(parsed))
226
- .map((parsed) => normalizeJournalEvent(parsed));
224
+ export function parseJournalLines(content) {
225
+ /** @type {object[]} */
226
+ const events = [];
227
+ /** @type {Array<{ lineNumber: number, byteOffset: number, reason: string }>} */
228
+ const skippedLines = [];
229
+ let byteOffset = 0;
230
+ for (const [index, line] of content.split("\n").entries()) {
231
+ if (line) {
232
+ try {
233
+ const parsed = JSON.parse(line);
234
+ if (verifyJournalChecksum(parsed)) {
235
+ events.push(normalizeJournalEvent(parsed));
236
+ } else {
237
+ skippedLines.push({ lineNumber: index + 1, byteOffset, reason: "checksum_mismatch" });
238
+ }
239
+ } catch {
240
+ skippedLines.push({ lineNumber: index + 1, byteOffset, reason: "json_parse_error" });
241
+ }
242
+ }
243
+ byteOffset += Buffer.byteLength(line, "utf-8") + 1;
244
+ }
245
+ return { events, skippedLines };
227
246
  }
228
247
 
229
248
  /**
@@ -235,7 +254,7 @@ export function readJournalEvents(projectRoot, batchId) {
235
254
  const filePath = journalPath(projectRoot, batchId);
236
255
  if (!fs.existsSync(filePath)) return [];
237
256
 
238
- return parseJournalLines(fs.readFileSync(filePath, "utf-8"));
257
+ return parseJournalLines(fs.readFileSync(filePath, "utf-8")).events;
239
258
  }
240
259
 
241
260
  /**
@@ -268,7 +287,7 @@ export function readJournalEventsCached(projectRoot, batchId) {
268
287
  return _journalCache.events;
269
288
  }
270
289
 
271
- const events = parseJournalLines(fs.readFileSync(filePath, "utf-8"));
290
+ const events = parseJournalLines(fs.readFileSync(filePath, "utf-8")).events;
272
291
 
273
292
  _journalCache.filePath = filePath;
274
293
  _journalCache.mtimeMs = stat.mtimeMs;
@@ -6,9 +6,84 @@
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { appendJournalEvent } from "./journal.mjs";
9
- import { clearActiveBatchStateIfMatches } from "./batch-state-io.mjs";
9
+ import {
10
+ clearActiveBatchStateIfMatches,
11
+ loadBatchStateFile,
12
+ readBatchStateId,
13
+ } from "./batch-state-io.mjs";
10
14
  import { removeLaneWorktrees, maxLaneNumberFromBatchState } from "./worktree.mjs";
11
15
 
16
+ /**
17
+ * Phases a resume/pause/engine writer can leave behind between a terminal
18
+ * write's pre-lock read and its lock section (SP-792 / #301). When the state
19
+ * re-read inside the lock holds one of these, the batch is active again and
20
+ * the pre-lock dismiss/complete decision no longer holds — fail closed.
21
+ * `executing` is excluded because it is a limbo phase that legitimately
22
+ * allows dismiss (limbo_stale).
23
+ */
24
+ const ACTIVE_RESUME_PHASES = new Set(["planning", "running", "paused", "merging"]);
25
+
26
+ /**
27
+ * Re-read the active batch state inside the terminal lock section
28
+ * (SP-792 / #301) so archive, history, and clear act on the freshest on-disk
29
+ * snapshot instead of the pre-lock read, which goes stale when a concurrent
30
+ * engine save lands between the read and the lock.
31
+ *
32
+ * Fail-closed contract: returns a ready-to-return non-ok `refusal` when the
33
+ * state file vanished, no longer parses, now describes a different batch, or
34
+ * — with `requireTerminalPhase` — the batch became active again mid-write.
35
+ * Abort passes `requireTerminalPhase: false` because aborting a running
36
+ * batch is its normal use case.
37
+ *
38
+ * @param {object} params
39
+ * @param {string} params.projectRoot
40
+ * @param {string|null} params.batchStatePath path used by the pre-lock read
41
+ * @param {string} params.batchId batch id the reloaded state must still match
42
+ * @param {"abort"|"dismiss"|"complete"} params.action action name for the refusal headline
43
+ * @param {boolean} [params.requireTerminalPhase] re-validate the terminal-phase precondition on the in-lock state
44
+ * @param {boolean} [params.force] `dismiss --force` skips the phase re-validation
45
+ * @param {string|null} [params.diagnosis] pre-lock diagnosis echoed on refusal
46
+ * @returns {{ state: { path: string, raw: object }|null, refusal: object|null }}
47
+ */
48
+ export function reloadStateForTerminalWrite({
49
+ projectRoot,
50
+ batchStatePath,
51
+ batchId,
52
+ action,
53
+ requireTerminalPhase = false,
54
+ force = false,
55
+ diagnosis = null,
56
+ }) {
57
+ const refuse = () => ({
58
+ ok: false,
59
+ exitCode: 1,
60
+ error: "batch_state_changed_during_terminal_write",
61
+ headline: `Batch state changed during ${action} — re-run spine status --diagnose`,
62
+ suggestedCommand: "spine status --diagnose",
63
+ diagnosis: diagnosis ?? null,
64
+ batchId,
65
+ });
66
+
67
+ const reloaded = loadBatchStateFile(projectRoot, batchStatePath);
68
+ if (!reloaded.path || !reloaded.raw || reloaded.parseError) {
69
+ return { state: null, refusal: refuse() };
70
+ }
71
+
72
+ const reloadedBatchId = readBatchStateId(reloaded.raw);
73
+ if (!reloadedBatchId || reloadedBatchId !== batchId) {
74
+ return { state: null, refusal: refuse() };
75
+ }
76
+
77
+ if (requireTerminalPhase && !force) {
78
+ const phase = String(/** @type {{ phase?: string }} */ (reloaded.raw).phase ?? "");
79
+ if (ACTIVE_RESUME_PHASES.has(phase)) {
80
+ return { state: null, refusal: refuse() };
81
+ }
82
+ }
83
+
84
+ return { state: { path: reloaded.path, raw: reloaded.raw }, refusal: null };
85
+ }
86
+
12
87
  /**
13
88
  * @param {string} projectRoot
14
89
  * @param {string} batchId
@@ -38,11 +113,17 @@ export function archiveBatchState(projectRoot, batchId, raw) {
38
113
  }
39
114
 
40
115
  /**
116
+ * Clear the completed batch-state pointer under the global batch-state lock
117
+ * (SP-722 / #264; SP-786 / #303). Delegates to `clearActiveBatchStateIfMatches`,
118
+ * which quarantines corrupt state instead of deleting it and refuses to touch
119
+ * Taskplane-owned `.pi/` state files.
120
+ *
121
+ * @param {string} projectRoot
41
122
  * @param {string|null} batchStatePath
42
123
  * @param {string} batchId
43
124
  */
44
- export function clearCompletedBatchState(batchStatePath, batchId) {
45
- clearActiveBatchStateIfMatches(batchStatePath, batchId);
125
+ export function clearCompletedBatchState(projectRoot, batchStatePath, batchId) {
126
+ clearActiveBatchStateIfMatches(batchStatePath, batchId, projectRoot);
46
127
  }
47
128
 
48
129
  /**