pi-spine 2.16.0 → 2.18.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 (47) hide show
  1. package/bin/spine-gate.mjs +8 -2
  2. package/package.json +1 -1
  3. package/skills/create-spine-tasks/SKILL.md +3 -1
  4. package/skills/create-spine-tasks/references/contract-template.md +12 -12
  5. package/skills/create-spine-tasks/references/prompt-template.md +8 -6
  6. package/skills/spine-autonomous-operator/SKILL.md +2 -0
  7. package/skills/spine-autonomous-operator/references/agent-shell-batch-policy.md +1 -1
  8. package/skills/spine-orchestrate-waves/SKILL.md +6 -4
  9. package/skills/spine-orchestrate-waves/references/outer-loop.md +16 -1
  10. package/skills/spine-release-operator/SKILL.md +3 -0
  11. package/skills/spine-release-operator/references/pi-async-orchestration.md +2 -1
  12. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +14 -0
  13. package/src/batch/batch-guards.mjs +14 -0
  14. package/src/batch/batch-meta-reconstruct.mjs +5 -2
  15. package/src/batch/diagnosis-worker-done-missing.mjs +12 -1
  16. package/src/batch/engine-lanes/matrix-run.mjs +122 -26
  17. package/src/batch/engine-lanes/merge.mjs +16 -11
  18. package/src/batch/engine-lanes/phase.mjs +45 -0
  19. package/src/batch/engine-lanes/queue.mjs +1 -1
  20. package/src/batch/engine-lanes.mjs +9 -37
  21. package/src/batch/engine.mjs +8 -16
  22. package/src/batch/gate.mjs +153 -6
  23. package/src/batch/heartbeat.mjs +18 -0
  24. package/src/batch/post-merge-finalize.mjs +128 -0
  25. package/src/batch/post-merge-limbo.mjs +14 -85
  26. package/src/batch/readers/spine-state.mjs +22 -1
  27. package/src/batch/readers/taskplane-state.mjs +22 -1
  28. package/src/batch/reconcile-batch.mjs +1 -1
  29. package/src/batch/resume-common.mjs +1 -1
  30. package/src/batch/resume-gate-reopen.mjs +50 -0
  31. package/src/batch/resume-multi-validate.mjs +43 -0
  32. package/src/batch/resume-multi.mjs +6 -2
  33. package/src/batch/resume-prompt-parse-fail.mjs +75 -0
  34. package/src/batch/resume.mjs +21 -40
  35. package/src/batch/review-spawn.mjs +4 -3
  36. package/src/batch/salvage-batch-integrate-gate.mjs +180 -0
  37. package/src/batch/salvage-batch-integrate.mjs +66 -4
  38. package/src/batch/worker-heartbeat.mjs +31 -6
  39. package/src/batch/worker-host.mjs +27 -1
  40. package/src/batch/worker-output.mjs +56 -0
  41. package/src/cli/journal-follow.mjs +3 -1
  42. package/src/cli/lane-logs.mjs +3 -1
  43. package/src/cli/settings-slash.mjs +2 -1
  44. package/src/config/worker-context.mjs +2 -1
  45. package/src/planner/matrix.mjs +24 -0
  46. package/src/tasks/analyze/index.mjs +2 -1
  47. package/src/tasks/validate-contract-warn.mjs +45 -0
@@ -10,6 +10,7 @@ import {
10
10
  checkpointSignalsChanged,
11
11
  collectProgressSignals,
12
12
  computeStallDeadline,
13
+ isStaticNullProgressSnapshot,
13
14
  recordCheckpointWarning,
14
15
  recordLaneHeartbeat,
15
16
  recordLaneProgressSnapshot,
@@ -326,12 +327,21 @@ export async function pollWorkerUntilSettled({
326
327
  heartbeatKind,
327
328
  }),
328
329
  );
