pi-spine 2.18.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.
@@ -255,19 +255,50 @@ export function removeMatrixSubLaneWorktree(projectRoot, worktreePath, branch) {
255
255
  }
256
256
  }
257
257
 
258
+ /**
259
+ * Matrix row index environment (#229). Gives row scripts Slurm/K8s-style
260
+ * identity without string substitution: `SPINE_MATRIX_JOB_ID` is the parent
261
+ * task id, `SPINE_MATRIX_TASK_ID` the row id, `SPINE_MATRIX_TASK_INDEX` the
262
+ * 0-based row position, `SPINE_MATRIX_TASK_COUNT` the row count, and
263
+ * `JOB_COMPLETION_INDEX` aliases the index for Kubernetes indexed-job scripts.
264
+ *
265
+ * Returns null when `rowIndex`/`rowCount` are absent so callers that do not
266
+ * know a row's position (legacy direct calls) inject nothing at all.
267
+ *
268
+ * @param {object} params
269
+ * @param {string} [params.taskId] Parent matrix task id.
270
+ * @param {string} [params.rowId] Row id (`run_id` or derived).
271
+ * @param {number} [params.rowIndex] 0-based position of the row in the matrix.
272
+ * @param {number} [params.rowCount] Total number of matrix rows.
273
+ * @returns {Record<string, string> | null}
274
+ */
275
+ export function buildMatrixRowEnv({ taskId, rowId, rowIndex, rowCount }) {
276
+ if (!Number.isInteger(rowIndex) || rowIndex < 0) return null;
277
+ if (!Number.isInteger(rowCount) || rowCount < 0) return null;
278
+ return {
279
+ SPINE_MATRIX_JOB_ID: String(taskId ?? ""),
280
+ SPINE_MATRIX_TASK_ID: String(rowId ?? ""),
281
+ SPINE_MATRIX_TASK_INDEX: String(rowIndex),
282
+ SPINE_MATRIX_TASK_COUNT: String(rowCount),
283
+ JOB_COMPLETION_INDEX: String(rowIndex),
284
+ };
285
+ }
286
+
258
287
  /**
259
288
  * Run a shell command in a directory, resolving with exit code and combined output.
260
289
  * Uses async spawn so concurrent rows genuinely overlap (required for maxParallel).
261
290
  *
262
291
  * @param {string} cwd
263
292
  * @param {string} command
293
+ * @param {Record<string, string> | null} [extraEnv] Extra environment variables
294
+ * layered over `process.env` (matrix row identity, #229). Null injects nothing.
264
295
  * @returns {Promise<{ exitCode: number, output: string }>}
265
296
  */
