pi-spine 2.23.0 → 2.25.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.
Files changed (33) hide show
  1. package/README.md +1 -1
  2. package/bin/spine-worker-runner.mjs +2 -1
  3. package/package.json +5 -5
  4. package/src/batch/attached-runner-promote.mjs +14 -0
  5. package/src/batch/batch-state-io.mjs +120 -45
  6. package/src/batch/engine-crash-guard.mjs +143 -0
  7. package/src/batch/engine-lanes/matrix-run.mjs +28 -2
  8. package/src/batch/engine-lanes/matrix.mjs +143 -8
  9. package/src/batch/integrate-dirty-overlap.mjs +35 -0
  10. package/src/batch/integrate-worktree.mjs +106 -13
  11. package/src/batch/integrate.mjs +34 -93
  12. package/src/batch/journal-checksum.mjs +26 -0
  13. package/src/batch/journal.mjs +32 -13
  14. package/src/batch/lifecycle-archive.mjs +8 -2
  15. package/src/batch/lifecycle.mjs +2 -2
  16. package/src/batch/reconcile-batch.mjs +26 -19
  17. package/src/batch/reconcile-classify.mjs +21 -11
  18. package/src/batch/reconcile-diagnosis-context.mjs +1 -2
  19. package/src/batch/reconcile-diagnosis.mjs +18 -19
  20. package/src/batch/reconcile-light-cache.mjs +0 -1
  21. package/src/batch/reconcile-orphan.mjs +9 -8
  22. package/src/batch/reconcile.mjs +0 -1
  23. package/src/batch/salvage-batch-integrate.mjs +13 -17
  24. package/src/batch/state.mjs +22 -1
  25. package/src/batch/worker-heartbeat.mjs +29 -8
  26. package/src/batch/worker-host.mjs +29 -4
  27. package/src/batch/worker-output.mjs +9 -6
  28. package/src/batch/worker-prompt.mjs +4 -2
  29. package/src/batch/worker-spawn.mjs +99 -12
  30. package/src/config/preflight/discovery.mjs +20 -12
  31. package/src/doctor/run-doctor-checks.mjs +41 -3
  32. package/src/planner/scope.mjs +3 -1
  33. package/src/tasks/packet/discover.mjs +59 -3