329
- stallAnchorAt = nextStallAnchorAt({
330
- stallAnchorAt,
331
- now,
332
- workerPhase,
333
- heartbeatKind,
334
- });
330
+ // Issue #272: a worker_alive heartbeat whose progress snapshot is static-null
331
+ // (statusMtimeMs / lastCommitAtMs / fileScopeMtimeMs null, dirtyPathCount 0, all
332
+ // unchanged) carries no progress evidence. The engine emits heartbeats itself
333
+ // while the child merely has not exited, so child liveness alone must not
334
+ // refresh the stall anchor — a SIGSTOP-style hung worker would otherwise slide
335
+ // the stall deadline forward forever and never journal stall events.
336
+ const staticNullProgress = isStaticNullProgressSnapshot(signals);
337
+ if (!(heartbeatKind === "worker_alive" && staticNullProgress)) {
338
+ stallAnchorAt = nextStallAnchorAt({
339
+ stallAnchorAt,
340
+ now,
341
+ workerPhase,
342
+ heartbeatKind,
343
+ });
344
+ }
335
345
  onHeartbeat?.(now);
336
346
  lastHeartbeatAt = now;
337
347
  }
@@ -344,6 +354,21 @@ export async function pollWorkerUntilSettled({
344
354
  });
345
355
 
