pi-spine 2.3.1 → 2.4.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.
@@ -2,18 +2,10 @@
2
2
  /**
3
3
  * Rebuild batch task/segment status from append-only journal (FR-REL-01/02, PRD §11.4).
4
4
  * Structural derivation → journal-rebuild-structural.mjs (SP-584).
5
- * Drift reconcile remains here until SP-602.
5
+ * Drift / done-marker / orphan-review → journal-rebuild-drift.mjs (SP-602).
6
+ * This file is the stable public re-export shim.
6
7
  */
7
8
 
8
- import fs from "node:fs";
9
- import path from "node:path";
10
- import { execFileSync } from "node:child_process";
11
- import { appendJournalEvent } from "./journal.mjs";
12
- import { laneTaskBranch } from "./worktree.mjs";
13
- import { parseReviewVerdict } from "./review-shared.mjs";
14
- import { journalHasTaskCompleted } from "./resume-common.mjs";
15
- import { recordTaskSucceeded, saveSpineBatchState } from "./state.mjs";
16
-
17
9
  export {
18
10
  BATCH_PHASE_EVENT_TYPES,
19
11
  deriveStructuralBatchStateFromJournal,
@@ -24,385 +16,13 @@ export {
24
16
  TASK_LIFECYCLE_EVENT_TYPES,
25
17
  } from "./journal-rebuild-structural.mjs";
26
18
 
27
- import { TASK_LIFECYCLE_EVENT_TYPES } from "./journal-rebuild-structural.mjs";
28
-
29
- /** @typedef {{ taskId: string, field: string, cached: unknown, rebuilt: unknown }} DriftEntry */
30
-
31
- const NON_TERMINAL_CACHE_STATUSES = new Set(["pending", "running"]);
32
- const JOURNAL_TERMINAL_LIFECYCLE = new Set([
33
- "task.completed",
34
- "task.skipped",
35
- "task.skipped_done_on_disk",
36
- "task.failed",
37
- "task.prompt_parse_failed",
38
- ]);
39
-
40
- function lastLifecycleEventForTask(events, taskId) {
41
- const taskEvents = events.filter(
42
- (event) => event?.taskId === taskId && TASK_LIFECYCLE_EVENT_TYPES.has(String(event?.type ?? "")),
43
- );
44
- return taskEvents.length > 0 ? taskEvents[taskEvents.length - 1] : null;
45
- }
46
-
47
- function hasJournalTerminalLifecycle(lastEvent) {
48
- if (!lastEvent) return false;
49
- return JOURNAL_TERMINAL_LIFECYCLE.has(String(lastEvent.type ?? ""));
50
- }
51
-
52
- /**
53
- * @param {object|null|undefined} classified
54
- */
55
- function classifiedShowsDoneInLaneDrift(classified) {
56
- if (!classified || typeof classified !== "object") return false;
57
- if (classified.doneInLane === true) return true;
58
- return (
59
- classified.classification === "terminal-success" &&
60
- !["succeeded", "skipped"].includes(String(classified.status ?? "").toLowerCase())
61
- );
62
- }
63
-
64
- export function normalizeTaskFolderRel(projectRoot, taskFolder) {
65
- if (!taskFolder) return null;
66
- if (path.isAbsolute(taskFolder)) {
67
- return path.relative(projectRoot, taskFolder).replace(/\\/g, "/");
68
- }
69
- return String(taskFolder).replace(/\\/g, "/");
70
- }
71
-
72
- /**
73
- * True when `.DONE` is committed on the lane task branch (fail-closed / #190).
74
- *
75
- * @param {string} projectRoot
76
- * @param {string} taskBranch
77
- * @param {string} taskFolderRel
78
- */
79
- export function laneDoneMarkerCommittedOnBranch(projectRoot, taskBranch, taskFolderRel) {
80
- const folderRel = normalizeTaskFolderRel(projectRoot, taskFolderRel);
81
- if (!projectRoot || !taskBranch || !folderRel) return false;
82
- const donePath = `${folderRel.replace(/\/+$/, "")}/.DONE`;
83
- try {
84
- execFileSync("git", ["cat-file", "-e", `${taskBranch}:${donePath}`], {
85
- cwd: projectRoot,
86
- stdio: ["ignore", "pipe", "pipe"],
87
- timeout: 5000,
88
- });
89
- return true;
90
- } catch {
91
- return false;
92
- }
93
- }
94
-
95
- /**
96
- * @param {object} task
97
- * @param {string} batchId
98
- * @param {unknown[]} lanes
99
- * @param {string} projectRoot
100
- */
101
- function laneTaskBranchForTask(task, batchId, lanes) {
102
- const laneNumber = Number(task.laneNumber ?? 1);
103
- const lane = Array.isArray(lanes)
104
- ? lanes.find((entry) => Number(entry?.laneNumber) === laneNumber)
105
- : null;
106
- if (lane && typeof lane.branch === "string" && lane.branch) {
107
- return lane.branch;
108
- }
109
- return laneTaskBranch(batchId, laneNumber);
110
- }
111
-
112
- /**
113
- * Fail-closed gate: filesystem `.DONE` in lane worktree and committed on lane branch.
114
- *
115
- * @param {object} params
116
- * @param {string} params.projectRoot
117
- * @param {string} params.batchId
118
- * @param {object} params.task
119
- * @param {unknown[]} [params.lanes]
120
- * @param {object|null|undefined} params.classified
121
- */
122
- export function laneDoneMarkerReadyForPromote({ projectRoot, batchId, task, lanes = [], classified }) {
123
- if (classified?.doneInLane !== true) return false;
124
- const taskFolder = normalizeTaskFolderRel(projectRoot, task?.taskFolder);
125
- if (!taskFolder) return false;
126
- const taskBranch = laneTaskBranchForTask(task, batchId, lanes);
127
- return laneDoneMarkerCommittedOnBranch(projectRoot, taskBranch, taskFolder);
128
- }
129
-
130
- /**
131
- * Detect review.started events that have no matching review.completed for the same
132
- * taskId + reviewType. These represent engine crashes mid-review where the artifact
133
- * may exist on disk but the completion was never journaled.
134
- *
135
- * @param {object[]} events
136
- * @returns {object[]} orphaned review.started events
137
- */
138
- export function detectOrphanedReviewStarted(events) {
139
- /** @type {Map<string, object>} keyed by "taskId:reviewType" */
140
- const latestStarted = new Map();
141
- /** @type {Set<string>} */
142
- const completedKeys = new Set();
143
-
144
- for (const event of events) {
145
- const type = String(event?.type ?? "");
146
- const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
147
- const taskId = event.taskId ?? payload.taskId;
148
- if (!taskId) continue;
149
- const reviewType = payload.reviewType;
150
- if (!reviewType) continue;
151
- const key = `${taskId}:${reviewType}`;
152
-
153
- if (type === "review.started") {
154
- latestStarted.set(key, event);
155
- } else if (type === "review.completed") {
156
- completedKeys.add(key);
157
- latestStarted.delete(key);
158
- }
159
- }
160
-
161
- const orphaned = [];
162
- for (const [key, event] of latestStarted) {
163
- if (!completedKeys.has(key)) {
164
- orphaned.push(event);
165
- }
166
- }
167
- return orphaned;
168
- }
169
-
170
- /** @type {ReadonlySet<string>} Verdicts that indicate a successful review outcome. */
171
- const APPROVED_VERDICTS = new Set(["APPROVE", "PASS"]);
172
-
173
- /**
174
- * Reconcile orphaned review.started events by checking for on-disk artifacts with
175
- * valid verdicts and synthesizing the missing review.completed + task.completed events.
176
- * Called at resume time to self-heal after engine crashes mid-review (SP-484 / #131).
177
- *
178
- * @param {object} params
179
- * @param {string} params.projectRoot
180
- * @param {string} params.batchId
181
- * @param {object[]} params.events - journal events
182
- * @returns {{ synthesized: Array<{ taskId: string, reviewType: string, verdict: string, artifactPath: string }> }}
183
- */
184
- export function reconcileOrphanedReviewEvents({ projectRoot, batchId, events }) {
185
- const orphaned = detectOrphanedReviewStarted(events);
186
- /** @type {Array<{ taskId: string, reviewType: string, verdict: string, artifactPath: string }>} */
187
- const synthesized = [];
188
-
189
- for (const event of orphaned) {
190
- const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
191
- const artifactPath = typeof payload.artifactPath === "string" ? payload.artifactPath : "";
192
- const taskId = event.taskId ?? payload.taskId;
193
- if (!taskId || !artifactPath) continue;
194
- if (!fs.existsSync(artifactPath)) continue;
195
-
196
- let content;
197
- try {
198
- content = fs.readFileSync(artifactPath, "utf-8");
199
- } catch {
200
- continue;
201
- }
202
-
203
- const reviewType = payload.reviewType ?? "code";
204
- const { verdict, feedback } = parseReviewVerdict(content, { reviewType });
205
- if (!verdict || !APPROVED_VERDICTS.has(verdict)) continue;
206
-
207
- appendJournalEvent(projectRoot, batchId, "review.completed", {
208
- taskId,
209
- laneNumber: payload.laneNumber ?? null,
210
- correlationId: payload.correlationId ?? null,
211
- stepNumber: payload.stepNumber ?? null,
212
- reviewType,
213
- reviewLevel: payload.reviewLevel ?? null,
214
- verdict,
215
- feedback: feedback ?? "",
216
- artifactPath,
217
- synthesized: true,
218
- synthesizeReason: "orphaned_review_crash_recovery",
219
- });
220
-
221
- appendJournalEvent(projectRoot, batchId, "task.completed", {
222
- taskId,
223
- laneNumber: payload.laneNumber ?? null,
224
- correlationId: payload.correlationId ?? null,
225
- synthesized: true,
226
- synthesizeReason: "orphaned_review_crash_recovery",
227
- exitReason: "done",
228
- doneFileFound: true,
229
- });
230
-
231
- synthesized.push({ taskId, reviewType, verdict, artifactPath });
232
- }
233
-
234
- return { synthesized };
235
- }
236
-
237
- export function detectBatchStateDrift(cachedState, rebuiltState, events = [], classifiedTasks = null) {
238
- /** @type {DriftEntry[]} */
239
- const entries = [];
240
- const rebuiltById = new Map((rebuiltState?.tasks ?? []).map((task) => [String(task?.taskId), task]));
241
- const classifiedById = Array.isArray(classifiedTasks)
242
- ? new Map(classifiedTasks.map((task) => [String(task?.taskId), task]))
243
- : null;
244
-
245
- for (const cached of cachedState?.tasks ?? []) {
246
- if (!cached?.taskId) continue;
247
- const taskId = String(cached.taskId);
248
- const rebuilt = rebuiltById.get(taskId);
249
- if (!rebuilt) continue;
250
- const classified = classifiedById?.get(taskId) ?? null;
251
- const cachedStatus = String(cached.status ?? "").toLowerCase();
252
- const lastEvent = lastLifecycleEventForTask(events, taskId);
253
- const lastType = lastEvent ? String(lastEvent.type ?? "") : "";
254
-
255
- if (
256
- NON_TERMINAL_CACHE_STATUSES.has(cachedStatus) &&
257
- classifiedShowsDoneInLaneDrift(classified) &&
258
- !hasJournalTerminalLifecycle(lastEvent)
259
- ) {
260
- entries.push({
261
- taskId,
262
- field: "doneInLane",
263
- cached: cached.status,
264
- rebuilt: classified?.classification ?? "terminal-success",
265
- });
266
- continue;
267
- }
268
-
269
- if (!lastEvent) continue;
270
-
271
- if (lastType === "task.completed" && cached.status !== "succeeded") {
272
- entries.push({ taskId, field: "status", cached: cached.status, rebuilt: rebuilt.status });
273
- continue;
274
- }
275
- if (lastType === "task.retry_requested" && cached.status === "failed" && rebuilt.status === "pending") {
276
- entries.push({ taskId, field: "status", cached: cached.status, rebuilt: rebuilt.status });
277
- continue;
278
- }
279
- if (lastType === "task.started" && cached.status === "failed") continue;
280
- if ((lastType === "task.failed" || lastType === "task.prompt_parse_failed") && cached.status === rebuilt.status) continue;
281
- }
282
-
283
- return { drifted: entries.length > 0, entries };
284
- }
285
-
286
- /**
287
- * Journal evidence that lane work finished and review/contract passed (FR-STA-01 / #170).
288
- *
289
- * @param {object[]} events
290
- * @param {string} taskId
291
- */
292
- export function journalShowsDoneInLaneTerminalArtifacts(events, taskId) {
293
- let hasApprovedReview = false;
294
- let hasLaneCompleted = false;
295
- let hasContractVerified = false;
296
-
297
- for (const event of events ?? []) {
298
- const type = String(event?.type ?? "");
299
- const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
300
- const eventTaskId = event.taskId ?? payload.taskId;
301
- if (eventTaskId !== taskId) continue;
302
-
303
- if (type === "review.completed" && APPROVED_VERDICTS.has(String(payload.verdict ?? ""))) {
304
- hasApprovedReview = true;
305
- }
306
- if (type === "task.verdict_recorded" && APPROVED_VERDICTS.has(String(payload.verdict ?? ""))) {
307
- hasApprovedReview = true;
308
- }
309
- if (type === "lane.completed") {
310
- hasLaneCompleted = true;
311
- }
312
- if (type === "contract.verified" && payload.ok === true) {
313
- hasContractVerified = true;
314
- }
315
- }
316
-
317
- return hasLaneCompleted && (hasApprovedReview || hasContractVerified);
318
- }
319
-
320
- /**
321
- * Promote batch-state tasks when lane on-disk truth and journal show terminal success
322
- * but cache still shows pending/running (idempotent; FR-STA-01 / SP-512).
323
- *
324
- * @param {object} params
325
- * @param {string} params.projectRoot
326
- * @param {object} params.state
327
- * @param {object[]} [params.classifiedTasks]
328
- * @param {object[]} [params.journalEvents]
329
- * @param {{ drifted?: boolean, entries?: Array<{ taskId: string, field: string, rebuilt?: unknown }> }} [params.drift]
330
- * @returns {{ reconciled: boolean, taskIds: string[] }}
331
- */
332
- export function reconcileBatchStateDrift({
333
- projectRoot,
334
- state,
335
- classifiedTasks = [],
336
- journalEvents = [],
337
- drift = null,
338
- }) {
339
- if (!state || typeof state !== "object" || !drift?.drifted || !Array.isArray(drift.entries)) {
340
- return { reconciled: false, taskIds: [] };
341
- }
342
-
343
- const batchId = String(state.batchId ?? "");
344
- if (!batchId) {
345
- return { reconciled: false, taskIds: [] };
346
- }
347
-
348
- const classifiedById = new Map(
349
- (classifiedTasks ?? []).map((task) => [String(task?.taskId ?? ""), task]),
350
- );
351
- /** @type {string[]} */
352
- const reconciledTaskIds = [];
353
- let changed = false;
354
-
355
- for (const entry of drift.entries) {
356
- const taskId = String(entry?.taskId ?? "");
357
- if (!taskId || taskId === "*") continue;
358
-
359
- const task = (state.tasks ?? []).find((row) => row?.taskId === taskId);
360
- if (!task) continue;
361
-
362
- if (entry.field === "status" && String(entry.rebuilt ?? "") === "succeeded") {
363
- if (String(task.status ?? "") === "succeeded") continue;
364
- if (!recordTaskSucceeded(state, taskId, { doneFileFound: true, exitReason: "done" })) continue;
365
- reconciledTaskIds.push(taskId);
366
- changed = true;
367
- continue;
368
- }
369
-
370
- if (entry.field !== "doneInLane") continue;
371
-
372
- const classified = classifiedById.get(taskId);
373
- if (!classifiedShowsDoneInLaneDrift(classified)) continue;
374
- if (
375
- !laneDoneMarkerReadyForPromote({
376
- projectRoot,
377
- batchId,
378
- task,
379
- lanes: state.lanes ?? [],
380
- classified,
381
- })
382
- ) {
383
- continue;
384
- }
385
- if (journalHasTaskCompleted(journalEvents, taskId)) continue;
386
- if (!journalShowsDoneInLaneTerminalArtifacts(journalEvents, taskId)) continue;
387
- if (String(task.status ?? "") === "succeeded") continue;
388
-
389
- if (!recordTaskSucceeded(state, taskId, { doneFileFound: true, exitReason: "done" })) continue;
390
-
391
- appendJournalEvent(projectRoot, batchId, "task.completed", {
392
- taskId,
393
- laneNumber: task.laneNumber ?? null,
394
- reconciled: true,
395
- reconcileReason: "done_in_lane_terminal",
396
- skippedDoneOnDisk: true,
397
- });
398
-
399
- reconciledTaskIds.push(taskId);
400
- changed = true;
401
- }
402
-
403
- if (changed) {
404
- saveSpineBatchState(projectRoot, state);
405
- }
406
-
407
- return { reconciled: changed, taskIds: reconciledTaskIds };
408
- }
19
+ export {
20
+ detectBatchStateDrift,
21
+ detectOrphanedReviewStarted,
22
+ journalShowsDoneInLaneTerminalArtifacts,
23
+ laneDoneMarkerCommittedOnBranch,
24
+ laneDoneMarkerReadyForPromote,
25
+ normalizeTaskFolderRel,
26
+ reconcileBatchStateDrift,
27
+ reconcileOrphanedReviewEvents,
28
+ } from "./journal-rebuild-drift.mjs";
@@ -6,6 +6,7 @@
6
6
  import fs from "node:fs";
7
7
  import { isProcessAlive } from "../process/liveness.mjs";
8
8
  import { hasPendingWaveMerge } from "./merge/wave-merge-state.mjs";
9
+ import { ensureForceResumeBatchState } from "./batch-meta-reconstruct.mjs";
9
10
  import { loadGateRecord } from "./gate.mjs";
10
11
  import { readJournalEvents } from "./journal.mjs";
11
12
  import { detectOrphanRunning, journalEventsSinceResume } from "./orphan-detect.mjs";
@@ -59,9 +60,26 @@ export function detectPostMergeLimboForResume({ projectRoot, state }) {
59
60
 
60
61
  export { hasPendingWaveMerge } from "./merge/wave-merge-state.mjs";
61
62
 
63
+ /**
64
+ * Whether every task is terminal-success (or skipped) for #196 drift recovery.
65
+ *
66
+ * @param {object|null|undefined} state
67
+ */
68
+ function allTasksTerminalSuccessForResume(state) {
69
+ const tasks = state?.tasks ?? [];
70
+ if (tasks.length < 1) return false;
71
+ return tasks.every((task) => {
72
+ const status = String(task?.status ?? "").toLowerCase();
73
+ return status === "succeeded" || status === "skipped";
74
+ });
75
+ }
76
+
62
77
  /**
63
78
  * Assess whether a running-phase batch may resume after a dead detached engine (SP-296).
64
79
  *
80
+ * Also covers SP-613 / #196: pidless engine + all tasks terminal-success + pending wave
81
+ * merge (doneInLane healed, enginePid cleared) must not dead-end on phase=running.
82
+ *
65
83
  * @param {object} params
66
84
  * @param {string} params.projectRoot
67
85
  * @param {object} params.state
@@ -83,17 +101,25 @@ export function assessRunningPhaseResumeEligibility({ projectRoot, state }) {
83
101
  const enginePid = readBatchEnginePid(state);
84
102
  const enginePidDead = enginePid != null && !isProcessAlive(enginePid);
85
103
  const pidlessEngineOrphan = enginePid == null && orphanRunning?.kind === "engine";
86
- const engineConfirmedDead = enginePidDead || pidlessEngineOrphan;
104
+ // Dead/missing engine with work finished but merge not landed — agent-safe detached resume (#196).
105
+ const pidlessTerminalSuccessPendingMerge =
106
+ enginePid == null &&
107
+ allTasksTerminalSuccessForResume(state) &&
108
+ hasPendingWaveMerge(state);
109
+ const engineConfirmedDead =
110
+ enginePidDead || pidlessEngineOrphan || pidlessTerminalSuccessPendingMerge;
87
111
 
88
112
  const allowOrphanResume =
89
113
  engineConfirmedDead &&
90
- orphanRunning != null &&
91
- (orphanRunning.kind === "engine" || orphanRunning.kind === "lane");
114
+ ((orphanRunning != null &&
115
+ (orphanRunning.kind === "engine" || orphanRunning.kind === "lane")) ||
116
+ pidlessTerminalSuccessPendingMerge);
92
117
 
93
118
  return {
94
119
  engineConfirmedDead,
95
120
  allowOrphanResume,
96
- orphanKind: orphanRunning?.kind ?? null,
121
+ orphanKind: orphanRunning?.kind ?? (pidlessTerminalSuccessPendingMerge ? "engine" : null),
122
+ terminalSuccessPendingMerge: pidlessTerminalSuccessPendingMerge,
97
123
  };
98
124
  }
99
125
 
@@ -103,9 +129,21 @@ export function assessRunningPhaseResumeEligibility({ projectRoot, state }) {
103
129
  * @param {boolean} [params.force]
104
130
  */
105
131
  export function validateMultiTaskResume({ projectRoot, force = false }) {
106
- const loaded = loadSpineBatchState(projectRoot);
132
+ let loaded = loadSpineBatchState(projectRoot);
107
133
  if (!loaded.raw) {
108
- return { ok: false, exitCode: 1, error: "no_active_batch", output: "No active pi-spine batch.\n" };
134
+ const ensured = ensureForceResumeBatchState(projectRoot, { force });
135
+ if (!ensured.ok) {
136
+ return {
137
+ ok: false,
138
+ exitCode: ensured.exitCode ?? 1,
139
+ error: ensured.error ?? "no_active_batch",
140
+ output: ensured.output ?? "No active pi-spine batch.\n",
141
+ };
142
+ }
143
+ loaded = loadSpineBatchState(projectRoot);
144
+ if (!loaded.raw) {
145
+ return { ok: false, exitCode: 1, error: "no_active_batch", output: "No active pi-spine batch.\n" };
146
+ }
109
147
  }
110
148
 
111
149
  const state = loaded.raw;
@@ -9,6 +9,7 @@ import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
9
  import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
10
10
  import { installAttachedEngineShutdownHandlers } from "./attached-engine-handoff.mjs";
11
11
  import { enforceAttachedEngineSingleOwner, finalizeResumePostMergeLimbo } from "./attached-runner.mjs";
12
+ import { ensureForceResumeBatchState } from "./batch-meta-reconstruct.mjs";
12
13
  import { openIntegrateGateAfterBatchComplete } from "./gate.mjs";
13
14
  import { finalizeResumedBatchForIntegrate, isPostMergeLimbo } from "./post-merge-limbo.mjs";
14
15
  import { prepareOrphanResumeHandoff } from "./resume-engine.mjs";
@@ -39,12 +40,9 @@ import { recordTaskFailureSalvage } from "./salvage.mjs";
39
40
 
40
41
  export { pauseBatch } from "./pause.mjs";
41
42
  export { validateResumeBatch } from "./resume-single-validate.mjs";
43
+ export { ensureForceResumeBatchState } from "./batch-meta-reconstruct.mjs";
42
44
 
43
- /**
44
- * @param {object} params
45
- * @param {string} params.projectRoot
46
- * @param {boolean} [params.force]
47
- */
45
+ /** @param {{ projectRoot: string, force?: boolean }} params */
48
46
  export async function resumeBatch({ projectRoot, force = false }) {
49
47
  const engineLock = enforceAttachedEngineSingleOwner({ projectRoot, force, operation: "resume" });
50
48
  if (!engineLock.ok) {
@@ -52,6 +50,15 @@ export async function resumeBatch({ projectRoot, force = false }) {
52
50
  }
53
51
  const releaseResumeLock = engineLock.releaseResumeLock;
54
52
 
53
+ // SP-620 / #126: reconstruct from batch-meta when live state is missing/corrupt.
54
+ if (force) {
55
+ const ensured = ensureForceResumeBatchState(projectRoot, { force: true });
56
+ if (!ensured.ok && ensured.attempted) {
57
+ releaseResumeLock?.();
58
+ return ensured;
59
+ }
60
+ }
61
+
55
62
  const resumeCheck = validateResumeBatch({ projectRoot, force });
56
63
  if (!resumeCheck.ok) {
57
64
  releaseResumeLock?.();