pi-spine 2.9.0 → 2.10.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.9.0",
3
+ "version": "2.10.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -5,7 +5,7 @@
5
5
 
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
- import { spawnSync } from "node:child_process";
8
+ import { spawnSync, execFileSync } from "node:child_process";
9
9
  import micromatch from "micromatch";
10
10
  import { parseAggregateLineCoverage } from "../../scripts/coverage-parse.mjs";
11
11
  import {
@@ -309,7 +309,17 @@ export function verifyContract(worktreePath, parsedContract, config = {}) {
309
309
  const checks = [];
310
310
  const baseBranch = config?.baseBranch ?? "main";
311
311
  const sinceCommit = config?.sinceCommit ?? config?.taskStartCommit ?? undefined;
312
- const changedFiles = listChangedFiles(worktreePath, baseBranch, sinceCommit);
312
+ const committedFiles = listChangedFiles(worktreePath, baseBranch, sinceCommit);
313
+
314
+ let indexAndWorktreeFiles = [];
315
+ try {
316
+ const stdout = execFileSync("git", ["diff", "--name-only", "HEAD"], { cwd: worktreePath, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] });
317
+ indexAndWorktreeFiles = stdout.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
318
+ } catch {
319
+ // Ignore git diff failures; fall back to committedFiles only.
320
+ }
321
+
322
+ const changedFiles = [...new Set([...committedFiles, ...indexAndWorktreeFiles])];
313
323
 
314
324
  prepareContractVerifyEnvironment(worktreePath, parsedContract, config);
315
325
 
@@ -11,6 +11,7 @@ import {
11
11
  isBaseScopeSatisfied,
12
12
  isStubPrelandedFileScopeSatisfied,
13
13
  } from "./contract-prelanded.mjs";
14
+ import { substituteMatrixVariables } from "../planner/matrix.mjs";
14
15
 
15
16
  /**
16
17
  * @param {string} taskId
@@ -241,3 +242,57 @@ export function verifyStubFileScopeMustChange(
241
242
  }
242
243
  return { ok: failures.length === 0, failures };
243
244
  }
245
+
246
+ /**
247
+ * Substitute `{matrix.<column>}` placeholders in a single scalar contract field.
248
+ * @param {string | null | undefined} value
249
+ * @param {Record<string, string>} row
250
+ * @returns {string | null | undefined}
251
+ */
252
+ function substituteContractScalar(value, row) {
253
+ return value == null ? value : substituteMatrixVariables(value, row);
254
+ }
255
+
256
+ /**
257
+ * Substitute `{matrix.<column>}` placeholders across each path in a contract list field.
258
+ * @param {string[] | null | undefined} values
259
+ * @param {Record<string, string>} row
260
+ * @returns {string[] | null | undefined}
261
+ */
262
+ function substituteContractList(values, row) {
263
+ if (!Array.isArray(values)) {
264
+ return values;
265
+ }
266
+ return values.map((pattern) => substituteMatrixVariables(pattern, row));
267
+ }
268
+
269
+ /**
270
+ * Apply a matrix row to a parsed contract, substituting `{matrix.<column>}`
271
+ * placeholders in `testCommand`, `runCommand`, `fileScopeMustChange`,
272
+ * `fileScopeMustNotChange`, and `artifactsMustExist`. Numeric and boolean fields
273
+ * (`minLineCoverage`, `stallTimeoutMinutes`, `extendGraceOnFileScope`) are passed
274
+ * through unchanged.
275
+ *
276
+ * Returns a new parsed contract object; the input is returned unchanged when no
277
+ * row is supplied so non-matrix tasks keep their parsed contract verbatim. Throws
278
+ * on unknown `{matrix.X}` references (fail-loud) — `substituteMatrixVariables` owns
279
+ * the validation.
280
+ *
281
+ * @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
282
+ * @param {Record<string, string> | null | undefined} row Matrix row values keyed by column.
283
+ * @returns {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>}
284
+ */
285
+ export function applyMatrixRowToContract(parsedContract, row) {
286
+ if (!parsedContract || !row || Object.keys(row).length === 0) {
287
+ return parsedContract;
288
+ }
289
+
290
+ return {
291
+ ...parsedContract,
292
+ testCommand: substituteContractScalar(parsedContract.testCommand, row),
293
+ runCommand: substituteContractScalar(parsedContract.runCommand, row),
294
+ fileScopeMustChange: substituteContractList(parsedContract.fileScopeMustChange, row),
295
+ fileScopeMustNotChange: substituteContractList(parsedContract.fileScopeMustNotChange, row),
296
+ artifactsMustExist: substituteContractList(parsedContract.artifactsMustExist, row),
297
+ };
298
+ }
@@ -23,8 +23,13 @@ export {
23
23
  shouldRunContractVerify,
24
24
  shouldRunContractVerifyForWorker,
25
25
  verifyStubFileScopeMustChange,
26
+ applyMatrixRowToContract,
26
27
  } from "./contract-parse.mjs";
27
28
 
29
+ import { verifyContract as _verifyContract } from "./contract-exec.mjs";
30
+ import { stageUntrackedScopeFiles } from "./lane-dirty-check-git.mjs";
31
+ import { applyMatrixRowToContract } from "./contract-parse.mjs";
32
+
28
33
  export {
29
34
  CONTRACT_TEST_COMMAND_MAX_BUFFER,
30
35
  CONTRACT_TEST_DEFAULT_RETRIES,
@@ -34,6 +39,41 @@ export {
34
39
  isRefusedNpmTestDashDashCommand,
35
40
  prepareContractVerifyEnvironment,
36
41
  runContractTestCommand,
37
- verifyContract,
38
42
  writeContractFailureLog,
39
43
  } from "./contract-exec.mjs";
44
+
45
+ /**
46
+ * Verify contract and auto-stage untracked scope files before verification.
47
+ *
48
+ * When `config.matrixRow` is supplied (a matrix sub-lane), `{matrix.<column>}`
49
+ * placeholders in `testCommand`, `fileScopeMustChange`, and other string/list
50
+ * contract fields are substituted with the row values before staging and
51
+ * verification. Omit `config.matrixRow` for non-matrix tasks — the parsed
52
+ * contract is used verbatim, preserving existing behavior.
53
+ *
54
+ * @param {string} worktreePath
55
+ * @param {object} parsedContract
56
+ * @param {object} [config]
57
+ */
58
+ export function verifyContract(worktreePath, parsedContract, config = {}) {
59
+ const effectiveContract = config?.matrixRow
60
+ ? applyMatrixRowToContract(parsedContract, config.matrixRow)
61
+ : parsedContract;
62
+
63
+ const stageResult = stageUntrackedScopeFiles(worktreePath, effectiveContract.fileScopeMustChange || []);
64
+
65
+ if (stageResult.error) {
66
+ return {
67
+ ok: false,
68
+ checks: [
69
+ {
70
+ field: "fileScopeMustChange",
71
+ ok: false,
72
+ message: `Failed to auto-stage untracked scope files: ${stageResult.error}`,
73
+ },
74
+ ],
75
+ };
76
+ }
77
+
78
+ return _verifyContract(worktreePath, effectiveContract, config);
79
+ }
@@ -0,0 +1,532 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Matrix task / sub-lane runners (SP-671 / #217).
4
+ *
5
+ * Kept out of `engine-lanes.mjs` so the facade stays under the Phase 23 500 LOC cap.
6
+ */
7
+
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import {
11
+ aggregateMatrixOutcomes,
12
+ provisionMatrixSubLaneWorktree,
13
+ recordMatrixEvent,
14
+ removeMatrixSubLaneWorktree,
15
+ runConcurrent,
16
+ runShellInDir,
17
+ substituteRowCommand,
18
+ } from "./matrix.mjs";
19
+ import { commitLaneAndValidateWorktree } from "./commit.mjs";
20
+ import { recordLaneTaskMetric } from "./queue.mjs";
21
+ import { appendJournalEvent } from "../journal.mjs";
22
+ import { saveEngineBatchState } from "../pause.mjs";
23
+ import {
24
+ recordTaskSucceeded,
25
+ recordTaskTransition,
26
+ recomputeTaskCounters,
27
+ updateSegmentForTask,
28
+ } from "../state.mjs";
29
+ import { runWorker } from "../worker-host.mjs";
30
+ import { resolveWorktreeSetupIgnorePaths } from "../../config/spine-config-load.mjs";
31
+ import { parseContract } from "../../tasks/packet/parse-prompt.mjs";
32
+ import { verifyContract } from "../contract-verify.mjs";
33
+ import { gitExec } from "../git-exec.mjs";
34
+
35
+ /**
36
+ * Read the `## Contract` table from a parent task folder (un-substituted).
37
+ *
38
+ * @param {string} parentTaskFolderAbs
39
+ * @returns {object|null}
40
+ */
41
+ export function readParentContract(parentTaskFolderAbs) {
42
+ const promptPath = path.join(parentTaskFolderAbs, "PROMPT.md");
43
+ if (!fs.existsSync(promptPath)) return null;
44
+ return parseContract(fs.readFileSync(promptPath, "utf-8"));
45
+ }
46
+
47
+ /**
48
+ * Execute a single matrix row in its own worktree. Substitutes `{matrix.X}`
49
+ * placeholders for execution-only rows; LLM rows delegate to `runWorker`.
50
+ * Commits successful row output to the row branch.
51
+ *
52
+ * @param {object} params
53
+ * @returns {Promise<{ rowId: string, ok: boolean, exitCode: number, output: string, worktreePath?: string, branch?: string, commitSha?: string }>}
54
+ */
55
+ export async function runMatrixSubLane({
56
+ projectRoot,
57
+ batchId,
58
+ laneNumber,
59
+ taskId,
60
+ laneBranch,
61
+ laneCorrelationId,
62
+ row,
63
+ matrixType,
64
+ parentTaskFolderAbs,
65
+ taskFolderRel,
66
+ config,
67
+ baseBranch,
68
+ }) {
69
+ const rowId = row.rowId;
70
+ const values = row.values;
71
+ let worktreePath;
72
+ let branch;
73
+
74
+ try {
75
+ const provisioned = provisionMatrixSubLaneWorktree({
76
+ projectRoot,
77
+ batchId,
78
+ laneNumber,
79
+ parentTaskId: taskId,
80
+ rowId,
81
+ baseRef: laneBranch,
82
+ });
83
+ worktreePath = provisioned.worktreePath;
84
+ branch = provisioned.branch;
85
+ } catch (err) {
86
+ const message = err instanceof Error ? err.message : String(err);
87
+ recordMatrixEvent(projectRoot, batchId, "matrix.sub_lane.failed", {
88
+ taskId,
89
+ laneNumber,
90
+ rowId,
91
+ correlationId: laneCorrelationId,
92
+ error: message,
93
+ });
94
+ return { rowId, ok: false, exitCode: 1, output: `worktree provision failed: ${message}` };
95
+ }
96
+
97
+ recordMatrixEvent(projectRoot, batchId, "matrix.sub_lane.started", {
98
+ taskId,
99
+ laneNumber,
100
+ rowId,
101
+ correlationId: laneCorrelationId,
102
+ branch,
103
+ worktreePath,
104
+ });
105
+
106
+ /** @type {{ rowId: string, ok: boolean, exitCode: number, output: string, worktreePath?: string, branch?: string }} */
107
+ let result;
108
+
109
+ if (matrixType === "execute") {
110
+ const contract = readParentContract(parentTaskFolderAbs);
111
+ const rawCommand = contract?.runCommand || contract?.testCommand;
112
+ if (!rawCommand) {
113
+ result = {
114
+ rowId,
115
+ ok: false,
116
+ exitCode: 1,
117
+ output: "No runCommand or testCommand for execute matrix row",
118
+ worktreePath,
119
+ branch,
120
+ };
121
+ } else {
122
+ const command = substituteRowCommand(rawCommand, values);
123
+ const run = await runShellInDir(worktreePath, command);
124
+ if (run.exitCode !== 0) {
125
+ result = {
126
+ rowId,
127
+ ok: false,
128
+ exitCode: run.exitCode,
129
+ output: run.output,
130
+ worktreePath,
131
+ branch,
132
+ };
133
+ } else {
134
+ // Commit row output first so per-row contract verification (which diffs
135
+ // committed files against baseBranch) sees the row's output, then verify.
136
+ let commitError = null;
137
+ try {
138
+ const dirty = gitExec(worktreePath, ["status", "--porcelain"], {
139
+ throwOnError: false,
140
+ projectRoot,
141
+ });
142
+ if (dirty) {
143
+ gitExec(worktreePath, ["add", "-A"], { projectRoot });
144
+ gitExec(
145
+ worktreePath,
146
+ ["commit", "-m", `feat(${taskId}[${rowId}]): matrix row`],
147
+ { projectRoot },
148
+ );
149
+ }
150
+ } catch (err) {
151
+ commitError = err instanceof Error ? err.message : String(err);
152
+ }
153
+ if (commitError) {
154
+ result = {
155
+ rowId,
156
+ ok: false,
157
+ exitCode: 1,
158
+ output: `${run.output}\nmatrix row commit failed: ${commitError}`,
159
+ worktreePath,
160
+ branch,
161
+ };
162
+ } else {
163
+ // Verify the contract per row (testCommand + fileScopeMustChange
164
+ // substituted with this row's values). This is the per-row gate.
165
+ const verify = verifyContract(worktreePath, contract, {
166
+ matrixRow: values,
167
+ baseBranch,
168
+ });
169
+ if (verify.ok) {
170
+ result = {
171
+ rowId,
172
+ ok: true,
173
+ exitCode: 0,
174
+ output: run.output,
175
+ worktreePath,
176
+ branch,
177
+ };
178
+ } else {
179
+ const failing = (verify.checks || [])
180
+ .filter((check) => !check.ok)
181
+ .map((check) => check.message)
182
+ .join("; ");
183
+ result = {
184
+ rowId,
185
+ ok: false,
186
+ exitCode: 1,
187
+ output: `${run.output}\ncontract verify failed: ${failing}`,
188
+ worktreePath,
189
+ branch,
190
+ };
191
+ }
192
+ }
193
+ }
194
+ }
195
+ } else {
196
+ // LLM rows delegate to the worker in the row worktree. Per-row agent-prompt
197
+ // substitution is handled by SP-670 helpers at the worker boundary; full
198
+ // worker-side substitution wiring is tracked for SP-673.
199
+ const workerResult = await runWorker({
200
+ worktreePath,
201
+ taskFolder: path.join(worktreePath, taskFolderRel),
202
+ projectRoot,
203
+ batchId,
204
+ laneNumber,
205
+ taskId,
206
+ laneBranch: branch,
207
+ laneCorrelationId: `${laneCorrelationId}-matrix-${rowId}`,
208
+ fileScopePaths: [],
209
+ config,
210
+ });
211
+ result = {
212
+ rowId,
213
+ ok: Boolean(workerResult.ok),
214
+ exitCode: workerResult.exitCode ?? 0,
215
+ output: workerResult.output ?? "",
216
+ worktreePath,
217
+ branch,
218
+ };
219
+ }
220
+
221
+ if (result.ok) {
222
+ try {
223
+ const dirty = gitExec(worktreePath, ["status", "--porcelain"], {
224
+ throwOnError: false,
225
+ projectRoot,
226
+ });
227
+ if (dirty) {
228
+ gitExec(worktreePath, ["add", "-A"], { projectRoot });
229
+ gitExec(
230
+ worktreePath,
231
+ ["commit", "-m", `feat(${taskId}[${rowId}]): matrix row`],
232
+ { projectRoot },
233
+ );
234
+ }
235
+ const sha = gitExec(worktreePath, ["rev-parse", "HEAD"], { projectRoot });
236
+ result.commitSha = sha;
237
+ recordMatrixEvent(projectRoot, batchId, "matrix.sub_lane.completed", {
238
+ taskId,
239
+ laneNumber,
240
+ rowId,
241
+ correlationId: laneCorrelationId,
242
+ commitSha: sha,
243
+ });
244
+ } catch (err) {
245
+ const message = err instanceof Error ? err.message : String(err);
246
+ result.ok = false;
247
+ result.exitCode = 1;
248
+ result.output = `${result.output}\nmatrix row commit failed: ${message}`;
249
+ recordMatrixEvent(projectRoot, batchId, "matrix.sub_lane.failed", {
250
+ taskId,
251
+ laneNumber,
252
+ rowId,
253
+ correlationId: laneCorrelationId,
254
+ error: message,
255
+ });
256
+ }
257
+ } else {
258
+ recordMatrixEvent(projectRoot, batchId, "matrix.sub_lane.failed", {
259
+ taskId,
260
+ laneNumber,
261
+ rowId,
262
+ correlationId: laneCorrelationId,
263
+ exitCode: result.exitCode,
264
+ output: (result.output || "").slice(0, 2000),
265
+ });
266
+ }
267
+
268
+ return result;
269
+ }
270
+
271
+ /**
272
+ * Run every matrix row of a task as a parallel sub-lane (SP-671).
273
+ *
274
+ * Each row runs in its own worktree off the lane task branch. The parent task
275
+ * succeeds only when every row succeeds; any failure fails the task and
276
+ * surfaces the failing row id(s). Successful row branches are merged back into
277
+ * the lane worktree so the normal lane-commit + wave-merge carry all rows'
278
+ * output. Concurrency is bounded by `maxParallel`.
279
+ *
280
+ * @param {object} params
281
+ */
282
+ export async function runMatrixTaskOnLane({
283
+ projectRoot,
284
+ state,
285
+ batchId,
286
+ baseBranch,
287
+ config,
288
+ task,
289
+ lane,
290
+ taskFolderRel,
291
+ laneCorrelationId,
292
+ fileScopePaths,
293
+ matrix,
294
+ maxParallel,
295
+ }) {
296
+ const taskId = task.taskId;
297
+ const laneNumber = lane.laneNumber;
298
+ const laneBranch = lane.branch;
299
+ const wt = lane.worktreePath;
300
+ const taskFolderInWorktree = path.join(wt, taskFolderRel);
301
+ const parentTaskFolderAbs = path.join(projectRoot, taskFolderRel);
302
+
303
+ task.status = "running";
304
+ task.isMatrix = true;
305
+ task.matrixType = matrix.type;
306
+ if (!task.startedAt) task.startedAt = Date.now();
307
+ task.matrixRows = matrix.rows.map((row) => ({
308
+ rowId: row.rowId,
309
+ status: "pending",
310
+ exitCode: null,
311
+ commitSha: null,
312
+ }));
313
+ updateSegmentForTask(state, taskId, "running");
314
+ saveEngineBatchState(projectRoot, state);
315
+
316
+ appendJournalEvent(projectRoot, batchId, "task.started", {
317
+ taskId,
318
+ laneNumber,
319
+ laneId: lane.laneId,
320
+ correlationId: laneCorrelationId,
321
+ matrix: true,
322
+ });
323
+ recordMatrixEvent(projectRoot, batchId, "matrix.task_started", {
324
+ taskId,
325
+ laneNumber,
326
+ laneId: lane.laneId,
327
+ correlationId: laneCorrelationId,
328
+ rowIds: matrix.rows.map((row) => row.rowId),
329
+ matrixType: matrix.type,
330
+ maxParallel,
331
+ });
332
+
333
+ const { results } = await runConcurrent(matrix.rows, maxParallel, async (row) => {
334
+ try {
335
+ return await runMatrixSubLane({
336
+ projectRoot,
337
+ batchId,
338
+ laneNumber,
339
+ taskId,
340
+ laneBranch,
341
+ laneCorrelationId,
342
+ row,
343
+ matrixType: matrix.type,
344
+ parentTaskFolderAbs,
345
+ taskFolderRel,
346
+ config,
347
+ baseBranch,
348
+ });
349
+ } catch (err) {
350
+ // Defensive: a crashed sub-lane must never lose its row identity, or the
351
+ // parent could aggregate a phantom pending row.
352
+ const message = err instanceof Error ? err.message : String(err);
353
+ recordMatrixEvent(projectRoot, batchId, "matrix.sub_lane.failed", {
354
+ taskId,
355
+ laneNumber,
356
+ rowId: row.rowId,
357
+ correlationId: laneCorrelationId,
358
+ error: `sub-lane crashed: ${message}`,
359
+ });
360
+ return {
361
+ rowId: row.rowId,
362
+ ok: false,
363
+ exitCode: 1,
364
+ output: `sub-lane crashed: ${message}`,
365
+ };
366
+ }
367
+ });
368
+
369
+ for (const rowResult of results) {
370
+ const entry = task.matrixRows.find((m) => m.rowId === rowResult.rowId);
371
+ if (entry) {
372
+ entry.status = rowResult.ok ? "succeeded" : "failed";
373
+ entry.exitCode = rowResult.exitCode ?? null;
374
+ entry.commitSha = rowResult.commitSha ?? null;
375
+ }
376
+ }
377
+
378
+ const { ok, failedRowIds } = aggregateMatrixOutcomes(
379
+ results.map((rowResult) => ({ rowId: rowResult.rowId, ok: rowResult.ok })),
380
+ );
381
+
382
+ if (!ok) {
383
+ for (const rowResult of results) {
384
+ if (rowResult.worktreePath) {
385
+ removeMatrixSubLaneWorktree(
386
+ projectRoot,
387
+ rowResult.worktreePath,
388
+ rowResult.branch,
389
+ );
390
+ }
391
+ }
392
+ const failedSummary = failedRowIds.join(", ");
393
+ task.status = "failed";
394
+ task.endedAt = Date.now();
395
+ task.exitReason = `matrix_sub_lane_failed:${failedSummary}`;
396
+ updateSegmentForTask(state, taskId, "failed");
397
+ recomputeTaskCounters(state);
398
+ saveEngineBatchState(projectRoot, state);
399
+ recordMatrixEvent(projectRoot, batchId, "matrix.task_failed", {
400
+ taskId,
401
+ laneNumber,
402
+ laneId: lane.laneId,
403
+ correlationId: laneCorrelationId,
404
+ failedRowIds,
405
+ matrixRows: task.matrixRows,
406
+ });
407
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
408
+ taskId,
409
+ laneNumber,
410
+ laneId: lane.laneId,
411
+ correlationId: laneCorrelationId,
412
+ classification: "matrix_sub_lane_failed",
413
+ exitCode: 1,
414
+ output: `Matrix sub-lane(s) failed: ${failedSummary}`,
415
+ failedRowIds,
416
+ });
417
+ recordLaneTaskMetric({
418
+ projectRoot,
419
+ batchId,
420
+ task,
421
+ config,
422
+ taskFolder: taskFolderInWorktree,
423
+ lane,
424
+ });
425
+ return {
426
+ ok: false,
427
+ aborted: false,
428
+ workerResult: {
429
+ ok: false,
430
+ classification: "matrix_sub_lane_failed",
431
+ exitCode: 1,
432
+ output: `Matrix sub-lane(s) failed: ${failedSummary}`,
433
+ },
434
+ };
435
+ }
436
+
437
+ // All rows succeeded: merge each row branch into the lane worktree so the
438
+ // lane carries every row's output, then run the standard lane commit.
439
+ for (const rowResult of results) {
440
+ if (!rowResult.branch) continue;
441
+ try {
442
+ gitExec(
443
+ wt,
444
+ ["merge", "--no-edit", "-m", `merge matrix row ${rowResult.rowId} into lane`, rowResult.branch],
445
+ { projectRoot },
446
+ );
447
+ } catch (err) {
448
+ const message = err instanceof Error ? err.message : String(err);
449
+ gitExec(wt, ["merge", "--abort"], { throwOnError: false, projectRoot });
450
+ for (const other of results) {
451
+ if (other.worktreePath) {
452
+ removeMatrixSubLaneWorktree(projectRoot, other.worktreePath, other.branch);
453
+ }
454
+ }
455
+ task.status = "failed";
456
+ task.endedAt = Date.now();
457
+ task.exitReason = `matrix_row_merge_failed:${rowResult.rowId}`;
458
+ updateSegmentForTask(state, taskId, "failed");
459
+ recomputeTaskCounters(state);
460
+ saveEngineBatchState(projectRoot, state);
461
+ return {
462
+ ok: false,
463
+ workerResult: {
464
+ ok: false,
465
+ classification: "matrix_row_merge_failed",
466
+ exitCode: 1,
467
+ output: `Failed to merge matrix row ${rowResult.rowId}: ${message}`,
468
+ },
469
+ };
470
+ }
471
+ removeMatrixSubLaneWorktree(projectRoot, rowResult.worktreePath, rowResult.branch);
472
+ }
473
+
474
+ // Mirror the execution-only convention: a `.DONE` marker authorizes commit.
475
+ const donePath = path.join(taskFolderInWorktree, ".DONE");
476
+ fs.mkdirSync(path.dirname(donePath), { recursive: true });
477
+ fs.writeFileSync(donePath, "");
478
+
479
+ recordMatrixEvent(projectRoot, batchId, "matrix.task_completed", {
480
+ taskId,
481
+ laneNumber,
482
+ laneId: lane.laneId,
483
+ correlationId: laneCorrelationId,
484
+ rowIds: results.map((rowResult) => rowResult.rowId),
485
+ });
486
+
487
+ const ignorePatterns = resolveWorktreeSetupIgnorePaths(config);
488
+ const commitResult = commitLaneAndValidateWorktree({
489
+ worktreePath: wt,
490
+ taskBranch: laneBranch,
491
+ taskId,
492
+ batchId,
493
+ taskFolder: taskFolderInWorktree,
494
+ projectRoot,
495
+ fileScopePaths,
496
+ ignorePatterns,
497
+ task,
498
+ lane,
499
+ laneNumber,
500
+ laneCorrelationId,
501
+ state,
502
+ config,
503
+ });
504
+ if (!commitResult.ok) {
505
+ return { ok: false, error: commitResult.error, output: commitResult.output };
506
+ }
507
+
508
+ recordTaskSucceeded(state, taskId, { exitReason: "done", doneFileFound: true });
509
+ recordTaskTransition({
510
+ projectRoot,
511
+ state,
512
+ journalType: "task.completed",
513
+ journalPayload: {
514
+ taskId,
515
+ laneNumber,
516
+ laneId: lane.laneId,
517
+ correlationId: laneCorrelationId,
518
+ matrix: true,
519
+ matrixRows: task.matrixRows,
520
+ },
521
+ });
522
+ recordLaneTaskMetric({
523
+ projectRoot,
524
+ batchId,
525
+ task,
526
+ config,
527
+ taskFolder: taskFolderInWorktree,
528
+ lane,
529
+ });
530
+
531
+ return { ok: true, laneCommit: commitResult.laneCommit };
532
+ }