pi-spine 2.19.0 → 2.20.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.
@@ -35,6 +35,7 @@ import {
35
35
  updateSegmentForTask,
36
36
  } from "./state.mjs";
37
37
  import { laneTaskBranch, laneWorktreePath } from "./worktree.mjs";
38
+ import { runMatrixTaskForResume } from "./engine-lanes/matrix-run.mjs";
38
39
  import { resumeMultiTaskBatch } from "./resume-multi.mjs";
39
40
  import { runLaneReviewPhasesBeforeCommit } from "./resume-lane-reviews.mjs";
40
41
  import { validateResumeBatch } from "./resume-single-validate.mjs";
@@ -44,7 +45,6 @@ import { recordTaskFailureSalvage } from "./salvage.mjs";
44
45
  export { pauseBatch } from "./pause.mjs";
45
46
  export { validateResumeBatch } from "./resume-single-validate.mjs";
46
47
  export { ensureForceResumeBatchState } from "./batch-meta-reconstruct.mjs";
47
-
48
48
  /** @param {{ projectRoot: string, force?: boolean }} params */
49
49
  export async function resumeBatch({ projectRoot, force = false }) {
50
50
  const engineLock = enforceAttachedEngineSingleOwner({ projectRoot, force, operation: "resume" });
@@ -187,6 +187,8 @@ export async function resumeBatch({ projectRoot, force = false }) {
187
187
  const laneCorrelationId = crypto.randomUUID();
188
188
  let workerResult = { ok: true, mode: "skipped" };
189
189
  let workerSucceeded = false;
190
+ // Matrix resume owns lane commit + success recording — skip plain worker postlude (#230).
191
+ let matrixHandled = false;
190
192
  const skippedWorkerBecauseComplete = taskAlreadyComplete({
191
193
  taskFolder: taskFolderInWorktree,
192
194
  events,
@@ -208,83 +210,101 @@ export async function resumeBatch({ projectRoot, force = false }) {
208
210
  resumed: true,
209
211
  });
210
212
 
211
- workerResult = await runWorker({
212
- worktreePath: wt,
213
- taskFolder: taskFolderInWorktree,
213
+ const matrixResume = await runMatrixTaskForResume({
214
214
  projectRoot,
215
+ state,
215
216
  batchId,
216
- laneNumber: 1,
217
- taskId,
218
- laneBranch: taskBranch,
217
+ baseBranch,
218
+ config,
219
+ task,
220
+ lane,
221
+ taskFolderRel,
219
222
  laneCorrelationId,
220
223
  fileScopePaths,
221
- config,
222
- onHeartbeat: (timestamp) => {
223
- state.lanes[0].lastHeartbeatAt = timestamp;
224
- saveSpineBatchState(projectRoot, state);
225
- },
226
- onWorkerPid: (pid) => {
227
- if (pid > 0) {
228
- state.lanes[0].workerPid = pid;
229
- saveSpineBatchState(projectRoot, state);
230
- }
231
- },
232
224
  });
233
-
234
- if (!workerResult.ok) {
235
- task.status = "failed";
236
- task.endedAt = Date.now();
237
- task.exitReason = workerResult.classification ?? "worker_failed";
238
- updateSegmentForTask(state, taskId, "failed");
239
- state.failedTasks = 1;
240
- state.succeededTasks = 0;
241
- state.endedAt = Date.now();
242
- state.lastError = workerResult.output?.slice(0, 500) ?? "worker failed";
243
- state.phase = "failed";
244
- saveSpineBatchState(projectRoot, state);
245
- const salvageFields = recordTaskFailureSalvage({
225
+ if (matrixResume.isMatrix) {
226
+ if (!matrixResume.ok) return matrixResume.cliResult;
227
+ workerSucceeded = true;
228
+ matrixHandled = true;
229
+ } else {
230
+ workerResult = await runWorker({
231
+ worktreePath: wt,
232
+ taskFolder: taskFolderInWorktree,
246
233
  projectRoot,
247
234
  batchId,
248
235
  laneNumber: 1,
249
- laneId: "lane-1",
250
236
  taskId,
251
- correlationId: laneCorrelationId,
252
- worktreePath: wt,
237
+ laneBranch: taskBranch,
238
+ laneCorrelationId,
253
239
  fileScopePaths,
254
- taskFolder: taskFolderInWorktree,
255
- workerResult,
256
240
  config,
257
- batchPhase: state.phase,
258
- taskBranch,
241
+ onHeartbeat: (timestamp) => {
242
+ state.lanes[0].lastHeartbeatAt = timestamp;
243
+ saveSpineBatchState(projectRoot, state);
244
+ },
245
+ onWorkerPid: (pid) => {
246
+ if (pid > 0) {
247
+ state.lanes[0].workerPid = pid;
248
+ saveSpineBatchState(projectRoot, state);
249
+ }
250
+ },
259
251
  });
260
- appendJournalEvent(projectRoot, batchId, "task.failed", {
261
- taskId,
252
+
253
+ if (!workerResult.ok) {
254
+ task.status = "failed";
255
+ task.endedAt = Date.now();
256
+ task.exitReason = workerResult.classification ?? "worker_failed";
257
+ updateSegmentForTask(state, taskId, "failed");
258
+ state.failedTasks = 1;
259
+ state.succeededTasks = 0;
260
+ state.endedAt = Date.now();
261
+ state.lastError = workerResult.output?.slice(0, 500) ?? "worker failed";
262
+ state.phase = "failed";
263
+ saveSpineBatchState(projectRoot, state);
264
+ const salvageFields = recordTaskFailureSalvage({
265
+ projectRoot,
266
+ batchId,
267
+ laneNumber: 1,
268
+ laneId: "lane-1",
269
+ taskId,
270
+ correlationId: laneCorrelationId,
271
+ worktreePath: wt,
272
+ fileScopePaths,
273
+ taskFolder: taskFolderInWorktree,
274
+ workerResult,
275
+ config,
276
+ batchPhase: state.phase,
277
+ taskBranch,
278
+ });
279
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
280
+ taskId,
281
+ laneNumber: 1,
282
+ laneId: "lane-1",
283
+ correlationId: laneCorrelationId,
284
+ ...workerResult,
285
+ ...salvageFields,
286
+ });
287
+ return {
288
+ ok: false,
289
+ exitCode: workerResult.exitCode ?? 1,
290
+ batchId,
291
+ taskId,
292
+ error: "worker_failed",
293
+ output: workerResult.output,
294
+ };
295
+ }
296
+
297
+ appendJournalEvent(projectRoot, batchId, "lane.completed", {
262
298
  laneNumber: 1,
263
299
  laneId: "lane-1",
300
+ taskId,
264
301
  correlationId: laneCorrelationId,
265
- ...workerResult,
266
- ...salvageFields,
267
302
  });
268
- return {
269
- ok: false,
270
- exitCode: workerResult.exitCode ?? 1,
271
- batchId,
272
- taskId,
273
- error: "worker_failed",
274
- output: workerResult.output,
275
- };
303
+ workerSucceeded = true;
276
304
  }
277
-
278
- appendJournalEvent(projectRoot, batchId, "lane.completed", {
279
- laneNumber: 1,
280
- laneId: "lane-1",
281
- taskId,
282
- correlationId: laneCorrelationId,
283
- });
284
- workerSucceeded = true;
285
305
  }
286
306
 
287
- if (workerSucceeded) {
307
+ if (workerSucceeded && !matrixHandled) {
288
308
  const lane =
289
309
  (state.lanes ?? []).find((entry) => entry.laneNumber === 1) ??
290
310
  {
@@ -0,0 +1,328 @@
1
+ /**
2
+ * Row-scoped matrix operations (SP-752 / #230).
3
+ *
4
+ * Split out of `retry.mjs` to keep that module under the Phase 23 500 LOC cap.
5
+ * Shared phase/load helpers live in `retry.mjs` and are imported from there
6
+ * (one-way dependency — `retry.mjs` never imports this module).
7
+ */
8
+
9
+ import {
10
+ countPendingSegments,
11
+ recordTaskTransition,
12
+ resetTaskForRetry,
13
+ validateBatchState,
14
+ } from "./state.mjs";
15
+ import { unblockBatchAfterRetry, loadMutableBatch, guardPhaseForMutation, findTask } from "./retry.mjs";
16
+
17
+ /**
18
+ * Parse a matrix row identity token `SP-X[rowId]` / `TP-X[rowId]`.
19
+ * Plain task ids and malformed brackets return null (CLI falls back to whole-task retry/skip).
20
+ *
21
+ * @param {unknown} raw
22
+ * @returns {{ taskId: string, rowId: string } | null}
23
+ */
24
+ export function parseMatrixRowRef(raw) {
25
+ if (typeof raw !== "string" || raw.length === 0) return null;
26
+ // Exact match: one pair of brackets, non-empty row id, no nested brackets.
27
+ const match = /^([A-Za-z]+-\d+)\[([^\[\]]+)\]$/.exec(raw);
28
+ if (!match) return null;
29
+ return { taskId: match[1], rowId: match[2] };
30
+ }
31
+
32
+ /**
33
+ * Row-scoped matrix retry (#230): `spine batch retry SP-X[rowId]` resets one
34
+ * `failed` row for re-execution without touching sibling rows — succeeded rows
35
+ * are never re-executed (their worktrees carry over), other failed rows stay
36
+ * failed until retried individually. The parent task re-enters the sweep so
37
+ * resume re-runs exactly the rows marked `pending`.
38
+ *
39
+ * @param {object} params
40
+ * @param {string} params.projectRoot
41
+ * @param {string} params.taskId Parent matrix task id.
42
+ * @param {string} params.rowId Row id inside `task.matrixRows`.
43
+ */
44
+ export function retryTaskRow({ projectRoot, taskId, rowId }) {
45
+ const loadedBatch = loadMutableBatch(projectRoot);
46
+ if (!loadedBatch.ok) return loadedBatch.result;
47
+ const state = loadedBatch.state;
48
+ const phase = String(state.phase ?? "");
49
+
50
+ const guard = guardPhaseForMutation({ phase, operation: "retry" });
51
+ if (!guard.ok) {
52
+ return {
53
+ ok: false,
54
+ exitCode: 1,
55
+ error: guard.error,
56
+ output: guard.output,
57
+ batchId: state.batchId,
58
+ phase,
59
+ };
60
+ }
61
+
62
+ const validation = validateBatchState(state);
63
+ if (!validation.ok) {
64
+ return {
65
+ ok: false,
66
+ exitCode: 1,
67
+ error: "invalid_batch_state",
68
+ output: `Batch state validation failed:\n ${validation.errors.join("\n ")}\n`,
69
+ batchId: state.batchId,
70
+ };
71
+ }
72
+
73
+ const task = findTask(state, taskId);
74
+ if (!task) {
75
+ return {
76
+ ok: false,
77
+ exitCode: 1,
78
+ error: "task_not_found",
79
+ output: `Task ${taskId} not found in batch ${state.batchId}.\n`,
80
+ batchId: state.batchId,
81
+ };
82
+ }
83
+
84
+ const rows = Array.isArray(task.matrixRows) ? task.matrixRows : [];
85
+ if (rows.length === 0) {
86
+ return {
87
+ ok: false,
88
+ exitCode: 1,
89
+ error: "not_a_matrix_task",
90
+ output: `Task ${taskId} has no matrix rows — retry the whole task with \`spine batch retry ${taskId}\`.\n`,
91
+ batchId: state.batchId,
92
+ taskId,
93
+ };
94
+ }
95
+
96
+ const row = rows.find((entry) => entry && typeof entry === "object" && entry.rowId === rowId);
97
+ if (!row) {
98
+ return {
99
+ ok: false,
100
+ exitCode: 1,
101
+ error: "row_not_found",
102
+ output: `Row ${taskId}[${rowId}] not found. Matrix rows: ${rows
103
+ .map((entry) => entry?.rowId)
104
+ .join(", ")}\n`,
105
+ batchId: state.batchId,
106
+ taskId,
107
+ };
108
+ }
109
+
110
+ if (row.status !== "failed") {
111
+ const reason =
112
+ row.status === "succeeded"
113
+ ? "already succeeded — succeeded rows are never re-executed"
114
+ : row.status === "canceled"
115
+ ? "was canceled — re-run the whole task to restore it"
116
+ : `is ${row.status ?? "pending"} — only failed rows can be retried`;
117
+ return {
118
+ ok: false,
119
+ exitCode: 1,
120
+ error: "row_not_retryable",
121
+ output: `Row ${taskId}[${rowId}] ${reason}.\n`,
122
+ batchId: state.batchId,
123
+ taskId,
124
+ };
125
+ }
126
+
127
+ // Parent/task/segment reset is identical to a whole-task retry; the only
128
+ // difference is which matrix rows re-enter the sweep as `pending`.
129
+ const reset = resetTaskForRetry(state, taskId);
130
+ if (!reset) {
131
+ return {
132
+ ok: false,
133
+ exitCode: 1,
134
+ error: "task_not_found",
135
+ output: `Task ${taskId} not found.\n`,
136
+ batchId: state.batchId,
137
+ };
138
+ }
139
+ row.status = "pending";
140
+ row.exitCode = null;
141
+
142
+ const unblocked = unblockBatchAfterRetry(state);
143
+ if (!unblocked) {
144
+ state.phase = "failed";
145
+ state.endedAt = null;
146
+ state.lastError = null;
147
+ }
148
+
149
+ state.resilience = state.resilience ?? {};
150
+ state.resilience.retryCountByScope = state.resilience.retryCountByScope ?? {};
151
+ const rowScope = `${taskId}[${rowId}]`;
152
+ state.resilience.retryCountByScope[rowScope] = (state.resilience.retryCountByScope[rowScope] ?? 0) + 1;
153
+
154
+ const pendingSegments = countPendingSegments(state, taskId);
155
+ recordTaskTransition({
156
+ projectRoot,
157
+ state,
158
+ journalType: "task.retry_requested",
159
+ journalPayload: {
160
+ taskId,
161
+ rowId,
162
+ previousClassification: reset.previousClassification,
163
+ pendingSegments,
164
+ retriedRowIds: [rowId],
165
+ },
166
+ });
167
+
168
+ if (unblocked) {
169
+ recordTaskTransition({
170
+ projectRoot,
171
+ state,
172
+ journalType: "batch.retry_unblocked",
173
+ journalPayload: {
174
+ taskId,
175
+ rowId,
176
+ pendingSegments,
177
+ fromPhase: phase,
178
+ },
179
+ });
180
+ }
181
+
182
+ const resumeHint = unblocked ? "spine batch resume" : "spine batch resume --force";
183
+
184
+ return {
185
+ ok: true,
186
+ exitCode: 0,
187
+ batchId: state.batchId,
188
+ taskId,
189
+ rowId,
190
+ pendingSegments,
191
+ unblocked,
192
+ output: `Row ${taskId}[${rowId}] reset for retry (pendingSegments=${pendingSegments}); sibling rows keep their status.\n → ${resumeHint}\n`,
193
+ };
194
+ }
195
+
196
+ /**
197
+ * Row-scoped matrix cancel (#230): `spine batch skip SP-X[rowId]` marks one row
198
+ * `canceled`. Canceled rows do not execute on resume and are excluded from the
199
+ * parent aggregation (the all-rows-must-succeed default now covers only the
200
+ * remaining rows). Cancel the whole matrix with `spine batch skip SP-X`.
201
+ *
202
+ * @param {object} params
203
+ * @param {string} params.projectRoot
204
+ * @param {string} params.taskId Parent matrix task id.
205
+ * @param {string} params.rowId Row id inside `task.matrixRows`.
206
+ */
207
+ export function skipTaskRow({ projectRoot, taskId, rowId }) {
208
+ const loadedBatch = loadMutableBatch(projectRoot);
209
+ if (!loadedBatch.ok) return loadedBatch.result;
210
+ const state = loadedBatch.state;
211
+ const phase = String(state.phase ?? "");
212
+
213
+ const guard = guardPhaseForMutation({ phase, operation: "skip" });
214
+ if (!guard.ok) {
215
+ return {
216
+ ok: false,
217
+ exitCode: 1,
218
+ error: guard.error,
219
+ output: guard.output,
220
+ batchId: state.batchId,
221
+ phase,
222
+ };
223
+ }
224
+
225
+ const validation = validateBatchState(state);
226
+ if (!validation.ok) {
227
+ return {
228
+ ok: false,
229
+ exitCode: 1,
230
+ error: "invalid_batch_state",
231
+ output: `Batch state validation failed:\n ${validation.errors.join("\n ")}\n`,
232
+ batchId: state.batchId,
233
+ };
234
+ }
235
+
236
+ const task = findTask(state, taskId);
237
+ if (!task) {
238
+ return {
239
+ ok: false,
240
+ exitCode: 1,
241
+ error: "task_not_found",
242
+ output: `Task ${taskId} not found in batch ${state.batchId}.\n`,
243
+ batchId: state.batchId,
244
+ };
245
+ }
246
+
247
+ const rows = Array.isArray(task.matrixRows) ? task.matrixRows : [];
248
+ if (rows.length === 0) {
249
+ return {
250
+ ok: false,
251
+ exitCode: 1,
252
+ error: "not_a_matrix_task",
253
+ output: `Task ${taskId} has no matrix rows — skip the whole task with \`spine batch skip ${taskId}\`.\n`,
254
+ batchId: state.batchId,
255
+ taskId,
256
+ };
257
+ }
258
+
259
+ const row = rows.find((entry) => entry && typeof entry === "object" && entry.rowId === rowId);
260
+ if (!row) {
261
+ return {
262
+ ok: false,
263
+ exitCode: 1,
264
+ error: "row_not_found",
265
+ output: `Row ${taskId}[${rowId}] not found. Matrix rows: ${rows
266
+ .map((entry) => entry?.rowId)
267
+ .join(", ")}\n`,
268
+ batchId: state.batchId,
269
+ taskId,
270
+ };
271
+ }
272
+
273
+ const previousStatus = String(row.status ?? "pending");
274
+ if (previousStatus === "succeeded") {
275
+ return {
276
+ ok: false,
277
+ exitCode: 1,
278
+ error: "row_not_cancellable",
279
+ output: `Row ${taskId}[${rowId}] already succeeded — cannot cancel a succeeded row.\n`,
280
+ batchId: state.batchId,
281
+ taskId,
282
+ };
283
+ }
284
+ if (previousStatus === "canceled") {
285
+ return {
286
+ ok: false,
287
+ exitCode: 1,
288
+ error: "row_not_cancellable",
289
+ output: `Row ${taskId}[${rowId}] is already canceled.\n`,
290
+ batchId: state.batchId,
291
+ taskId,
292
+ };
293
+ }
294
+
295
+ row.status = "canceled";
296
+ row.exitCode = null;
297
+ row.endedAt = Date.now();
298
+
299
+ recordTaskTransition({
300
+ projectRoot,
301
+ state,
302
+ journalType: "matrix.row_skipped",
303
+ journalPayload: {
304
+ taskId,
305
+ rowId,
306
+ previousStatus,
307
+ },
308
+ });
309
+
310
+ const resumeHint = phase === "failed" ? "spine batch resume --force" : "spine batch resume";
311
+ let output = `Row ${taskId}[${rowId}] canceled (was ${previousStatus}). It will not execute on resume and is excluded from matrix aggregation.\n`;
312
+ const allResolved = rows.every(
313
+ (entry) => entry && typeof entry === "object" && (entry.status === "succeeded" || entry.status === "canceled"),
314
+ );
315
+ if (allResolved) {
316
+ output += ` All rows are now succeeded or canceled — retry the task to land carried-over rows.\n → spine batch retry ${taskId}\n`;
317
+ }
318
+ output += ` → ${resumeHint}\n`;
319
+
320
+ return {
321
+ ok: true,
322
+ exitCode: 0,
323
+ batchId: state.batchId,
324
+ taskId,
325
+ rowId,
326
+ output,
327
+ };
328
+ }