package/README.md CHANGED
@@ -49,7 +49,7 @@ Primary monitor surfaces: **`spine status --diagnose`**, **`spine dashboard`** /
49
49
  | [pi](https://pi.dev) coding agent | ≥ 0.80.0 (`pi.minPiVersion`) | Yes |
50
50
  | Git (worktree support) | — | Yes |
51
51
 
52
- These are the Wave A floors ([#285](https://github.com/beettlle/pi-spine/issues/285)). `spine doctor` **warns** when the installed pi is below `pi.minPiVersion` ("pi version supported"). The optional peer `@earendil-works/pi-coding-agent` is developed and tested against `^0.87.0` (pinned in `devDependencies`; the `peerDependencies` range stays `*`).
52
+ These are the Wave A floors ([#285](https://github.com/beettlle/pi-spine/issues/285)). `spine doctor` **warns** when the installed pi is below `pi.minPiVersion` ("pi version supported"). The optional peer `@earendil-works/pi-coding-agent` is developed and tested against `^0.87.1` (pinned in `devDependencies`; the `peerDependencies` range stays `*`).
53
53
 
54
54
  ## Install
55
55
 
@@ -36,6 +36,7 @@ import {
36
36
  writeWorkerDoneMarker,
37
37
  } from "../src/batch/worker-output.mjs";
38
38
  import { buildWorkerTailPrompt, taskIdFromFolder } from "../src/batch/worker-prompt.mjs";
39
+ import { taskIdFromFolderName } from "../src/tasks/packet/discover.mjs";
39
40
  import { DEFAULT_TASKS_ROOT } from "../src/config/spine-init-constants.mjs";
40
41
  import {
41
42
  isPiExtensionConflictOutput,
@@ -312,7 +313,7 @@ async function runWorkerRunner() {
312
313
  const mode = process.argv.includes("--stub") ? "stub" : "pi";
313
314
 
314
315
  if (mode === "stub") {
315
- const parsedTaskId = path.basename(taskFolder).match(/^([A-Z]+-\d+)/)?.[1] ?? "";
316
+ const parsedTaskId = taskIdFromFolderName(path.basename(taskFolder)) ?? "";
316
317
  const failTasks = String(process.env.SPINE_WORKER_STUB_FAIL_TASKS ?? "")
317
318
  .split(/[,\s]+/)
318
319
  .filter(Boolean);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.23.0",
3
+ "version": "2.25.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -72,11 +72,11 @@
72
72
  }
73
73
  },
74
74
  "devDependencies": {
75
- "@earendil-works/pi-coding-agent": "^0.87.0",
76
- "@types/node": "^22.19.18",
77
- "eslint": "^10.10.0",
75
+ "@earendil-works/pi-coding-agent": "^0.87.1",
76
+ "@types/node": "^22.20.4",
77
+ "eslint": "^10.11.0",
78
78
  "globals": "^17.12.0",
79
- "typebox": "1.3.30",
79
+ "typebox": "1.3.34",
80
80
  "typescript": "6.0.3"
81
81
  },
82
82
  "license": "MIT",
@@ -19,6 +19,7 @@ import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
19
19
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
20
20
  import { resolveAttachedMilestonePollMs } from "../config/spine-config-schema.mjs";
21
21
  import { startParentSessionMonitor } from "./parent-session-monitor.mjs";
22
+ import { installEngineCrashHandlers } from "./engine-crash-guard.mjs";
22
23
  import {
23
24
  enforceAttachedEngineSingleOwner,
24
25
  reconcilePausedResumeDoneInLane,
@@ -240,6 +241,15 @@ export async function startAttachedMilestoneReporter({
240
241
  stop: async () => {
241
242
  stopped = true;
242
243
  await loopPromise;
244
+ // A fast engine can finish inside one poll interval, so the loop above
245
+ // may never have discovered the batchId (#308 follow-up: the worker
246
+ // poll loop no longer idles 5s per poll, shortening attached runs).
247
+ // Discover it here so the final flush still prints milestones — a
248
+ // completed batch must always surface [spine] batch.completed.
249
+ if (!batchId) {
250
+ const loaded = loadSpineBatchState(projectRoot);
251
+ batchId = loaded.raw?.batchId ? String(loaded.raw.batchId) : null;
252
+ }
243
253
  if (batchId) {
244
254
  const events = readJournalEventsCached(projectRoot, batchId);
245
255
  for (const event of events) {
@@ -282,6 +292,9 @@ export async function runAttachedBatchEngine({
282
292
  }
283
293
 
284
294
  installAttachedExitFinalizeHandlers({ projectRoot, spineBin });
295
+ // Scoped to this engine run: journal `engine.crashed` + fail the batch on a
296
+ // process-level crash, then uninstall so handlers never leak into importers (SP-788).
297
+ const uninstallEngineCrashGuard = installEngineCrashHandlers({ projectRoot });
285
298
  const reporter = await startAttachedMilestoneReporter({ projectRoot, write });
286
299
  /** @type {{ stop: () => Promise<void> }} */
287
300
  let parentMonitor = { stop: async () => {} };
@@ -301,6 +314,7 @@ export async function runAttachedBatchEngine({
301
314
  }
302
315
  return result;
303
316
  } finally {
317
+ uninstallEngineCrashGuard();
304
318
  await parentMonitor.stop();
305
319
  await reporter.stop();
306
320
  }
@@ -7,6 +7,7 @@ import path from "node:path";
7
7
  import { isProcessAlive } from "../process/liveness.mjs";
8
8
  import { parseSpineBatchState } from "./readers/spine-state.mjs";
9
9
  import { parseTaskplaneBatchState } from "./readers/taskplane-state.mjs";
10
+ import { withBatchStateLock } from "./batch-state-lock.mjs";
10
11
 
11
12
  /** Terminal phases safe to clear before a new batch start (SP-441 / #94). */
12
13
  const TERMINAL_PHASES_FOR_HANDOFF = new Set(["completed", "failed", "aborted", "merge_blocked"]);
@@ -126,77 +127,151 @@ export function readAliveBatchEnginePid(raw) {
126
127
  return enginePid;
127
128
  }
128
129
 
130
+ /**
131
+ * Detect a Taskplane-owned batch-state path (`.pi/`) that spine must never
132
+ * modify (SP-786 / #303). Spine start/clear paths act on `.spine/` state only.
133
+ *
134
+ * @param {string} batchStatePath
135
+ */
136
+ function isForeignBatchStatePath(batchStatePath) {
137
+ return batchStatePath.includes(`${path.sep}.pi${path.sep}`);
138
+ }
139
+
140
+ /**
141
+ * Rename a corrupt batch-state file to a collision-safe quarantine name in the
142
+ * same directory (SP-786 / #303). Never unlink: the file is evidence for
143
+ * post-mortem inspection. Uses a UTC timestamp plus a numeric suffix when the
144
+ * name is already taken (two corruptions within the same millisecond).
145
+ *
146
+ * @param {string} batchStatePath
147
+ * @returns {string} the quarantined file path
148
+ */
149
+ function quarantineCorruptBatchState(batchStatePath) {
150
+ const dir = path.dirname(batchStatePath);
151
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
152
+ let quarantinedPath = path.join(dir, `batch-state.corrupt-${stamp}.json`);
153
+ let attempt = 1;
154
+ while (fs.existsSync(quarantinedPath)) {
155
+ quarantinedPath = path.join(dir, `batch-state.corrupt-${stamp}-${attempt}.json`);
156
+ attempt += 1;
157
+ }
158
+ fs.renameSync(batchStatePath, quarantinedPath);
159
+ return quarantinedPath;
160
+ }
161
+
129
162
  /**
130
163
  * Remove active batch-state only when on-disk batch matches expected (SP-441 / #94).
131
164
  * Prevents complete/dismiss from clearing a newer batch after a concurrent start handoff.
132
165
  *
166
+ * Spine-owned path only: a Taskplane-owned `.pi/batch-state.json` is never
167
+ * renamed or unlinked here (SP-786 / #303). A corrupt spine-owned state file
168
+ * is quarantined (renamed), never deleted. The read-check-mutate sequence runs
169
+ * under the global batch-state lock; `projectRoot` may be omitted and is then
170
+ * derived from the `.spine` parent directory of `batchStatePath`.
171
+ *
133
172
  * @param {string|null} batchStatePath
134
173
  * @param {string} expectedBatchId
135
- * @returns {{ cleared: boolean, reason?: string, activeBatchId?: string }}
174
+ * @param {string|null} [projectRoot] derived from the `.spine` parent when omitted
175
+ * @returns {{ cleared: boolean, reason?: string, activeBatchId?: string, quarantinedPath?: string }}
136
176
  */
137
- export function clearActiveBatchStateIfMatches(batchStatePath, expectedBatchId) {
177
+ export function clearActiveBatchStateIfMatches(batchStatePath, expectedBatchId, projectRoot = null) {
138
178
  if (!batchStatePath || !fs.existsSync(batchStatePath)) {
139
179
  return { cleared: false, reason: "missing" };
140
180
  }
141
-
142
- try {
143
- const onDisk = JSON.parse(fs.readFileSync(batchStatePath, "utf-8"));
144
- const onDiskBatchId = readBatchStateId(onDisk);
145
- if (onDiskBatchId && onDiskBatchId !== expectedBatchId) {
146
- return {
147
- cleared: false,
148
- reason: "batch_id_mismatch",
149
- activeBatchId: onDiskBatchId,
150
- };
151
- }
152
- } catch {
153
- // Corrupt active state — remove so a new batch can start cleanly.
181
+ if (isForeignBatchStatePath(batchStatePath)) {
182
+ return { cleared: false, reason: "foreign_state" };
154
183
  }
155
184
 
156
- fs.unlinkSync(batchStatePath);
157
- return { cleared: true };
185
+ // Derive the lock root from `<root>/.spine/batch-state.json` when no caller supplies one.
186
+ const lockRoot = projectRoot ?? path.dirname(path.dirname(batchStatePath));
187
+ const result = /** @type {{ cleared: boolean, reason?: string, activeBatchId?: string, quarantinedPath?: string }} */ (
188
+ withBatchStateLock(lockRoot, () => {
189
+ try {
190
+ const onDisk = JSON.parse(fs.readFileSync(batchStatePath, "utf-8"));
191
+ const onDiskBatchId = readBatchStateId(onDisk);
192
+ if (onDiskBatchId && onDiskBatchId !== expectedBatchId) {
193
+ return {
194
+ cleared: false,
195
+ reason: "batch_id_mismatch",
196
+ activeBatchId: onDiskBatchId,
197
+ };
198
+ }
199
+ } catch (err) {
200
+ if (/** @type {NodeJS.ErrnoException} */ (err)?.code === "ENOENT") {
201
+ return { cleared: false, reason: "missing" };
202
+ }
203
+ // Corrupt active state — quarantine for inspection, never delete (SP-786 / #303).
204
+ const quarantinedPath = quarantineCorruptBatchState(batchStatePath);
205
+ return { cleared: false, reason: "corrupt", quarantinedPath };
206
+ }
207
+
208
+ fs.unlinkSync(batchStatePath);
209
+ return { cleared: true };
210
+ })
211
+ );
212
+ return result;
158
213
  }
159
214
 
160
215
  /**
161
216
  * Clear a terminal completed batch-state pointer before spine batch start (SP-441 / #94).
162
217
  *
218
+ * Spine-owned path only (SP-786 / #303): when `.spine/batch-state.json` is
219
+ * absent, a Taskplane-owned `.pi/batch-state.json` is reported as
220
+ * `foreign_state` and never renamed or unlinked. A corrupt spine-owned state
221
+ * file is quarantined (renamed), never deleted. The read-check-mutate sequence
222
+ * runs under the global batch-state lock.
223
+ *
163
224
  * @param {string} projectRoot
164
- * @returns {{ cleared: boolean, reason?: string, batchId?: string }}
225
+ * @returns {{ cleared: boolean, reason?: string, batchId?: string, quarantinedPath?: string }}
165
226
  */
166
227
  export function clearStaleTerminalBatchStateForStart(projectRoot) {
167
- const resolved = resolveBatchStatePath(projectRoot);
168
- if (!resolved || !fs.existsSync(resolved)) {
228
+ const spinePath = path.join(projectRoot, ".spine", "batch-state.json");
229
+ const piPath = path.join(projectRoot, ".pi", "batch-state.json");
230
+
231
+ if (!fs.existsSync(spinePath)) {
232
+ if (fs.existsSync(piPath)) {
233
+ return { cleared: false, reason: "foreign_state" };
234
+ }
169
235
  return { cleared: false, reason: "missing" };
170
236
  }
171
237
 
172
- /** @type {unknown} */
173
- let raw;
174
- try {
175
- raw = JSON.parse(fs.readFileSync(resolved, "utf-8"));
176
- } catch {
177
- fs.unlinkSync(resolved);
178
- return { cleared: true, reason: "corrupt" };
179
- }
238
+ const result = /** @type {{ cleared: boolean, reason?: string, batchId?: string, quarantinedPath?: string }} */ (
239
+ withBatchStateLock(projectRoot, () => {
240
+ /** @type {unknown} */
241
+ let raw;
242
+ try {
243
+ raw = JSON.parse(fs.readFileSync(spinePath, "utf-8"));
244
+ } catch (err) {
245
+ if (/** @type {NodeJS.ErrnoException} */ (err)?.code === "ENOENT") {
246
+ return { cleared: false, reason: "missing" };
247
+ }
248
+ // Corrupt state — quarantine for inspection, never delete (SP-786 / #303).
249
+ const quarantinedPath = quarantineCorruptBatchState(spinePath);
250
+ return { cleared: false, reason: "corrupt", quarantinedPath };
251
+ }
180
252
 
181
- const batchId = readBatchStateId(raw);
182
- const phase = String(/** @type {{ phase?: string }} */ (raw)?.phase ?? "");
183
- const ownerPid = readBatchStateEnginePid(raw);
253
+ const batchId = readBatchStateId(raw);
254
+ const phase = String(/** @type {{ phase?: string }} */ (raw)?.phase ?? "");
255
+ const ownerPid = readBatchStateEnginePid(raw);
184
256
 
185
- if (ACTIVE_PHASES_FOR_HANDOFF.has(phase) && !/** @type {{ endedAt?: unknown }} */ (raw)?.endedAt) {
186
- return { cleared: false, reason: "active", batchId };
187
- }
257
+ if (ACTIVE_PHASES_FOR_HANDOFF.has(phase) && !/** @type {{ endedAt?: unknown }} */ (raw)?.endedAt) {
258
+ return { cleared: false, reason: "active", batchId };
259
+ }
188
260
 
189
- if (ownerPid && isProcessAlive(ownerPid)) {
190
- throw new Error(
191
- `Active batch ${batchId || "(unknown)"} engine still running (pid=${ownerPid}). ` +
192
- "Wait for it to exit or run spine batch dismiss before spine batch start.",
193
- );
194
- }
261
+ if (ownerPid && isProcessAlive(ownerPid)) {
262
+ throw new Error(
263
+ `Active batch ${batchId || "(unknown)"} engine still running (pid=${ownerPid}). ` +
264
+ "Wait for it to exit or run spine batch dismiss before spine batch start.",
265
+ );
266
+ }
195
267
 
196
- if (TERMINAL_PHASES_FOR_HANDOFF.has(phase) || /** @type {{ endedAt?: unknown }} */ (raw)?.endedAt) {
197
- fs.unlinkSync(resolved);
198
- return { cleared: true, reason: "stale_terminal", batchId };
199
- }
268
+ if (TERMINAL_PHASES_FOR_HANDOFF.has(phase) || /** @type {{ endedAt?: unknown }} */ (raw)?.endedAt) {
269
+ fs.unlinkSync(spinePath);
270
+ return { cleared: true, reason: "stale_terminal", batchId };
271
+ }
200
272
 
201
- return { cleared: false, reason: "idle", batchId };
273
+ return { cleared: false, reason: "idle", batchId };
274
+ })
275
+ );
276
+ return result;
202
277
  }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Attached-engine crash guard (SP-788 / #306 item 5).
3
+ *
4
+ * Registers `uncaughtException` / `unhandledRejection` listeners for the
5
+ * duration of one attached engine run only. On a crash the guard journals
6
+ * `engine.crashed`, marks the batch failed, and exits non-zero — the journal
7
+ * and batch-state must never be left on a `running` orphan after a crash.
8
+ *
9
+ * All side effects are injectable via `deps` so tests never touch real
10
+ * process exit or real crash paths.
11
+ */
12
+
13
+ import { appendJournalEvent } from "./journal.mjs";
14
+ import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
15
+
16
+ /** Same cap `failBatchFromEngineError` applies to `lastError` in batch state. */
17
+ const ERROR_MESSAGE_CAP = 500;
18
+ /** Keep the head of the stack: frames near the throw site are the useful ones. */
19
+ const STACK_LINE_CAP = 20;
20
+
21
+ /**
22
+ * Resolve the active batch id from batch-state.json, or null when absent.
23
+ *
24
+ * @param {string} projectRoot
25
+ * @returns {string|null}
26
+ */
27
+ function resolveActiveBatchId(projectRoot) {
28
+ const loaded = loadSpineBatchState(projectRoot);
29
+ const batchId = loaded.raw?.batchId;
30
+ return typeof batchId === "string" && batchId ? batchId : null;
31
+ }
32
+
33
+ /**
34
+ * Cap an error message to the journal-friendly length.
35
+ *
36
+ * @param {unknown} error
37
+ * @returns {string}
38
+ */
39
+ function crashMessage(error) {
40
+ const message = error instanceof Error ? error.message : String(error);
41
+ return message.slice(0, ERROR_MESSAGE_CAP);
42
+ }
43
+
44
+ /**
45
+ * First ~20 lines of the error stack (empty for non-Error throws).
46
+ *
47
+ * @param {unknown} error
48
+ * @returns {string}
49
+ */
50
+ function crashStack(error) {
51
+ const stack = error instanceof Error && typeof error.stack === "string" ? error.stack : "";
52
+ return stack.split("\n").slice(0, STACK_LINE_CAP).join("\n");
53
+ }
54
+
55
+ /**
56
+ * Real mark-failed: same terminal fields as the failed paths in resume.mjs
57
+ * (`phase = "failed"`, `endedAt`, `lastError`) persisted via saveSpineBatchState.
58
+ *
59
+ * @param {object} params
60
+ * @param {string} params.projectRoot
61
+ * @param {string} params.batchId
62
+ * @param {string} params.message
63
+ * @param {number} [params.endedAt]
64
+ * @returns {boolean} false when there is no on-disk batch state to fail
65
+ */
66
+ function defaultMarkBatchFailed({ projectRoot, batchId, message, endedAt }) {
67
+ const loaded = loadSpineBatchState(projectRoot);
68
+ if (!loaded.raw) return false;
69
+ // Fail only the batch that was active at crash time — never a batch that
70
+ // appeared in batch-state.json between resolution and this write.
71
+ if (loaded.raw.batchId !== batchId) return false;
72
+ loaded.raw.phase = "failed";
73
+ loaded.raw.endedAt = typeof endedAt === "number" ? endedAt : Date.now();
74
+ loaded.raw.lastError = String(message).slice(0, ERROR_MESSAGE_CAP);
75
+ saveSpineBatchState(projectRoot, loaded.raw);
76
+ return true;
77
+ }
78
+
79
+ /**
80
+ * Install process-level crash handlers for one attached engine run.
81
+ *
82
+ * The handlers run once (re-entrancy guarded): journal `engine.crashed`,
83
+ * mark the batch failed, then exit non-zero. If journaling or the state
84
+ * save itself throws, the original error still reaches stderr and the
85
+ * process still exits non-zero — a crash guard must never swallow a crash.
86
+ *
87
+ * @param {object} params
88
+ * @param {string} params.projectRoot
89
+ * @param {object} [params.deps] Injectable side effects (all optional).
90
+ * @param {(projectRoot: string, batchId: string, type: string, payload: object) => unknown} [params.deps.appendJournalEvent]
91
+ * @param {(params: { projectRoot: string, batchId: string, message: string, endedAt?: number }) => boolean} [params.deps.markBatchFailed]
92
+ * @param {(code?: number) => void} [params.deps.exit]
93
+ * @param {() => number} [params.deps.now]
94
+ * @returns {() => void} Uninstall — removes both listeners.
95
+ */
96
+ export function installEngineCrashHandlers({ projectRoot, deps = {} }) {
97
+ const {
98
+ appendJournalEvent: appendEvent = appendJournalEvent,
99
+ markBatchFailed = defaultMarkBatchFailed,
100
+ exit = /** @type {(code?: number) => void} */ ((code) => process.exit(code)),
101
+ now = /** @type {() => number} */ (() => Date.now()),
102
+ } = deps ?? {};
103
+
104
+ /** Guard against a second fault firing while the first is being journaled. */
105
+ let handling = false;
106
+
107
+ const handle = (/** @type {string} */ kind, /** @type {unknown} */ error) => {
108
+ if (handling) return;
109
+ handling = true;
110
+
111
+ const message = crashMessage(error);
112
+ try {
113
+ const batchId = resolveActiveBatchId(projectRoot);
114
+ if (batchId) {
115
+ appendEvent(projectRoot, batchId, "engine.crashed", {
116
+ kind,
117
+ error: message,
118
+ stack: crashStack(error),
119
+ });
120
+ markBatchFailed({ projectRoot, batchId, message, endedAt: now() });
121
+ } else {
122
+ process.stderr.write("[spine] engine crashed but no active batch state found; nothing to journal\n");
123
+ }
124
+ } catch (guardError) {
125
+ // Never swallow: the original crash must surface even if the
126
+ // journal write or the state save is what failed.
127
+ const guardMessage = guardError instanceof Error ? guardError.message : String(guardError);
128
+ process.stderr.write(`[spine] engine crash guard failed: ${guardMessage}\n`);
129
+ }
130
+ process.stderr.write(`[spine] engine crashed (${kind}): ${message}\n`);
131
+ exit(1);
132
+ };
133
+
134
+ const onUncaughtException = (/** @type {unknown} */ error) => handle("uncaughtException", error);
135
+ const onUnhandledRejection = (/** @type {unknown} */ reason) => handle("unhandledRejection", reason);
136
+ process.on("uncaughtException", onUncaughtException);
137
+ process.on("unhandledRejection", onUnhandledRejection);
138
+
139
+ return function uninstall() {
140
+ process.removeListener("uncaughtException", onUncaughtException);
141
+ process.removeListener("unhandledRejection", onUnhandledRejection);
142
+ };
143
+ }
@@ -34,7 +34,11 @@ import {
34
34
  } from "../state.mjs";
35
35
  import { runWorker } from "../worker-host.mjs";
36
36
  import { resolveWorktreeSetupIgnorePaths } from "../../config/spine-config-load.mjs";
37
- import { parseContract } from "../../tasks/packet/parse-prompt.mjs";
37
+ import {
38
+ findContractCommandMetacharIssue,
39
+ isRefusedContractMetacharCommand,
40
+ parseContract,
41
+ } from "../../tasks/packet/parse-prompt.mjs";
38
42
  import { verifyContract } from "../contract-verify.mjs";
39
43
  import { gitExec } from "../git-exec.mjs";
40
44
 
@@ -50,6 +54,21 @@ export function readParentContract(parentTaskFolderAbs) {
50
54
  return parseContract(fs.readFileSync(promptPath, "utf-8"));
51
55
  }
52
56
 
57
+ /**
58
+ * Matrix-specific refusal copy for an execute row whose substituted command
59
+ * contains shell metacharacters (#297). Deliberately distinct from the
60
+ * contract-verify copy ("Contract testCommand refused before spawn") so
61
+ * operators can tell a bad row value from a bad authored command.
62
+ *
63
+ * @param {string} rowId
64
+ * @param {string} command
65
+ * @returns {string}
66
+ */
67
+ function formatMatrixRowRefusedMetacharMessage(rowId, command) {
68
+ const issue = findContractCommandMetacharIssue(String(command ?? "").trim());
69
+ return `matrix row command refused before spawn: row '${rowId}' substitutes to a command containing ${issue ?? "shell metacharacters"} (command: ${command}). Row values flow into runCommand through /bin/sh -c; remove $, backticks, ;, |, || or lone & from the row value — && chains are allowed (#268, #297).`;
70
+ }
71
+
53
72
  /**
54
73
  * Serve a matrix LLM row its row-substituted PROMPT.md (#232). Reads the parent
55
74
  * PROMPT.md (same source convention as `readParentContract`), substitutes
@@ -251,7 +270,14 @@ export async function runMatrixSubLane({
251
270
  };
252
271
  } else {
253
272
  const command = substituteRowCommand(rawCommand, values);
254
- const run = await runShellInDir(worktreePath, command, matrixEnv);
273
+ // Guard AFTER substitution, BEFORE spawn (#297): parse-time validation only
274
+ // saw the raw template, so a row value can reintroduce shell metacharacters
275
+ // into an otherwise-clean command. Refused rows never reach /bin/sh — the
276
+ // ternary short-circuits before `runShellInDir` — and the refusal message
277
+ // flows through the failed-row path, which journals `matrix.sub_lane.failed`.
278
+ const run = isRefusedContractMetacharCommand(command)
279
+ ? { exitCode: 1, output: formatMatrixRowRefusedMetacharMessage(rowId, command) }
280
+ : await runShellInDir(worktreePath, command, matrixEnv);
255
281
  if (run.exitCode !== 0) {
256
282
  result = {
257
283
  rowId,