pi-spine 2.27.0 → 2.28.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 (71) hide show
  1. package/bin/spine-batch.mjs +46 -4
  2. package/bin/spine-tasks.mjs +1 -0
  3. package/bin/spine-worker-runner.mjs +17 -3
  4. package/package.json +1 -1
  5. package/skills/create-spine-tasks/SKILL.md +60 -33
  6. package/skills/create-spine-tasks/references/authoring-evidence.md +58 -0
  7. package/skills/create-spine-tasks/references/contract-template.md +52 -7
  8. package/skills/create-spine-tasks/references/prompt-template.md +77 -8
  9. package/skills/spine-release-operator/SKILL.md +43 -52
  10. package/skills/spine-release-operator/references/issue-intake-checklist.md +3 -1
  11. package/skills/spine-release-operator/references/pi-async-orchestration.md +13 -9
  12. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +8 -1
  13. package/skills/spine-release-operator/references/publish-recovery.md +62 -0
  14. package/src/batch/contract-task-start.mjs +23 -1
  15. package/src/batch/diagnosis-alternatives.mjs +16 -1
  16. package/src/batch/diagnosis-handoff-packet.mjs +18 -0
  17. package/src/batch/diagnosis-pending-lane.mjs +18 -0
  18. package/src/batch/diagnosis-review-infra.mjs +144 -0
  19. package/src/batch/diagnosis-suggested-command.mjs +9 -0
  20. package/src/batch/diagnosis.mjs +19 -20
  21. package/src/batch/engine-lanes/merge.mjs +0 -8
  22. package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
  23. package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
  24. package/src/batch/engine-lanes/review-code.mjs +20 -0
  25. package/src/batch/engine-lanes/review-final.mjs +10 -2
  26. package/src/batch/engine-lanes/review-poll.mjs +37 -1
  27. package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
  28. package/src/batch/engine-lanes.mjs +18 -18
  29. package/src/batch/gate-posture-approve.mjs +154 -15
  30. package/src/batch/integrate-path-delete.mjs +85 -0
  31. package/src/batch/integrate-worktree.mjs +20 -27
  32. package/src/batch/journal.mjs +5 -3
  33. package/src/batch/metrics-rollup.mjs +98 -4
  34. package/src/batch/metrics.mjs +134 -9
  35. package/src/batch/provider-quota.mjs +156 -7
  36. package/src/batch/quota-fallback.mjs +87 -6
  37. package/src/batch/reconcile-diagnosis.mjs +24 -77
  38. package/src/batch/resume-lane-reviews.mjs +11 -10
  39. package/src/batch/retry-profile.mjs +77 -0
  40. package/src/batch/retry.mjs +32 -1
  41. package/src/batch/review-artifacts.mjs +3 -2
  42. package/src/batch/review-level-effective.mjs +19 -0
  43. package/src/batch/review-spawn.mjs +12 -1
  44. package/src/batch/review-step-run.mjs +18 -2
  45. package/src/batch/review-step.mjs +1 -0
  46. package/src/batch/reviewer-provider-error.mjs +153 -0
  47. package/src/batch/worker-heartbeat.mjs +10 -2
  48. package/src/batch/worker-host.mjs +1 -1
  49. package/src/batch/worker-prompt.mjs +9 -7
  50. package/src/cli/deps.mjs +3 -2
  51. package/src/config/agent-model-resolve.mjs +144 -8
  52. package/src/config/cursor-rules/discover.mjs +38 -1
  53. package/src/config/model-family.mjs +60 -0
  54. package/src/config/preflight/discovery.mjs +1 -0
  55. package/src/config/settings-fields.mjs +11 -0
  56. package/src/config/spine-config-schema.mjs +87 -0
  57. package/src/doctor/agent-model-inherit.mjs +78 -1
  58. package/src/doctor/pi-extension-hooks.mjs +322 -0
  59. package/src/doctor/run-doctor-checks.mjs +18 -2
  60. package/src/metrics/quota-cli.mjs +16 -0
  61. package/src/metrics/quota-probes.mjs +228 -31
  62. package/src/metrics/quota-snapshot.mjs +21 -2
  63. package/src/planner/graph.mjs +7 -5
  64. package/src/planner/pending.mjs +2 -2
  65. package/src/planner/scope.mjs +3 -3
  66. package/src/tasks/packet/parse-prompt.mjs +47 -0
  67. package/src/tasks/packet/validate-prompt.mjs +167 -2
  68. package/src/tasks/validate-contract-warn.mjs +16 -0
  69. package/templates/agents/reviewer.md +3 -1
  70. package/templates/agents/worker.md +15 -19
  71. package/templates/spine-config.json +1 -1
