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.
@@ -10,7 +10,7 @@ import {
10
10
  resolveWorkerPiTimeoutMs,
11
11
  parseTaskSizeFromFolder,
12
12
  } from "./task-stall-budget.mjs";
13
- import { parseContract } from "../tasks/packet/parse-prompt.mjs";
13
+ import { parseContract, parsePrompt } from "../tasks/packet/parse-prompt.mjs";
14
14
  import { appendJournalEvent } from "./journal.mjs";
15
15
  import { assertReviewToolAvailable } from "./review.mjs";
16
16
  import { finalizeWorkerOutput, createWorkerLiveLogWriter } from "./worker-output.mjs";
@@ -22,6 +22,7 @@ import {
22
22
  resolveWorkerLaunchScript,
23
23
  resolveWorkerPhase,
24
24
  spawnWorkerHandle,
25
+ spawnExecutionOnlyHandle,
25
26
  terminateHungWorkerChild,
26
27
  CHILD_DONE_TIMEOUT_MS,
27
28
  } from "./worker-spawn.mjs";
@@ -203,32 +204,48 @@ export async function runWorker({
203
204
 
204
205
  const taskSize = parseTaskSizeFromFolder(taskFolder);
205
206
  const promptPath = path.join(taskFolder, "PROMPT.md");
206
- const contract = fs.existsSync(promptPath)
207
- ? parseContract(fs.readFileSync(promptPath, "utf-8"))
208
- : { stallTimeoutMinutes: null, extendGraceOnFileScope: null };
207
+ const promptText = fs.existsSync(promptPath) ? fs.readFileSync(promptPath, "utf-8") : "";
208
+ const parsedPrompt = promptText ? parsePrompt(promptText) : null;
209
+ const contract = promptText ? parseContract(promptText) : { stallTimeoutMinutes: null, extendGraceOnFileScope: null, runCommand: null, testCommand: null };
209
210
  const stallConfig = resolveStallConfigForTask({ config, taskSize, contract });
210
211
  const piTimeoutMs = resolveWorkerPiTimeoutMs({ config, taskSize, contract });
211
212
  const startedAt = Date.now();
212
213
 
213
- const child = spawnWorkerHandle({
214
- worktreePath,
215
- taskFolder,
216
- useStub,
217
- timeoutMs: piTimeoutMs,
218
- piTimeoutMs,
219
- projectRoot,
220
- batchId,
221
- laneNumber,
222
- taskId,
223
- laneCorrelationId,
224
- fileScopePaths,
225
- config,
226
- workerBackendDeps,
227
- });
214
+ const isExecute = parsedPrompt?.type === "execute";
215
+ const runCommand = contract.runCommand || contract.testCommand;
216
+
217
+ const child = isExecute
218
+ ? spawnExecutionOnlyHandle({
219
+ worktreePath,
220
+ taskFolder,
221
+ command: runCommand || "echo 'No runCommand or testCommand provided' && exit 1",
222
+ projectRoot,
223
+ batchId,
224
+ laneNumber,
225
+ taskId,
226
+ laneCorrelationId,
227
+ fileScopePaths,
228
+ config,
229
+ })
230
+ : spawnWorkerHandle({
231
+ worktreePath,
232
+ taskFolder,
233
+ useStub,
234
+ timeoutMs: piTimeoutMs,
235
+ piTimeoutMs,
236
+ projectRoot,
237
+ batchId,
238
+ laneNumber,
239
+ taskId,
240
+ laneCorrelationId,
241
+ fileScopePaths,
242
+ config,
243
+ workerBackendDeps,
244
+ });
228
245
  const workerChild = /** @type {WorkerChildHandle} */ (child);
229
- let childPastPreflight = !useLaunchScript;
246
+ let childPastPreflight = isExecute ? true : !useLaunchScript;
230
247
  /** @type {WorkerPhase} */
231
- const initialWorkerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
248
+ const initialWorkerPhase = isExecute ? "pi" : resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
232
249
  markChildPastPreflight(workerChild, () => {
233
250
  childPastPreflight = true;
234
251
  });
@@ -167,6 +167,55 @@ export function spawnWorkerChild({
167
167
  });
168
168
  }
169
169
 
170
+ /**
171
+ * @param {object} params
172
+ * @param {string} params.worktreePath
173
+ * @param {string} params.taskFolder
174
+ * @param {string} params.command
175
+ * @param {string} [params.projectRoot]
176
+ * @param {string} [params.batchId]
177
+ * @param {number} [params.laneNumber]
178
+ * @param {string} [params.taskId]
179
+ * @param {string} [params.laneCorrelationId]
180
+ * @param {string[]} [params.fileScopePaths]
181
+ * @param {object} [params.config]
182
+ */
183
+ export function spawnExecutionOnlyHandle({
184
+ worktreePath,
185
+ taskFolder,
186
+ command,
187
+ projectRoot,
188
+ batchId,
189
+ laneNumber,
190
+ taskId,
191
+ laneCorrelationId,
192
+ fileScopePaths = [],
193
+ config = {},
194
+ }) {
195
+ const env = buildWorkerChildEnv({
196
+ taskFolder,
197
+ worktreePath,
198
+ projectRoot,
199
+ batchId,
200
+ laneNumber,
201
+ taskId,
202
+ laneCorrelationId,
203
+ fileScopePaths,
204
+ config,
205
+ });
206
+
207
+ // Create a wrapper script that runs the command and then creates .DONE
208
+ // This matches the behavior expected by the heartbeat loop.
209
+ // We run `/bin/sh -c "<command> && touch .DONE"`
210
+ const script = `${command} && touch "${path.join(taskFolder, ".DONE")}"`;
211
+
212
+ return spawn("/bin/sh", ["-c", script], {
213
+ cwd: worktreePath,
214
+ env,
215
+ stdio: ["ignore", "pipe", "pipe"],
216
+ });
217
+ }
218
+
170
219
  /**
171
220
  * @param {WorkerChildHandle} child
172
221
  * @param {() => void} onPreflightComplete
@@ -2,6 +2,8 @@
2
2
  * FR-SCHED-03/04: greedy lane assignment subject to file-scope disjointness.
3
3
  */
4
4
 
5
+ import { deriveMatrixRowId } from './matrix.mjs';
6
+
5
7
  function normalizeFileScopePath(p) {
6
8
  let s = String(p ?? '').trim();
7
9
  if (!s) return null;
@@ -40,9 +42,36 @@ export function assignLanesToWaves({ waves, tasksById, maxParallel, queueExcess
40
42
  const planned = [];
41
43
 
42
44
  for (let waveIndex = 0; waveIndex < waves.length; waveIndex++) {
43
- const waveTaskIds = waves[waveIndex];
45
+ const rawWaveTaskIds = waves[waveIndex];
46
+ const waveTaskIds = [];
47
+
48
+ // Expand matrix tasks
49
+ for (const taskId of rawWaveTaskIds) {
50
+ const task = tasksById[taskId];
51
+ if (!task) {
52
+ throw new Error(`Missing task packet for ${taskId} during lane assignment`);
53
+ }
54
+
55
+ if (task.matrix && Array.isArray(task.matrix) && task.matrix.length > 0) {
56
+ for (const row of task.matrix) {
57
+ const rowId = deriveMatrixRowId(row, task.matrixColumns || []);
58
+ const subTaskId = `${taskId}[${rowId}]`;
59
+ waveTaskIds.push(subTaskId);
60
+ if (!tasksById[subTaskId]) {
61
+ tasksById[subTaskId] = {
62
+ ...task,
63
+ taskId: subTaskId,
64
+ matrixRow: row,
65
+ parentTaskId: taskId
66
+ };
67
+ }
68
+ }
69
+ } else {
70
+ waveTaskIds.push(taskId);
71
+ }
72
+ }
44
73
 
45
- /** @type {{ lanePaths: string[] }} */
74
+ /** @type {{ lanePaths: string[], taskIds: string[] }} */
46
75
  const virtualLanes = [];
47
76
 
48
77
  /** @type {Record<string, { virtualLane: number, tick: number, laneInTick: number }>} */
@@ -53,10 +82,7 @@ export function assignLanesToWaves({ waves, tasksById, maxParallel, queueExcess
53
82
  // Greedy packing into virtual lanes.
54
83
  for (const taskId of waveTaskIds) {
55
84
  const task = tasksById[taskId];
56
- if (!task) {
57
- throw new Error(`Missing task packet for ${taskId} during lane assignment`);
58
- }
59
-
85
+
60
86
  const taskPaths = (task.fileScope ?? [])
61
87
  .map(normalizeFileScopePath)
62
88
  .filter(Boolean);
@@ -64,10 +90,18 @@ export function assignLanesToWaves({ waves, tasksById, maxParallel, queueExcess
64
90
  let placed = false;
65
91
  for (let i = 0; i < virtualLanes.length; i++) {
66
92
  const lane = virtualLanes[i];
67
- if (taskOverlapsLane(taskPaths, lane.lanePaths)) {
93
+
94
+ // Matrix sub-tasks of the same parent task do not conflict with each other
95
+ const hasSameParent = lane.taskIds.some(id => {
96
+ const other = tasksById[id];
97
+ return other && other.parentTaskId && other.parentTaskId === task.parentTaskId;
98
+ });
99
+
100
+ if (!hasSameParent && taskOverlapsLane(taskPaths, lane.lanePaths)) {
68
101
  virtualLaneForTask[taskId] = i;
69
102
  // Append to lane paths so future tasks are checked against everything already assigned.
70
103
  lane.lanePaths.push(...taskPaths);
104
+ lane.taskIds.push(taskId);
71
105
  placed = true;
72
106
  break;
73
107
  }
@@ -75,7 +109,7 @@ export function assignLanesToWaves({ waves, tasksById, maxParallel, queueExcess
75
109
 
76
110
  if (!placed) {
77
111
  const i = virtualLanes.length;
78
- virtualLanes.push({ lanePaths: [...taskPaths] });
112
+ virtualLanes.push({ lanePaths: [...taskPaths], taskIds: [taskId] });
79
113
  virtualLaneForTask[taskId] = i;
80
114
  }
81
115
  }
@@ -0,0 +1,122 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * Parse a markdown table into an array of objects.
5
+ *
6
+ * @param {string} markdown
7
+ * @returns {{ rows: Array<Record<string, string>>, columns: string[] }}
8
+ */
9
+ export function parseMatrixTable(markdown) {
10
+ if (!markdown || !markdown.trim()) {
11
+ return { rows: [], columns: [] };
12
+ }
13
+
14
+ const lines = markdown.split(/\r?\n/).map(line => line.trim()).filter(line => line.startsWith('|') && line.endsWith('|'));
15
+
16
+ if (lines.length < 2) {
17
+ return { rows: [], columns: [] };
18
+ }
19
+
20
+ /** @param {string} line */
21
+ const parseCells = (line) => {
22
+ const parts = line.split('|');
23
+ // Remove the first and last parts since they are outside the bounding pipes
24
+ return parts.slice(1, parts.length - 1).map(s => s.trim());
25
+ };
26
+
27
+ const columns = parseCells(lines[0]);
28
+ if (columns.length === 0 || columns.every(c => !c)) {
29
+ return { rows: [], columns: [] };
30
+ }
31
+
32
+ /** @type {Array<Record<string, string>>} */
33
+ const rows = [];
34
+ // Skip line[1] which is the separator
35
+ for (let i = 2; i < lines.length; i++) {
36
+ const cellValues = parseCells(lines[i]);
37
+ /** @type {Record<string, string>} */
38
+ const rowObj = {};
39
+ let hasValue = false;
40
+ for (let c = 0; c < columns.length; c++) {
41
+ const col = columns[c];
42
+ if (!col) continue; // Skip empty header columns
43
+ const val = cellValues[c] ?? "";
44
+ rowObj[col] = val;
45
+ if (val) hasValue = true;
46
+ }
47
+ if (hasValue) {
48
+ rows.push(rowObj);
49
+ }
50
+ }
51
+
52
+ return { rows, columns };
53
+ }
54
+
55
+ /**
56
+ * Derives a string id for a row. Prefer `run_id`, else join values.
57
+ * @param {Record<string, string>} row
58
+ * @param {string[]} columns
59
+ * @returns {string}
60
+ */
61
+ export function deriveMatrixRowId(row, columns) {
62
+ if (row['run_id']) {
63
+ return row['run_id'];
64
+ }
65
+ return columns.map(col => row[col]).join('_').replace(/[^a-zA-Z0-9_-]/g, '_');
66
+ }
67
+
68
+ /** Matches `{matrix.<column>}` placeholders. Column names are `[a-zA-Z0-9_-]+`. */
69
+ const MATRIX_VAR_RE = /\{matrix\.([a-zA-Z0-9_-]+)\}/g;
70
+
71
+ /**
72
+ * Substitute `{matrix.<column>}` placeholders in a template string with the
73
+ * matching value from a matrix row.
74
+ *
75
+ * Fails loud (throws) on any reference whose column is absent from the row, so a
76
+ * typo such as `{matrix.rnu_id}` never silently reaches execution. When no row is
77
+ * supplied, text without placeholders is returned unchanged (non-matrix tasks).
78
+ *
79
+ * @param {string} template Arbitrary text (PROMPT body, contract field, step command).
80
+ * @param {Record<string, string> | null | undefined} row Matrix row values keyed by column.
81
+ * @returns {string}
82
+ */
83
+ export function substituteMatrixVariables(template, row) {
84
+ const text = String(template ?? "");
85
+
86
+ // No row: a template without placeholders (non-matrix task) is returned verbatim.
87
+ // A leftover {matrix.X} with no row is an authoring error — fail loud.
88
+ if (!row) {
89
+ return text.replace(MATRIX_VAR_RE, (match, column) => {
90
+ throw new Error(`Unknown matrix variable reference: {matrix.${column}}`);
91
+ });
92
+ }
93
+
94
+ const values = row;
95
+ return text.replace(MATRIX_VAR_RE, (match, column) => {
96
+ if (!Object.prototype.hasOwnProperty.call(values, column)) {
97
+ throw new Error(`Unknown matrix variable reference: {matrix.${column}}`);
98
+ }
99
+ const value = values[column];
100
+ return value == null ? "" : String(value);
101
+ });
102
+ }
103
+
104
+ /**
105
+ * Substitute `{matrix.<column>}` placeholders in parsed step titles and bodies.
106
+ * Returns a new steps array; the input is returned unchanged when no row is
107
+ * supplied (non-matrix tasks are untouched).
108
+ *
109
+ * @param {Array<{ number: number, title: string, body: string }>} steps Parsed steps from `parsePrompt`.
110
+ * @param {Record<string, string> | null | undefined} row Matrix row values keyed by column.
111
+ * @returns {Array<{ number: number, title: string, body: string }>}
112
+ */
113
+ export function applyMatrixRowToSteps(steps, row) {
114
+ if (!Array.isArray(steps) || !row || Object.keys(row).length === 0) {
115
+ return steps;
116
+ }
117
+ return steps.map((step) => ({
118
+ ...step,
119
+ title: substituteMatrixVariables(step.title, row),
120
+ body: substituteMatrixVariables(step.body, row),
121
+ }));
122
+ }
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  import { fileScopesOverlap, findWaveFileScopeOverlaps } from './file-scope.mjs';
7
+ import { deriveMatrixRowId } from './matrix.mjs';
7
8
 
8
9
  /**
9
10
  * @param {string[]} taskScope
@@ -27,9 +28,35 @@ export function assignLanesToWaves({ waves, tasksById, maxParallel, queueExcess
27
28
  const planned = [];
28
29
 
29
30
  for (let waveIndex = 0; waveIndex < waves.length; waveIndex++) {
30
- const waveTaskIds = waves[waveIndex];
31
+ const rawWaveTaskIds = waves[waveIndex];
32
+ const waveTaskIds = [];
31
33
 
32
- /** @type {{ taskScopes: string[][] }} */
34
+ for (const taskId of rawWaveTaskIds) {
35
+ const task = tasksById[taskId];
36
+ if (!task) {
37
+ throw new Error(`Missing task packet for ${taskId} during lane assignment`);
38
+ }
39
+
40
+ if (task.matrix && Array.isArray(task.matrix) && task.matrix.length > 0) {
41
+ for (const row of task.matrix) {
42
+ const rowId = deriveMatrixRowId(row, task.matrixColumns || []);
43
+ const subTaskId = `${taskId}[${rowId}]`;
44
+ waveTaskIds.push(subTaskId);
45
+ if (!tasksById[subTaskId]) {
46
+ tasksById[subTaskId] = {
47
+ ...task,
48
+ taskId: subTaskId,
49
+ matrixRow: row,
50
+ parentTaskId: taskId
51
+ };
52
+ }
53
+ }
54
+ } else {
55
+ waveTaskIds.push(taskId);
56
+ }
57
+ }
58
+
59
+ /** @type {{ taskScopes: string[][], taskIds: string[] }} */
33
60
  const virtualLanes = [];
34
61
 
35
62
  /** @type {Record<string, { virtualLane: number, tick: number, laneInTick: number }>} */
@@ -39,18 +66,22 @@ export function assignLanesToWaves({ waves, tasksById, maxParallel, queueExcess
39
66
 
40
67
  for (const taskId of waveTaskIds) {
41
68
  const task = tasksById[taskId];
42
- if (!task) {
43
- throw new Error(`Missing task packet for ${taskId} during lane assignment`);
44
- }
45
-
69
+
46
70
  const taskScope = Array.isArray(task.fileScope) ? task.fileScope : [];
47
71
 
48
72
  let placed = false;
49
73
  for (let i = 0; i < virtualLanes.length; i++) {
50
74
  const lane = virtualLanes[i];
51
- if (taskOverlapsLane(taskScope, lane.taskScopes)) {
75
+
76
+ const hasSameParent = lane.taskIds.some(id => {
77
+ const other = tasksById[id];
78
+ return other && other.parentTaskId && other.parentTaskId === task.parentTaskId;
79
+ });
80
+
81
+ if (!hasSameParent && taskOverlapsLane(taskScope, lane.taskScopes)) {
52
82
  virtualLaneForTask[taskId] = i;
53
83
  lane.taskScopes.push(taskScope);
84
+ lane.taskIds.push(taskId);
54
85
  placed = true;
55
86
  break;
56
87
  }
@@ -58,7 +89,7 @@ export function assignLanesToWaves({ waves, tasksById, maxParallel, queueExcess
58
89
 
59
90
  if (!placed) {
60
91
  const i = virtualLanes.length;
61
- virtualLanes.push({ taskScopes: [taskScope] });
92
+ virtualLanes.push({ taskScopes: [taskScope], taskIds: [taskId] });
62
93
  virtualLaneForTask[taskId] = i;
63
94
  }
64
95
  }
@@ -1,6 +1,8 @@
1
1
  // @ts-nocheck
2
2
  import { parseSizeLineFromMarkdown } from "./size-line.mjs";
3
3
 
4
+ import { parseMatrixTable } from "../../planner/matrix.mjs";
5
+
4
6
  /** PRD §13.4 — em dash (U+2014) required between ID and title. */
5
7
  export const TASK_HEADING_RE = /^# Task: ([A-Z][A-Z0-9]*-\d+) — (.+)$/m;
6
8
 
@@ -13,7 +15,7 @@ const REQUIRED_SECTIONS = [
13
15
  "Do NOT",
14
16
  ];
15
17
 
16
- const OPTIONAL_SECTIONS = ["Testing", "Context to Read First", "Environment", "Documentation Requirements"];
18
+ const OPTIONAL_SECTIONS = ["Testing", "Context to Read First", "Environment", "Documentation Requirements", "Matrix"];
17
19
 
18
20
  const H2_SECTION_RE = /^## (.+)$/gm;
19
21
  const STEP_HEADING_RE = /^### Step (\d+): (.+)$/gm;
@@ -21,6 +23,7 @@ const STEP_HEADING_RE = /^### Step (\d+): (.+)$/gm;
21
23
  /** Normative contract table fields per handoff §4.1. */
22
24
  export const CONTRACT_FIELD_NAMES = Object.freeze([
23
25
  "testCommand",
26
+ "runCommand",
24
27
  "fileScopeMustChange",
25
28
  "fileScopeMustNotChange",
26
29
  "minLineCoverage",
@@ -65,11 +68,24 @@ export function parsePrompt(markdown) {
65
68
 
66
69
  const missingSections = REQUIRED_SECTIONS.filter((name) => !sections[name]);
67
70
  const size = parseSizeLineFromMarkdown(markdown);
71
+ const typeMatch = /^\*\*Type:\*\*\s*(llm|execute)\s*$/im.exec(markdown);
72
+ const type = typeMatch ? typeMatch[1].toLowerCase() : "llm";
73
+
74
+ let matrix = null;
75
+ let matrixColumns = null;
76
+ if (sections.Matrix) {
77
+ const parsedMatrix = parseMatrixTable(sections.Matrix);
78
+ if (parsedMatrix.rows.length > 0) {
79
+ matrix = parsedMatrix.rows;
80
+ matrixColumns = parsedMatrix.columns;
81
+ }
82
+ }
68
83
 
69
84
  return {
70
85
  taskId,
71
86
  title,
72
87
  size,
88
+ type,
73
89
  headingLine,
74
90
  sections,
75
91
  steps,
@@ -79,6 +95,7 @@ export function parsePrompt(markdown) {
79
95
  missingSections,
80
96
  requiredSections: REQUIRED_SECTIONS,
81
97
  optionalSections: OPTIONAL_SECTIONS,
98
+ ...(matrix ? { matrix, matrixColumns } : {})
82
99
  };
83
100
  }
84
101
 
@@ -113,6 +130,13 @@ export function validatePrompt(markdown) {
113
130
 
114
131
  errors.push(...collectDuplicateStepNumberErrors(prompt.steps));
115
132
 
133
+ if (prompt.type === "execute") {
134
+ const contract = parseContract(markdown);
135
+ if (!contract.testCommand && !contract.runCommand) {
136
+ errors.push("Type: execute tasks require a testCommand or runCommand in the ## Contract section");
137
+ }
138
+ }
139
+
116
140
  return { ok: errors.length === 0, errors, prompt };
117
141
  }
118
142
 
@@ -149,6 +173,7 @@ function collectDuplicateStepNumberErrors(steps) {
149
173
  * @param {string} markdown PROMPT.md contents
150
174
  * @returns {{
151
175
  * testCommand: string | null,
176
+ * runCommand: string | null,
152
177
  * fileScopeMustChange: string[],
153
178
  * fileScopeMustNotChange: string[],
154
179
  * minLineCoverage: number | null,
@@ -171,6 +196,7 @@ export function parseContract(markdown) {
171
196
  /** @type {ReturnType<typeof parseContract>} */
172
197
  const parsed = {
173
198
  testCommand: null,
199
+ runCommand: null,
174
200
  fileScopeMustChange: [],
175
201
  fileScopeMustNotChange: [],
176
202
  minLineCoverage: null,
@@ -297,6 +323,19 @@ function applyContractField(parsed, field, rawValue) {
297
323
  parsed.testCommand = command;
298
324
  return;
299
325
  }
326
+ case "runCommand": {
327
+ const command = parseContractScalar(value);
328
+ if (command.includes("\n")) {
329
+ parsed.errors.push("Contract runCommand must not contain newlines");
330
+ return;
331
+ }
332
+ if (command.length > TEST_COMMAND_MAX_LENGTH) {
333
+ parsed.errors.push(`Contract runCommand exceeds ${TEST_COMMAND_MAX_LENGTH} characters`);
334
+ return;
335
+ }
336
+ parsed.runCommand = command;
337
+ return;
338
+ }
300
339
  case "fileScopeMustChange":
301
340
  parsed.fileScopeMustChange = parseContractPathList(value);
302
341
  return;