266
- export function runShellInDir(cwd, command) {
297
+ export function runShellInDir(cwd, command, extraEnv = null) {
267
298
  return new Promise((resolve) => {
268
299
  const child = spawn("/bin/sh", ["-c", command], {
269
300
  cwd,
270
- env: process.env,
301
+ env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
271
302
  stdio: ["ignore", "pipe", "pipe"],
272
303
  });
273
304
  let output = "";
@@ -123,9 +123,10 @@ function recordRejectStreakReset(projectRoot, gate) {
123
123
  * @param {string} ctx.batchId
124
124
  * @param {"human" | "auto"} [ctx.decidedBy]
125
125
  * @param {GatePostureEvaluateResult | null} [ctx.postureEvaluation]
126
+ * @param {string} [ctx.synthesis] Optional operator readback note (SP-747 / #280); omitted stays absent.
126
127
  */
127
128
  export function approveIntegrateGate(ctx) {
128
- const { projectRoot, batchId, decidedBy = "human", postureEvaluation = null } = ctx;
129
+ const { projectRoot, batchId, decidedBy = "human", postureEvaluation = null, synthesis } = ctx;
129
130
  const gate = loadGateRecord(projectRoot, batchId);
130
131
 
131
132
  if (!gate) {
@@ -161,6 +162,11 @@ export function approveIntegrateGate(ctx) {
161
162
  gate.status = "approved";
162
163
  gate.decidedAt = new Date().toISOString();
163
164
  gate.decidedBy = actor;
165
+ // SP-747 / #280: persist the operator's synthesis readback when provided.
166
+ // Absent / empty flag leaves the field omitted (non-breaking null default);
167
+ // auto-approve never passes synthesis, so automated records stay without one.
168
+ const synthesisNote = typeof synthesis === "string" && synthesis.trim() !== "" ? synthesis : null;
169
+ if (synthesisNote) gate.synthesis = synthesisNote;
164
170
  saveGateRecord(projectRoot, gate);
165
171
  recordApprovalStreak(projectRoot, gate);
166
172
 
@@ -177,6 +183,9 @@ export function approveIntegrateGate(ctx) {
177
183
  journalPayload.postureReason = postureEvaluation.reason;
178
184
  journalPayload.postureTier = postureEvaluation.tier;
179
185
  }
186
+ if (synthesisNote) {
187
+ journalPayload.synthesis = synthesisNote;
188
+ }
180
189
 
181
190
  appendJournalEvent(projectRoot, batchId, "gate.approved", journalPayload);
182
191
 
@@ -288,9 +297,10 @@ export function maybeAutoApproveIntegrateGate(ctx) {
288
297
  * @param {string} ctx.projectRoot
289
298
  * @param {string} ctx.batchId
290
299
  * @param {string} [ctx.reason]
300
+ * @param {string} [ctx.synthesis] Optional operator readback note (SP-747 / #280).
291
301
  */
292
302
  export function rejectIntegrateGate(ctx) {
293
- const { projectRoot, batchId, reason } = ctx;
303
+ const { projectRoot, batchId, reason, synthesis } = ctx;
294
304
  const gate = loadGateRecord(projectRoot, batchId);
295
305
 
296
306
  if (!gate) {
@@ -322,6 +332,9 @@ export function rejectIntegrateGate(ctx) {
322
332
  gate.decidedAt = new Date().toISOString();
323
333
  gate.decidedBy = "human";
324
334
  if (reason) gate.rejectionReason = reason;
335
+ // SP-747 / #280: same optional readback contract as approve — omit when absent.
336
+ const synthesisNote = typeof synthesis === "string" && synthesis.trim() !== "" ? synthesis : null;
337
+ if (synthesisNote) gate.synthesis = synthesisNote;
325
338
  saveGateRecord(projectRoot, gate);
326
339
  recordRejectStreakReset(projectRoot, gate);
327
340
 
@@ -331,6 +344,7 @@ export function rejectIntegrateGate(ctx) {
331
344
  category: gate.category ?? null,
332
345
  status: gate.status,
333
346
  reason: reason ?? null,
347
+ ...(synthesisNote ? { synthesis: synthesisNote } : {}),
334
348
  decidedBy: "human",
335
349
  });
336
350
 
@@ -14,6 +14,7 @@ import {
14
14
  sanitizeGitignoredArtifactsBeforeLaneCommit,
15
15
  } from "./lane-dirty-check.mjs";
16
16
  import { gitExec } from "./git-exec.mjs";
17
+ import { deriveMatrixRowId } from "../planner/matrix.mjs";
17
18
  import { parseContract, parsePrompt } from "../tasks/packet/parse-prompt.mjs";
18
19
  import { substituteMatrixVariables } from "../planner/matrix.mjs";
19
20
  import {
@@ -229,6 +230,7 @@ function listPorcelainPaths(porcelain) {
229
230
  * @param {string} [params.baseBranch] Base branch for stub contract diff (default main)
230
231
  * @param {string[]} [params.ignorePatterns] Hook paths to skip (default includes `.venv`)
231
232
  * @param {string[]} [params.fileScopePaths] Task fileScope — paths here are never skipped
233
+ * @param {string[]} [params.canceledMatrixRowIds] Row ids canceled by the operator (#230) — their expanded fileScope patterns are excluded
232
234
  * @returns {{ ok: true, committed: boolean, commitSha?: string, skippedGitignoredPaths?: string[], skippedIgnorePaths?: string[] } | { ok: false, error: string, failureClass: string, gitignoredPaths?: string[] }}
233
235
  */
234
236
  export function commitLaneWorktree({
@@ -241,6 +243,7 @@ export function commitLaneWorktree({
241
243
  baseBranch = "main",
242
244
  ignorePatterns,
243
245
  fileScopePaths = [],
246
+ canceledMatrixRowIds = [],
244
247
  }) {
245
248
  const identityRoot = projectRoot ?? worktreePath;
246
249
  const effectiveIgnorePatterns = Array.isArray(ignorePatterns)
@@ -286,18 +289,30 @@ export function commitLaneWorktree({
286
289
  // Matrix tasks carry `{matrix.<column>}` placeholders in fileScopeMustChange.
287
290
  // Expand them across every matrix row so the stub check matches the
288
291
  // concrete per-row output paths the rows actually produced.
289
- const prompt = promptText ? parsePrompt(promptText) : null;
290
- const matrixRows = Array.isArray(prompt?.matrix) ? prompt.matrix : [];
291
- const effectiveContract =
292
- matrixRows.length > 0
293
- ? {
294
- ...parsedContract,
295
- fileScopeMustChange: expandMatrixFileScopePatterns(
296
- parsedContract.fileScopeMustChange,
297
- matrixRows,
298
- ),
299
- }
300
- : parsedContract;
292
+ const prompt = promptText ? parsePrompt(promptText) : null;
293
+ const matrixRows = Array.isArray(prompt?.matrix) ? prompt.matrix : [];
294
+ // Canceled rows (#230) are operator exclusions — they never execute and
295
+ // produce no output, so their expanded fileScopeMustChange patterns must
296
+ // not gate the lane commit.
297
+ const canceledRowIds = new Set(
298
+ Array.isArray(canceledMatrixRowIds) ? canceledMatrixRowIds : [],
299
+ );
300
+ const activeMatrixRows =
301
+ canceledRowIds.size === 0
302
+ ? matrixRows
303
+ : matrixRows.filter(
304
+ (row) => !canceledRowIds.has(deriveMatrixRowId(row, prompt?.matrixColumns ?? [])),
305
+ );
306
+ const effectiveContract =
307
+ matrixRows.length > 0
308
+ ? {
309
+ ...parsedContract,
310
+ fileScopeMustChange: expandMatrixFileScopePatterns(
311
+ parsedContract.fileScopeMustChange,
312
+ activeMatrixRows,
313
+ ),
314
+ }
315
+ : parsedContract;
301
316
  const scopeCheck = verifyStubFileScopeMustChange(
302
317
  worktreePath,
303
318
  effectiveContract,
@@ -72,6 +72,9 @@ function normalizeTasks(tasks) {
72
72
  /** @type {Record<string, unknown>} */
73
73
  const task = entry && typeof entry === "object" ? /** @type {Record<string, unknown>} */ (entry) : {};
74
74
  const status = String(task.status ?? "pending").toLowerCase();
75
+ // Matrix per-row state (#230): pass the row array through when present so
76
+ // `spine status --json` / diagnose surfaces per-row running/succeeded/failed.
77
+ const matrixRows = Array.isArray(task.matrixRows) ? task.matrixRows : null;
75
78
  return {
76
79
  taskId: String(task.taskId ?? task.id ?? ""),
77
80
  status,
@@ -81,6 +84,7 @@ function normalizeTasks(tasks) {
81
84
  startedAt: task.startedAt ?? null,
82
85
  endedAt: task.endedAt ?? null,
83
86
  classification: classifyStatus(status),
87
+ ...(matrixRows ? { matrixRows } : {}),
84
88
  };
85
89
  });
86
90
  }
@@ -18,6 +18,7 @@ import { saveSpineBatchState, updateSegmentForTask } from "./state.mjs";
18
18
  import { laneTaskBranch } from "./worktree.mjs";
19
19
  import { laneDoneMarkerCommittedOnBranch } from "./journal-rebuild.mjs";
20
20
  import { runWorker } from "./worker-host.mjs";
21
+ import { runMatrixTaskForResume } from "./engine-lanes/matrix-run.mjs";
21
22
  import { runLaneReviewPhasesBeforeCommit } from "./resume-lane-reviews.mjs";
22
23
 
23
24
  export { executeResumeWave } from "./resume-multi-queue.mjs";
@@ -252,6 +253,36 @@ export async function runResumedTaskOnLane({
252
253
  resumed: true,
253
254
  });
254
255
 
256
+ // Matrix tasks resume through runMatrixTaskOnLane (row fan-out, carry-over,
257
+ // lane commit, success recording) instead of a plain worker run (#230).
258
+ const matrixResume = await runMatrixTaskForResume({
259
+ projectRoot,
260
+ state,
261
+ batchId,
262
+ baseBranch: state.baseBranch ?? "main",
263
+ config,
264
+ task,
265
+ lane,
266
+ taskFolderRel,
267
+ laneCorrelationId,
268
+ fileScopePaths,
269
+ });
270
+ if (matrixResume.isMatrix) {
271
+ if (!matrixResume.ok) {
272
+ const classification = matrixResume.cliResult?.error ?? "matrix_failed";
273
+ appendJournalEvent(projectRoot, batchId, "lane.died", {
274
+ laneNumber,
275
+ laneId: lane.laneId,
276
+ taskId,
277
+ correlationId: laneCorrelationId,
278
+ reason: classification,
279
+ });
280
+ return { ok: false, aborted: false, workerResult: matrixResume.cliResult, taskId, laneNumber };
281
+ }
282
+ // The matrix runner already lane-committed, recorded success, and journaled.
283
+ return { ok: true, taskId, laneNumber };
284
+ }
285
+
255
286
  const workerResult = await runWorker({
256
287
  worktreePath: wt,
257
288
  taskFolder: taskFolderInWorktree,
@@ -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
  {