@@ -3,7 +3,9 @@
3
3
  * Atomic task retry and skip (TP-017, PRD §18.5, FR-BATCH-09/10).
4
4
  */
5
5
 
6
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
6
7
  import { reconcileOrphanRunningState } from "./reconcile.mjs";
8
+ import { resolveRetryProfileOverride } from "./retry-profile.mjs";
7
9
  import {
8
10
  clearTaskFailureMetadata,
9
11
  countPendingSegments,
@@ -18,6 +20,7 @@ import {
18
20
  const RETRY_ALLOWED_PHASES = new Set(["paused", "failed"]);
19
21
  const RETRY_BLOCKED_PHASES = new Set(["running", "planning"]);
20
22
 
23
+ export { ESCALATION_ELIGIBLE_CLASSES, resolveRetryProfileOverride } from "./retry-profile.mjs";
21
24
 
22
25
  /**
23
26
  * Fail running tasks and clear dead engine/worker PIDs before retry/skip (#203 / SP-647).
@@ -201,8 +204,10 @@ export function detectSegmentDrift(state) {
201
204
  * @param {object} params
202
205
  * @param {string} params.projectRoot
203
206
  * @param {string} params.taskId
207
+ * @param {string|null} [params.profile] `--profile <name>`: run the retry on this profile (content/contract failures only).
208
+ * @param {boolean} [params.noEscalate] `--no-escalate`: skip `agents.escalatePolicy` for this retry.
204
209
  */
205
- export function retryTask({ projectRoot, taskId }) {
210
+ export function retryTask({ projectRoot, taskId, profile = null, noEscalate = false }) {
206
211
  const loadedBatch = loadMutableBatch(projectRoot);
207
212
  if (!loadedBatch.ok) return loadedBatch.result;
208
213
  const state = loadedBatch.state;
@@ -257,6 +262,24 @@ export function retryTask({ projectRoot, taskId }) {
257
262
  };
258
263
  }
259
264
 
265
+ // Classify before reset: `resetTaskForRetry` clears `exitReason` / `classification`.
266
+ const profileDecision = resolveRetryProfileOverride({
267
+ task,
268
+ config: loadSpineConfig(projectRoot).config,
269
+ profile,
270
+ noEscalate,
271
+ });
272
+ if (!profileDecision.ok) {
273
+ return {
274
+ ok: false,
275
+ exitCode: 1,
276
+ error: profileDecision.error,
277
+ output: profileDecision.output,
278
+ batchId: state.batchId,
279
+ taskId,
280
+ };
281
+ }
282
+
260
283
  const reset = resetTaskForRetry(state, taskId);
261
284
  if (!reset) {
262
285
  return {
@@ -267,6 +290,7 @@ export function retryTask({ projectRoot, taskId }) {
267
290
  batchId: state.batchId,
268
291
  };
269
292
  }
293
+ if (profileDecision.apply) task.profileOverride = profileDecision.profileOverride;
270
294
 
271
295
  // Matrix tasks (#230): succeeded rows carry over (never re-executed) and
272
296
  // canceled rows stay excluded — only failed rows re-enter the sweep.
@@ -294,6 +318,8 @@ export function retryTask({ projectRoot, taskId }) {
294
318
  taskId,
295
319
  previousClassification: reset.previousClassification,
296
320
  pendingSegments,
321
+ profileOverride: profileDecision.profileOverride,
322
+ escalation: profileDecision.escalation,
297
323
  ...(retriedRowIds.length > 0 ? { retriedRowIds } : {}),
298
324
  },
299
325
  });
@@ -317,6 +343,9 @@ export function retryTask({ projectRoot, taskId }) {
317
343
  if (retriedRowIds.length > 0) {
318
344
  output += `\n Matrix rows re-running: ${retriedRowIds.join(", ")} (succeeded rows carry over).`;
319
345
  }
346
+ if (profileDecision.escalation) {
347
+ output += `\n Profile override: ${profileDecision.profileOverride} (${profileDecision.escalation === "auto" ? "escalatePolicy" : "--profile"}).`;
348
+ }
320
349
  output += `\n → ${resumeHint}\n`;
321
350
 
322
351
  return {
@@ -326,6 +355,8 @@ export function retryTask({ projectRoot, taskId }) {
326
355
  taskId,
327
356
  pendingSegments,
328
357
  unblocked,
358
+ profileOverride: profileDecision.profileOverride,
359
+ escalation: profileDecision.escalation,
329
360
  ...(retriedRowIds.length > 0 ? { retriedRowIds } : {}),
330
361
  output,
331
362
  };
@@ -4,7 +4,8 @@ import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { detectOrphanedReviewStarted } from "./journal-rebuild.mjs";
6
6
  import { NESTED_REVIEW_SPAWN_REASON } from "./review-spawn.mjs";
7
- import { normalizeVerdict, parseReviewLevel, parseReviewVerdict } from "./review-shared.mjs";
7
+ import { normalizeVerdict, parseReviewVerdict } from "./review-shared.mjs";
8
+ import { effectiveReviewLevel } from "./review-level-effective.mjs";
8
9
  import { shouldUseReviewStub } from "./engine-lanes/review-stub.mjs";
9
10
 
10
11
  /**
@@ -13,7 +14,7 @@ import { shouldUseReviewStub } from "./engine-lanes/review-stub.mjs";
13
14
  export function readReviewLevel(taskFolder) {
14
15
  const promptPath = path.join(taskFolder, "PROMPT.md");
15
16
  if (!fs.existsSync(promptPath)) return 0;
16
- return parseReviewLevel(fs.readFileSync(promptPath, "utf-8"));
17
+ return effectiveReviewLevel(fs.readFileSync(promptPath, "utf-8"));
17
18
  }
18
19
 
19
20
  /**
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Effective review level for a task packet (SP-827 / #336).
3
+ *
4
+ * `**Type:** execute` packets run no reviewers (operator runbook §2.5), so
5
+ * their effective review level is 0 regardless of the declared level. `llm`
6
+ * packets return their declared level unchanged.
7
+ */
8
+
9
+ import { parsePrompt } from "../tasks/packet/parse-prompt.mjs";
10
+ import { parseReviewLevel } from "./review-shared.mjs";
11
+
12
+ /**
13
+ * @param {string} markdown PROMPT.md contents
14
+ * @returns {number}
15
+ */
16
+ export function effectiveReviewLevel(markdown) {
17
+ if (parsePrompt(markdown).type === "execute") return 0;
18
+ return parseReviewLevel(markdown);
19
+ }
@@ -108,6 +108,13 @@ function reviewerPiCommandExists(cmd) {
108
108
  }
109
109
 
110
110
  /**
111
+ * Build the argv for a reviewer `pi` spawn.
112
+ *
113
+ * SP-819 / #334: reviewers pass `-ne` (pi `--no-extensions`) by default so operator-installed
114
+ * pi extensions (e.g. context-rewriting hooks) cannot break review runs. Core tools are not
115
+ * extensions, so reviewers keep read/bash/write. `agents.reviewer.loadUserExtensions: true`
116
+ * opts back into user extensions.
117
+ *
111
118
  * @param {object} params
112
119
  */
113
120
  export function buildReviewerPiArgs({
@@ -122,7 +129,11 @@ export function buildReviewerPiArgs({
122
129
  const reviewerModel = resolveReviewerModelPin(config, reviewType);
123
130
  const reviewerThinking = resolveReviewerThinkingPin(config, reviewType);
124
131
 
125
- const piArgs = ["-p", "--no-session"];
132
+ const piArgs = [];
133
+ if (config?.agents?.reviewer?.loadUserExtensions !== true) {
134
+ piArgs.push("-ne");
135
+ }
136
+ piArgs.push("-p", "--no-session");
126
137
  if (reviewerAgentPath && fs.existsSync(reviewerAgentPath)) {
127
138
  piArgs.push("--append-system-prompt", reviewerAgentPath);
128
139
  }
@@ -6,6 +6,7 @@
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
+ import { resolveReviewerModelPin, resolveReviewerThinkingPin } from "../config/agent-model-resolve.mjs";
9
10
  import { readJournalEvents } from "./journal.mjs";
10
11
  import {
11
12
  ARTIFACT_READY_HONOR_REASON,
@@ -43,6 +44,10 @@ import {
43
44
  journalReviewEvent,
44
45
  writeStubReviewArtifact,
45
46
  } from "./review-step.mjs";
47
+ import {
48
+ classifyReviewerSpawnFailure,
49
+ providerErrorFields,
50
+ } from "./reviewer-provider-error.mjs";
46
51
 
47
52
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
48
53
  const PACKAGE_ROOT = path.resolve(__dirname, "../..");
@@ -123,11 +128,14 @@ export async function runStepReview({
123
128
  contractVerifyResult,
124
129
  });
125
130
 
131
+ // SP-834 (#355): effective reviewer of the (per-task) config; null means inherit.
126
132
  journalReviewEvent("review.started", journal, {
127
133
  stepNumber,
128
134
  reviewType,
129
135
  reviewLevel,
130
136
  artifactPath,
137
+ reviewerModel: resolveReviewerModelPin(config, reviewType),
138
+ reviewerThinking: resolveReviewerThinkingPin(config, reviewType),
131
139
  });
132
140
 
133
141
  const useStub =
@@ -290,6 +298,11 @@ export async function runStepReview({
290
298
  if (honoredRetry) return honoredRetry;
291
299
  }
292
300
 
301
+ // SP-820 / #334: classify the terminal attempt once, after the SP-814
302
+ // re-spawn loop. A set `reason` means a dedicated path (nested-spawn guard
303
+ // returned above; timeout keeps `review_timeout`) — those stay unchanged.
304
+ const providerError = spawnResult.reason ? null : classifyReviewerSpawnFailure(spawnResult);
305
+
293
306
  if (spawnResult.spawnFailed) {
294
307
  if (spawnResult.reason === NESTED_REVIEW_SPAWN_REASON) {
295
308
  return completeNestedReviewSpawnSkipped({
@@ -335,7 +348,8 @@ export async function runStepReview({
335
348
  error: spawnResult.error,
336
349
  spawnFailed: true,
337
350
  exitCode: spawnResult.exitCode,
338
- ...(spawnResult.reason ? { reason: spawnResult.reason } : {}),
351
+ ...(spawnResult.reason && !providerError ? { reason: spawnResult.reason } : {}),
352
+ ...providerErrorFields(providerError),
339
353
  ...diagnostics,
340
354
  });
341
355
  return {
@@ -348,7 +362,7 @@ export async function runStepReview({
348
362
  spawnFailed: true,
349
363
  error: spawnResult.error,
350
364
  exitCode: spawnResult.exitCode ?? 1,
351
- reason: spawnResult.reason,
365
+ ...(providerError ? providerErrorFields(providerError) : { reason: spawnResult.reason }),
352
366
  ...diagnostics,
353
367
  };
354
368
  }
@@ -378,6 +392,7 @@ export async function runStepReview({
378
392
  error,
379
393
  spawnFailed: true,
380
394
  exitCode: spawnResult.exitCode ?? 0,
395
+ ...providerErrorFields(providerError),
381
396
  ...diagnostics,
382
397
  });
383
398
  return {
@@ -390,6 +405,7 @@ export async function runStepReview({
390
405
  spawnFailed: true,
391
406
  error,
392
407
  exitCode: 1,
408
+ ...providerErrorFields(providerError),
393
409
  ...diagnostics,
394
410
  };
395
411
  }
@@ -140,6 +140,7 @@ export function buildReviewRequest({
140
140
  "## Output",
141
141
  `Write your review to: \`${outputPath}\``,
142
142
  "Include `### Verdict: PASS`, `### Verdict: REVISE`, or `### Verdict: REPLAN` and a JSON block.",
143
+ 'Final verdicts are PASS, REVISE, or REPLAN only — APPROVE is rejected. JSON shape: `{"verdict":"PASS","feedback":"..."}`',
143
144
  ].join("\n");
144
145
  }
145
146
  if (reviewType === "plan") {
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Pure classifier for provider request errors in reviewer output
3
+ * (SP-820, partial #334).
4
+ *
5
+ * When the reviewer's model provider rejects the request — Gemini HTTP 400
6
+ * `INVALID_ARGUMENT` ("Function call is missing a thought_signature") or a
7
+ * `MALFORMED_FUNCTION_CALL` finish reason — the reviewer exits non-zero, or
8
+ * exits 0 without writing the review artifact. Both used to collapse into the
9
+ * generic `${reviewType}_review_spawn_failed` exit reason, indistinguishable
10
+ * from a missing `pi` binary or an empty model turn. This module recognizes
11
+ * the provider payload shapes and reports the provider's message so the
12
+ * journal records *why* the reviewer died.
13
+ *
14
+ * Quota exhaustion (HTTP 429 / z.ai `1308` / Kimi usage limits) keeps its own
15
+ * path: `classifyReviewerProviderError` returns null whenever
16
+ * `classifyProviderQuotaError` matches, so quota output is never relabelled.
17
+ */
18
+ import {
19
+ classifyProviderQuotaError,
20
+ collectStatusPayloads,
21
+ } from "./provider-quota.mjs";
22
+
23
+ /** `reason` carried by the `review.failed` payload and the review result. */
24
+ export const REVIEW_PROVIDER_ERROR_REASON = "review_provider_error";
25
+
26
+ /** Provider messages can embed long request dumps; keep a bounded slice. */
27
+ const MAX_PROVIDER_MESSAGE_LENGTH = 500;
28
+
29
+ /**
30
+ * Markers that identify a provider request error even without a
31
+ * status-prefixed JSON payload (plain-text stdout/stderr from pi, or a
32
+ * finishReason inside a larger JSON chunk).
33
+ */
34
+ const PROVIDER_ERROR_MARKERS = [
35
+ "INVALID_ARGUMENT",
36
+ "thought_signature",
37
+ "MALFORMED_FUNCTION_CALL",
38
+ ];
39
+
40
+ /**
41
+ * @param {string} message
42
+ * @returns {string}
43
+ */
44
+ function truncateProviderMessage(message) {
45
+ return message.length > MAX_PROVIDER_MESSAGE_LENGTH
46
+ ? message.slice(0, MAX_PROVIDER_MESSAGE_LENGTH)
47
+ : message;
48
+ }
49
+
50
+ /**
51
+ * Extracts the provider's message text from a parsed status payload:
52
+ * nested `error.message` (Gemini/Kimi envelope) or flat `message` (z.ai).
53
+ *
54
+ * @param {Record<string, any>} payload
55
+ * @returns {string|null}
56
+ */
57
+ function payloadProviderMessage(payload) {
58
+ const error = payload?.error && typeof payload.error === "object" ? payload.error : null;
59
+ if (typeof error?.message === "string" && error.message.trim()) return error.message.trim();
60
+ if (typeof payload?.message === "string" && payload.message.trim()) return payload.message.trim();
61
+ return null;
62
+ }
63
+
64
+ /**
65
+ * Finds the first output line containing a provider error marker, trimmed
66
+ * and capped — the provider message for marker-only matches.
67
+ *
68
+ * @param {string} output
69
+ * @returns {string|null}
70
+ */
71
+ function markerLine(output) {
72
+ for (const line of output.split("\n")) {
73
+ if (PROVIDER_ERROR_MARKERS.some((marker) => line.includes(marker))) {
74
+ return truncateProviderMessage(line.trim());
75
+ }
76
+ }
77
+ return null;
78
+ }
79
+
80
+ /**
81
+ * Classifies a provider request error in raw reviewer output. Pure: no I/O,
82
+ * no clocks, no configuration reads.
83
+ *
84
+ * Match rules (SP-820 / #334):
85
+ * - any status-prefixed JSON payload with an HTTP 4xx status other than
86
+ * 408 (request timeout) and 429 (rate limit — quota's own path), or
87
+ * - any of the markers `INVALID_ARGUMENT`, `thought_signature`,
88
+ * `MALFORMED_FUNCTION_CALL` anywhere in the output.
89
+ *
90
+ * Returns null when `classifyProviderQuotaError(output)` matches (quota
91
+ * keeps its own handling), and for empty or non-string input. When several
92
+ * payloads qualify, the last one is classified — it is the terminal error
93
+ * the reviewer actually died on.
94
+ *
95
+ * @param {string|null|undefined} output Reviewer error text / redacted output tails.
96
+ * @returns {{ httpStatus: number|null, providerMessage: string }|null}
97
+ */
98
+ export function classifyReviewerProviderError(output) {
99
+ if (typeof output !== "string" || !output) return null;
100
+ if (classifyProviderQuotaError(output)) return null;
101
+
102
+ const payloads = collectStatusPayloads(output);
103
+ for (let i = payloads.length - 1; i >= 0; i--) {
104
+ const { httpStatus, payload } = payloads[i];
105
+ if (httpStatus >= 400 && httpStatus < 500 && httpStatus !== 408 && httpStatus !== 429) {
106
+ return {
107
+ httpStatus,
108
+ providerMessage: truncateProviderMessage(
109
+ // The message must describe THIS payload — an unrelated earlier
110
+ // marker line must not be attributed to the terminal 4xx. The
111
+ // raw payload text is the faithful fallback (stet 3295372).
112
+ payloadProviderMessage(payload) ?? JSON.stringify(payload),
113
+ ),
114
+ };
115
+ }
116
+ }
117
+
118
+ const marker = markerLine(output);
119
+ if (marker) return { httpStatus: null, providerMessage: marker };
120
+ return null;
121
+ }
122
+
123
+ /**
124
+ * SP-820 fields added to the `review.failed` payload and the returned review
125
+ * result when the terminal attempt matched the classifier. Empty for generic
126
+ * failures, quota payloads (their own path), and timeouts.
127
+ *
128
+ * @param {{ httpStatus: number|null, providerMessage: string }|null} providerError
129
+ * @returns {Record<string, any>}
130
+ */
131
+ export function providerErrorFields(providerError) {
132
+ if (!providerError) return {};
133
+ return {
134
+ reason: REVIEW_PROVIDER_ERROR_REASON,
135
+ providerMessage: providerError.providerMessage,
136
+ ...(typeof providerError.httpStatus === "number" ? { httpStatus: providerError.httpStatus } : {}),
137
+ };
138
+ }
139
+
140
+ /**
141
+ * Runs the classifier over a reviewer spawn attempt's error text and redacted
142
+ * output tails, joined in failure-order (error, stderr, stdout). Quota
143
+ * payloads anywhere in the combined text keep the generic path.
144
+ *
145
+ * @param {{ error?: string, stderrTail?: string, stdoutTail?: string }|null|undefined} spawnResult
146
+ * @returns {{ httpStatus: number|null, providerMessage: string }|null}
147
+ */
148
+ export function classifyReviewerSpawnFailure(spawnResult) {
149
+ const combined = [spawnResult?.error, spawnResult?.stderrTail, spawnResult?.stdoutTail]
150
+ .filter((part) => typeof part === "string" && part)
151
+ .join("\n");
152
+ return classifyReviewerProviderError(combined);
153
+ }
@@ -110,7 +110,8 @@ export function createWorkerPollState(startedAt, workerPhase) {
110
110
  * @param {string} [params.laneCorrelationId]
111
111
  * @param {boolean} params.useStub
112
112
  * @param {string} params.workerBackend
113
- * @param {boolean} params.childPastPreflight
113
+ * @param {boolean} [params.childPastPreflight] Static snapshot of preflight state; kept for existing callers.
114
+ * @param {() => boolean} [params.isPastPreflight] Live preflight getter read on every poll (#353); wins over `childPastPreflight`.
114
115
  * @param {(timestamp: number) => void} [params.onHeartbeat]
115
116
  * @param {(failure: {
116
117
  * rawOutput: string;
@@ -147,6 +148,7 @@ export async function pollWorkerUntilSettled({
147
148
  useStub,
148
149
  workerBackend,
149
150
  childPastPreflight,
151
+ isPastPreflight,
150
152
  onHeartbeat,
151
153
  buildFailureResult,
152
154
  workerMode,
@@ -240,7 +242,13 @@ export async function pollWorkerUntilSettled({
240
242
  : undefined,
241
243
  }),
242
244
  );
243
- const nextWorkerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
245
+ const pastPreflight =
246
+ typeof isPastPreflight === "function" ? isPastPreflight() : Boolean(childPastPreflight);
247
+ const nextWorkerPhase = resolveWorkerPhase({
248
+ childPastPreflight: pastPreflight,
249
+ useStub,
250
+ workerBackend,
251
+ });
244
252
  if (nextWorkerPhase !== "launching" && workerPhase === "launching") {
245
253
  stallAnchorAt = now;
246
254
  lastCheckpointAt = now;
@@ -363,7 +363,7 @@ export async function runWorker({
363
363
  laneCorrelationId,
364
364
  useStub,
365
365
  workerBackend,
366
- childPastPreflight,
366
+ isPastPreflight: () => childPastPreflight,
367
367
  onHeartbeat,
368
368
  workerMode,
369
369
  buildFailureResult: (
@@ -13,16 +13,15 @@ export function buildReviewLevelHint(reviewLevel) {
13
13
  return "";
14
14
  }
15
15
  let hint =
16
- "When Review Level ≥ 1, run plan review only at step checkpoints: spine review step --step N --type plan (or spine_review_step with type=plan). ";
16
+ "Reviews run in the batch engine after .DONE, not in the worker: do not call spine_review_step or spine review step from the worker. ";
17
17
  if (reviewLevel >= 2) {
18
18
  hint +=
19
- "Do not run code or final review from inside the worker — the batch engine runs those after .DONE. ";
19
+ "At Review Level 2 the engine runs plan review, code review, and final review after .DONE. ";
20
20
  } else {
21
- hint +=
22
- "Do not run final review from the worker — the batch engine runs final review after .DONE. ";
21
+ hint += "At Review Level 1 the engine runs plan review and final review after .DONE. ";
23
22
  }
24
23
  hint +=
25
- "On REVISE, fix feedback before continuing. On review spawn failure, stop with non-zero exit. After creating .DONE, exit immediately with no further tool calls or reviewer spawns. ";
24
+ "If the engine returns REVISE feedback, address it when resumed. After creating .DONE, exit immediately with no further tool calls or reviewer spawns. ";
26
25
  return hint;
27
26
  }
28
27
 
@@ -48,6 +47,7 @@ export async function buildWorkerTailPrompt({
48
47
  taskIdHint = taskIdFromFolder(taskFolder),
49
48
  reviewLevel = 0,
50
49
  includePromptInclude = false,
50
+ includeAgentInclude = true,
51
51
  config = {},
52
52
  projectRoot = worktreePath || process.cwd(),
53
53
  taskFileScope = [],
@@ -58,7 +58,9 @@ export async function buildWorkerTailPrompt({
58
58
  : null;
59
59
  const promptPath = path.join(taskFolder, "PROMPT.md");
60
60
  const agentAppend =
61
- workerAgentPath && fs.existsSync(workerAgentPath) ? `\n\n@${workerAgentPath}` : "";
61
+ includeAgentInclude && workerAgentPath && fs.existsSync(workerAgentPath)
62
+ ? `\n\n@${workerAgentPath}`
63
+ : "";
62
64
  const promptInclude =
63
65
  includePromptInclude && fs.existsSync(promptPath) ? `\n\n@${promptPath}` : "";
64
66
 
@@ -70,7 +72,7 @@ export async function buildWorkerTailPrompt({
70
72
  });
71
73
 
72
74
  return (
73
- `Complete this task in the worktree (${worktreePath || "."}). Follow PROMPT.md, keep STATUS.md current, run npm test. ` +
75
+ `Complete this task in the worktree (${worktreePath || "."}). Follow PROMPT.md, keep STATUS.md current, and run the Contract testCommand from PROMPT.md; the full suite runs at post-integrate release:check. ` +
74
76
  WORKER_TOOLS_HINT +
75
77
  buildReviewLevelHint(reviewLevel) +
76
78
  buildCommitBoundaryHint(taskIdHint) +
package/src/cli/deps.mjs CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  import { buildGraph, topoWaves } from '../planner/graph.mjs';
13
13
  import { findCyclePath } from '../planner/cycles.mjs';
14
14
  import { parseScope } from '../planner/scope.mjs';
15
+ import { compareTaskIds } from '../tasks/packet/discover.mjs';
15
16
 
16
17
  /**
17
18
  * @param {string} projectRoot
@@ -42,7 +43,7 @@ export function depsToEdges(depsByTask) {
42
43
  }
43
44
  }
44
45
 
45
- edges.sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to));
46
+ edges.sort((a, b) => compareTaskIds(a.from, b.from) || compareTaskIds(a.to, b.to));
46
47
  return edges;
47
48
  }
48
49
 
@@ -55,7 +56,7 @@ export function cycleNodesFromPath(cyclePath) {
55
56
  const nodes = cyclePath[cyclePath.length - 1] === cyclePath[0]
56
57
  ? cyclePath.slice(0, -1)
57
58
  : cyclePath;
58
- return [...new Set(nodes.map(String))].sort();
59
+ return [...new Set(nodes.map(String))].sort(compareTaskIds);
59
60
  }
60
61
 
61
62
  /**