346
356
  if (now >= stallDeadline) {
357
+ // SP-738 (#273): .DONE can be written between the loop-top check and this
358
+ // deadline check. A worker that has completed its contract is not a stall —
359
+ // hand it back to the done branch, which honors the post-done grace before
360
+ // any termination. Workers without .DONE keep the strict stall path (#272).
361
+ if (fs.existsSync(donePath)) {
362
+ if (projectRoot && batchId) {
363
+ appendJournalEvent(projectRoot, batchId, "worker.done_honored_at_stall", {
364
+ laneNumber,
365
+ taskId,
366
+ correlationId: laneCorrelationId,
367
+ stallDeadline,
368
+ });
369
+ }
370
+ continue;
371
+ }
347
372
  if (!stallWarningSent && projectRoot && batchId) {
348
373
  recordStallWarning({
349
374
  projectRoot,
@@ -36,6 +36,15 @@ export { buildWorkerChildEnv } from "./worker-spawn.mjs";
36
36
 
37
37
  const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
38
38
 
39
+ /**
40
+ * Exit code the worker runner uses when the `pi` spawn hits its wall-clock
41
+ * budget (ETIMEDOUT). Must stay in sync with bin/spine-worker-runner.mjs.
42
+ * Engine-initiated kills surface as exit code 1 (signal → `code ?? 1` in
43
+ * collectChildOutput), so 124 only ever originates from the runner's own
44
+ * timeout — never from post-done or stall termination.
45
+ */
46
+ const WORKER_TIMEOUT_EXIT_CODE = 124;
47
+
39
48
  /**
40
49
  * Force-terminate lane worker process trees tracked in batch state.
41
50
  * Reaps nested `pi` grandchildren, not only the tracked runner PID (SP-609 / #194).
@@ -326,7 +335,24 @@ export async function runWorker({
326
335
  config,
327
336
  });
328
337
  }
329
- const ok = doneFound && (exitCode === 0 || postDoneTerminated);
338
+ // SP-738 (#273): the runner exits 124 when the `pi` spawn hit its wall-clock
339
+ // budget (ETIMEDOUT). If the agent had already written .DONE, the task is done —
340
+ // do not classify a completed worker as timeout-failed. Post-done termination
341
+ // already resolves via postDoneTerminated, and true stalls never reach this
342
+ // boundary with .DONE absent (#272 keeps them failing).
343
+ const timedOutAfterDone =
344
+ doneFound && !postDoneTerminated && exitCode === WORKER_TIMEOUT_EXIT_CODE;
345
+ if (timedOutAfterDone && projectRoot && batchId) {
346
+ appendJournalEvent(projectRoot, batchId, "worker.done_after_timeout", {
347
+ laneNumber,
348
+ taskId,
349
+ correlationId: laneCorrelationId,
350
+ exitCode,
351
+ mode: workerMode,
352
+ });
353
+ }
354
+ const ok =
355
+ doneFound && (exitCode === 0 || postDoneTerminated || timedOutAfterDone);
330
356
  let classification = ok ? "succeeded" : "failed";
331
357
  if (!ok && useLaunchScript && !childPastPreflight) {
332
358
  classification = "launch_failed";
@@ -360,6 +360,62 @@ export function finalizeWorkerOutput({
360
360
  };
361
361
  }
362
362
 
363
+ /**
364
+ * Targeted `worker_done_missing` hint for backgrounded verifications (SP-741, #276).
365
+ * A worker that exits while a long verification is still running (waiting on a
366
+ * completion wake) cannot be resumed — the session dies with the turn.
367
+ */
368
+ export const BACKGROUND_VERIFICATION_HINT =
369
+ "backgrounded verification detected — long verifications must run in the foreground and finish in-session before .DONE";
370
+
371
+ /** Output phrases that on their own indicate background-and-exit behavior. */
372
+ const BACKGROUND_VERIFICATION_STRONG_MARKERS = [
373
+ "completion wake",
374
+ "running in the background",
375
+ "background monitor",
376
+ "backgrounded",
377
+ "monitorcreate",
378
+ ];
379
+
380
+ /** Output phrases indicating a verification has not finished yet. */
381
+ const BACKGROUND_VERIFICATION_PENDING_MARKERS = [
382
+ "still running",
383
+ "still in progress",
384
+ "not finished",
385
+ "hasn't finished",
386
+ "has not finished",
387
+ ];
388
+
389
+ /** Phrases that pair with pending work to indicate it was detached/backgrounded. */
390
+ const BACKGROUND_VERIFICATION_CONTEXT_MARKERS = [
391
+ "background",
392
+ "wake",
393
+ "monitor",
394
+ "redirected",
395
+ "detached",
396
+ ];
397
+
398
+ /**
399
+ * Detect worker output suggesting a long verification was backgrounded instead
400
+ * of run in the foreground (#276). Matched against the captured output tail
401
+ * at `worker_done_missing` diagnosis time; advisory only.
402
+ *
403
+ * @param {string|null|undefined} outputText
404
+ * @returns {boolean}
405
+ */
406
+ export function detectBackgroundedVerification(outputText) {
407
+ if (!outputText || !String(outputText).trim()) return false;
408
+ const normalized = String(outputText).toLowerCase();
409
+ if (BACKGROUND_VERIFICATION_STRONG_MARKERS.some((marker) => normalized.includes(marker))) {
410
+ return true;
411
+ }
412
+ const hasPending = BACKGROUND_VERIFICATION_PENDING_MARKERS.some((marker) =>
413
+ normalized.includes(marker),
414
+ );
415
+ if (!hasPending) return false;
416
+ return BACKGROUND_VERIFICATION_CONTEXT_MARKERS.some((marker) => normalized.includes(marker));
417
+ }
418
+
363
419
  /**
364
420
  * Parse a `.DONE` marker body. Legacy empty/text markers remain valid (SP-321).
365
421
  *
@@ -157,8 +157,10 @@ const defaultDeps = {
157
157
  * @param {string[]} [options.args]
158
158
  * @param {boolean} [options.follow]
159
159
  * @param {typeof defaultDeps} [options.deps]
160
+ * @returns {{ exitCode: number, output: string } | Promise<{ exitCode: number, output: string }>}
161
+ * Plain result for the non-follow path; a Promise that resolves on SIGINT/SIGTERM when following.
160
162
  */
161
- export async function runJournalFollow(options) {
163
+ export function runJournalFollow(options) {
162
164
  const { projectRoot, args = [], follow = true, deps = defaultDeps } = options;
163
165
  const { batchId: argBatchId, laneId, json } = parseJournalFollowArgs(args);
164
166
  let batchId = null;
@@ -190,8 +190,10 @@ const defaultDeps = {
190
190
  * @param {string[]} [options.args]
191
191
  * @param {boolean} [options.follow]
192
192
  * @param {typeof defaultDeps} [options.deps]
193
+ * @returns {{ exitCode: number, output: string } | Promise<{ exitCode: number, output: string }>}
194
+ * Plain result for the non-follow path; a Promise that resolves on SIGINT/SIGTERM when following.
193
195
  */
194
- export async function runLaneLogs(options) {
196
+ export function runLaneLogs(options) {
195
197
  const { projectRoot, args = [], follow: followOverride, deps = defaultDeps } = options;
196
198
  const { batchId: argBatchId, laneNumber, taskId: argTaskId, follow: argFollow } =
197
199
  parseLaneLogsArgs(args);
@@ -66,8 +66,9 @@ function parseSetArgs(argsText) {
66
66
  * @param {string} args
67
67
  * @param {{ notify: (message: string, level: string) => void }} ui
68
68
  * @param {string} [cwd]
69
+ * @returns {void}
69
70
  */
70
- export async function runSpineSettingsSlash(args, ui, cwd = process.cwd()) {
71
+ export function runSpineSettingsSlash(args, ui, cwd = process.cwd()) {
71
72
  const trimmed = args.trim();
72
73
 
73
74
  if (trimmed === "set" || trimmed.startsWith("set ")) {
@@ -223,8 +223,9 @@ export function emitWorkerRulesSelected(journal, payload) {
223
223
  * @param {string[]} [params.taskFileScope]
224
224
  * @param {number} [params.byteCap]
225
225
  * @param {WorkerRulesJournalContext} [params.journal]
226
+ * @returns {{ text: string, entries: object[], truncated: boolean, skipped: string[], bytesUsed: number, byteCap: number, selection: object, error?: string, blockedPath?: string }}
226
227
  */
227
- export async function buildWorkerContextAsync({
228
+ export function buildWorkerContextAsync({
228
229
  config = {},
229
230
  projectRoot = process.cwd(),
230
231
  taskFileScope = [],
@@ -120,3 +120,27 @@ export function applyMatrixRowToSteps(steps, row) {
120
120
  body: substituteMatrixVariables(step.body, row),
121
121
  }));
122
122
  }
123
+
124
+ /**
125
+ * Substitute `{matrix.<column>}` placeholders across an entire raw PROMPT.md
126
+ * document for one matrix row. This is the LLM-row serving vehicle (#232):
127
+ * workers consume the raw markdown, so whole-document substitution is the
128
+ * composition of `applyMatrixRowToSteps` (step titles/bodies),
129
+ * `applyMatrixRowToContract` (contract table fields), and the File Scope paths
130
+ * in a single pass, with the same fail-loud semantics via
131
+ * `substituteMatrixVariables` — an unknown `{matrix.X}` reference throws.
132
+ *
133
+ * The input is returned unchanged when no row is supplied or the row is empty
134
+ * (non-matrix tasks keep their PROMPT verbatim), mirroring the guards on the
135
+ * structured helpers.
136
+ *
137
+ * @param {string} promptText Raw PROMPT.md content.
138
+ * @param {Record<string, string> | null | undefined} row Matrix row values keyed by column.
139
+ * @returns {string}
140
+ */
141
+ export function applyMatrixRowToPrompt(promptText, row) {
142
+ if (typeof promptText !== "string" || !row || Object.keys(row).length === 0) {
143
+ return promptText;
144
+ }
145
+ return substituteMatrixVariables(promptText, row);
146
+ }
@@ -334,8 +334,9 @@ function throwAnalyzeError(message, { suggestedCommand, exitCode = 2 } = {}) {
334
334
 
335
335
  /**
336
336
  * @param {{ projectRoot?: string, scope?: string }} [args]
337
+ * @returns {{ scope: ReturnType<typeof parseScope>, result: object, output: string, exitCode: number }}
337
338
  */
338
- export async function analyzeTasksScope({ projectRoot = process.cwd(), scope = 'all' } = {}) {
339
+ export function analyzeTasksScope({ projectRoot = process.cwd(), scope = 'all' } = {}) {
339
340
  const configResult = loadSpineConfig(projectRoot);
340
341
  if (configResult.error) {
341
342
  throwAnalyzeError(configResult.error.message, {
@@ -15,7 +15,23 @@ export const TEST_COMMAND_NPM_TEST_FIX_HINT =
15
15
  export const TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT =
16
16
  "npm test -- <path> runs the full suite, not the path argument. Use scoped node --test path/to.test.mjs instead.";
17
17
 
18
+ /** Code tasks should chain project lint/analyze in Contract testCommand (post-mortem v2.15.0 F-C). */
19
+ export const TEST_COMMAND_LINT_MISSING_FIX_HINT =
20
+ "Prefix Contract testCommand with project lint/analyze (pi-spine: npm run lint &&). Docs-only testCommand: true is exempt.";
21
+
18
22
  const PATCH_TASK_SIZES = new Set(["S", "M"]);
23
+ const LINT_IN_TEST_COMMAND_RE = /\b(?:lint|eslint|analyze)\b/;
24
+
25
+ /**
26
+ * @param {string | null | undefined} testCommand
27
+ * @returns {boolean}
28
+ */
29
+ function testCommandIncludesLintOrAnalyze(testCommand) {
30
+ if (!testCommand || testCommand === "true") {
31
+ return true;
32
+ }
33
+ return LINT_IN_TEST_COMMAND_RE.test(testCommand);
34
+ }
19
35
 
20
36
  /** Matches `npm test --` followed by at least one path/token argument. */
21
37
  export const NPM_TEST_DASH_DASH_RE = /\bnpm\s+test\s+--\s+\S+/;
@@ -94,6 +110,33 @@ export function collectNpmTestDashDashWarnings(parsed, options = {}) {
94
110
  return [formatNpmTestDashDashIssue(taskSize)];
95
111
  }
96
112
 
113
+ /**
114
+ * Warn when code-task contracts omit project lint/analyze from testCommand (post-mortem v2.15.0 F-C).
115
+ *
116
+ * @param {ReturnType<import("./packet/parse-prompt.mjs").parseContract>} parsed
117
+ * @param {{ taskSize?: "S"|"M"|"L"|"XL"|null }} [options]
118
+ * @returns {string[]}
119
+ */
120
+ export function collectLintMissingWarnings(parsed, options = {}) {
121
+ const taskSize = options.taskSize ?? null;
122
+ if (taskSize !== "S" && taskSize !== "M" && taskSize !== "L") {
123
+ return [];
124
+ }
125
+
126
+ const testCommand = parsed?.testCommand;
127
+ if (!testCommand || testCommand === "true") {
128
+ return [];
129
+ }
130
+
131
+ if (testCommandIncludesLintOrAnalyze(testCommand)) {
132
+ return [];
133
+ }
134
+
135
+ return [
136
+ `Contract testCommand omits project lint/analyze on Size ${taskSize} code task. ${TEST_COMMAND_LINT_MISSING_FIX_HINT}`,
137
+ ];
138
+ }
139
+
97
140
  /**
98
141
  * Warn when S/M task contracts chain full-suite gates in testCommand.
99
142
  *
@@ -129,11 +172,13 @@ export function collectTestCommandScopeWarnings(parsed, options = {}) {
129
172
  );
130
173
  }
131
174
 
175
+ warnings.push(...collectLintMissingWarnings(parsed, { taskSize }));
132
176
  return warnings;
133
177
  }
134
178
 
135
179
  if (taskSize === "L") {
136
180
  warnings.push(...collectNpmTestDashDashWarnings(parsed, { taskSize, mode }));
181
+ warnings.push(...collectLintMissingWarnings(parsed, { taskSize }));
137
182
  }
138
183
 
139
184
  return warnings;