pi-spine 2.26.0 → 2.27.1

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 (63) hide show
  1. package/README.md +1 -1
  2. package/bin/spine-review-step.mjs +8 -1
  3. package/bin/spine-worker-runner.mjs +15 -1
  4. package/package.json +3 -3
  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 +72 -8
  9. package/skills/spine-release-operator/SKILL.md +33 -51
  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/batch-meta-reconstruct.mjs +3 -0
  15. package/src/batch/contract-exec.mjs +2 -2
  16. package/src/batch/contract-parse.mjs +2 -2
  17. package/src/batch/contract-prelanded.mjs +2 -2
  18. package/src/batch/diagnosis-alternatives.mjs +16 -1
  19. package/src/batch/diagnosis-handoff-packet.mjs +74 -0
  20. package/src/batch/diagnosis-pending-lane.mjs +52 -1
  21. package/src/batch/diagnosis-review-infra.mjs +144 -0
  22. package/src/batch/diagnosis-suggested-command.mjs +9 -0
  23. package/src/batch/diagnosis.mjs +19 -20
  24. package/src/batch/engine-lanes/merge.mjs +0 -8
  25. package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
  26. package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
  27. package/src/batch/engine-lanes/review-code.mjs +1 -0
  28. package/src/batch/engine-lanes/review-final.mjs +83 -46
  29. package/src/batch/engine-lanes/review-plan.mjs +22 -2
  30. package/src/batch/engine-lanes/review-poll.mjs +51 -2
  31. package/src/batch/engine-lanes.mjs +6 -8
  32. package/src/batch/gate-posture-approve.mjs +154 -15
  33. package/src/batch/integrate-path-delete.mjs +85 -0
  34. package/src/batch/integrate-worktree.mjs +20 -27
  35. package/src/batch/journal.mjs +15 -0
  36. package/src/batch/metrics.mjs +13 -1
  37. package/src/batch/provider-quota.mjs +220 -0
  38. package/src/batch/quota-fallback.mjs +319 -0
  39. package/src/batch/reconcile-diagnosis-context.mjs +22 -0
  40. package/src/batch/reconcile-diagnosis.mjs +24 -77
  41. package/src/batch/resume-multi-queue.mjs +25 -10
  42. package/src/batch/review-artifacts.mjs +96 -17
  43. package/src/batch/review-level-effective.mjs +19 -0
  44. package/src/batch/review-spawn-retry.mjs +106 -0
  45. package/src/batch/review-spawn.mjs +60 -3
  46. package/src/batch/review-step-run.mjs +110 -8
  47. package/src/batch/reviewer-output.mjs +162 -0
  48. package/src/batch/reviewer-provider-error.mjs +153 -0
  49. package/src/batch/worker-host.mjs +49 -3
  50. package/src/batch/worker-prompt.mjs +5 -2
  51. package/src/config/cursor-rules/discover.mjs +40 -3
  52. package/src/config/cursor-rules/match-globs.mjs +6 -4
  53. package/src/config/env-overrides.mjs +41 -4
  54. package/src/config/settings-fields.mjs +11 -0
  55. package/src/config/spine-config-schema.mjs +62 -0
  56. package/src/doctor/pi-extension-hooks.mjs +322 -0
  57. package/src/doctor/quota-risk.mjs +45 -0
  58. package/src/doctor/run-doctor-checks.mjs +14 -1
  59. package/src/planner/file-scope.mjs +6 -6
  60. package/src/tasks/packet/validate-contract.mjs +3 -3
  61. package/src/tasks/packet/validate-prompt.mjs +11 -1
  62. package/src/tasks/validate-contract-warn.mjs +16 -0
  63. package/templates/spine-config.json +1 -1
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Reviewer output log persistence (SP-814 / #332).
3
+ *
4
+ * Every failed reviewer attempt leaves a bounded, redacted log next to the
5
+ * worker output logs under `.spine/runtime/<batchId>/lanes/lane-<n>/`. The
6
+ * helpers reuse the worker output conventions from `worker-output.mjs`
7
+ * (redaction, tail caps, atomic writes) without modifying that module, which
8
+ * sits at its line-count policy cap.
9
+ */
10
+
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ import { writeTextAtomic } from "../fs/atomic-write.mjs";
14
+ import {
15
+ captureWorkerOutputTail,
16
+ redactWorkerOutput,
17
+ resolveWorkerOutputConfig,
18
+ } from "./worker-output.mjs";
19
+
20
+ /** Diagnostic output tail budget for `review.failed` payloads (SP-814 / #332). */
21
+ export const REVIEWER_FAILURE_OUTPUT_TAIL_MAX_BYTES = 2048;
22
+
23
+ /**
24
+ * Shape of the `spawnReviewerPi` result consumed by the log helpers.
25
+ *
26
+ * @typedef {object} ReviewerSpawnResult
27
+ * @property {boolean} [spawnFailed]
28
+ * @property {number} [exitCode]
29
+ * @property {number} [durationMs]
30
+ * @property {string} [stdoutTail]
31
+ * @property {string} [stderrTail]
32
+ */
33
+
34
+ /**
35
+ * Absolute path of the reviewer output log for one (task, reviewType) pair.
36
+ *
37
+ * @param {string} projectRoot
38
+ * @param {string} batchId
39
+ * @param {number} laneNumber
40
+ * @param {string} taskId
41
+ * @param {string} reviewType
42
+ */
43
+ export function reviewerOutputLogPath(projectRoot, batchId, laneNumber, taskId, reviewType) {
44
+ return path.join(
45
+ projectRoot,
46
+ ".spine",
47
+ "runtime",
48
+ batchId,
49
+ "lanes",
50
+ `lane-${laneNumber}`,
51
+ `reviewer-output-${taskId}-${reviewType}.log`,
52
+ );
53
+ }
54
+
55
+ /**
56
+ * Root-relative journal/log reference for the reviewer output log.
57
+ *
58
+ * @param {string} batchId
59
+ * @param {number} laneNumber
60
+ * @param {string} taskId
61
+ * @param {string} reviewType
62
+ */
63
+ export function reviewerOutputLogRef(batchId, laneNumber, taskId, reviewType) {
64
+ return path.join(
65
+ ".spine",
66
+ "runtime",
67
+ batchId,
68
+ "lanes",
69
+ `lane-${laneNumber}`,
70
+ `reviewer-output-${taskId}-${reviewType}.log`,
71
+ );
72
+ }
73
+
74
+ /**
75
+ * Combined stderr + stdout diagnostic tail (redacted, ≤ 2 KB) for failure
76
+ * payloads. Stderr leads because reviewer diagnostics conventionally land
77
+ * there; stdout follows so silent reviewer exits stay explainable.
78
+ *
79
+ * @param {ReviewerSpawnResult} spawnResult Result from `spawnReviewerPi`.
80
+ * @param {object} [config]
81
+ */
82
+ export function buildReviewerOutputTail(spawnResult, config = {}) {
83
+ const outputConfig = resolveWorkerOutputConfig(config);
84
+ const stderrTail = redactWorkerOutput(spawnResult?.stderrTail ?? "", outputConfig).trim();
85
+ const stdoutTail = redactWorkerOutput(spawnResult?.stdoutTail ?? "", outputConfig).trim();
86
+
87
+ const parts = [];
88
+ if (stderrTail) parts.push(`--- stderr ---\n${stderrTail}`);
89
+ if (stdoutTail) parts.push(`--- stdout ---\n${stdoutTail}`);
90
+ const joined = parts.join("\n");
91
+ if (!joined) return "";
92
+
93
+ const tailConfig = { ...outputConfig, maxBytes: REVIEWER_FAILURE_OUTPUT_TAIL_MAX_BYTES };
94
+ return captureWorkerOutputTail(joined, tailConfig);
95
+ }
96
+
97
+ /**
98
+ * Append one redacted, tail-capped attempt section to the reviewer log for a
99
+ * (task, reviewType) pair. One file per pair: attempts append so a re-spawn
100
+ * never erases the previous attempt's diagnostics.
101
+ *
102
+ * @param {object} params
103
+ * @param {string} params.projectRoot
104
+ * @param {string} params.batchId
105
+ * @param {number} params.laneNumber
106
+ * @param {string} params.taskId
107
+ * @param {string} params.reviewType
108
+ * @param {number|null} [params.stepNumber]
109
+ * @param {number} [params.attempt]
110
+ * @param {ReviewerSpawnResult} [params.spawnResult] Result from `spawnReviewerPi`.
111
+ * @param {object} [params.config]
112
+ * @returns {{ logPath: string, logRef: string }|null}
113
+ */
114
+ export function persistReviewerOutputLog({
115
+ projectRoot,
116
+ batchId,
117
+ laneNumber,
118
+ taskId,
119
+ reviewType,
120
+ stepNumber = null,
121
+ attempt = 1,
122
+ spawnResult = {},
123
+ config = {},
124
+ }) {
125
+ const outputConfig = resolveWorkerOutputConfig(config);
126
+ const stderrTail = captureWorkerOutputTail(
127
+ redactWorkerOutput(spawnResult.stderrTail ?? "", outputConfig),
128
+ outputConfig,
129
+ );
130
+ const stdoutTail = captureWorkerOutputTail(
131
+ redactWorkerOutput(spawnResult.stdoutTail ?? "", outputConfig),
132
+ outputConfig,
133
+ );
134
+
135
+ const header = [
136
+ `# reviewer attempt ${attempt} — ${new Date().toISOString()}`,
137
+ `taskId=${taskId} reviewType=${reviewType} step=${stepNumber ?? "?"}`,
138
+ `spawnFailed=${spawnResult.spawnFailed === true} exitCode=${
139
+ spawnResult.exitCode ?? "null"
140
+ } durationMs=${spawnResult.durationMs ?? "null"}`,
141
+ ].join("\n");
142
+ const section = [
143
+ header,
144
+ "--- stderr ---",
145
+ stderrTail.trim() || "(empty)",
146
+ "--- stdout ---",
147
+ stdoutTail.trim() || "(empty)",
148
+ ].join("\n");
149
+
150
+ const logPath = reviewerOutputLogPath(projectRoot, batchId, laneNumber, taskId, reviewType);
151
+ let previous = "";
152
+ if (fs.existsSync(logPath)) {
153
+ previous = fs.readFileSync(logPath, "utf-8").trim();
154
+ }
155
+ const content = previous ? `${previous}\n\n${section}\n` : `${section}\n`;
156
+ writeTextAtomic(logPath, content);
157
+
158
+ return {
159
+ logPath,
160
+ logRef: reviewerOutputLogRef(batchId, laneNumber, taskId, reviewType),
161
+ };
162
+ }
@@ -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
+ }
@@ -12,6 +12,8 @@ import {
12
12
  } from "./task-stall-budget.mjs";
13
13
  import { parseContract, parsePrompt } from "../tasks/packet/parse-prompt.mjs";
14
14
  import { appendJournalEvent } from "./journal.mjs";
15
+ import { classifyProviderQuotaError } from "./provider-quota.mjs";
16
+ import { resolveWorkerQuotaFallbackContext } from "./engine-lanes/quota-fallback-state.mjs";
15
17
  import { assertReviewToolAvailable } from "./review.mjs";
16
18
  import {
17
19
  finalizeWorkerOutput,
@@ -49,6 +51,36 @@ const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
49
51
  */
50
52
  const WORKER_TIMEOUT_EXIT_CODE = 124;
51
53
 
54
+ /**
55
+ * Reclassify a plain `failed` worker exit as a provider quota/overload exit
56
+ * when forwarded output matches a known provider payload, and journal
57
+ * `worker.quota_exhausted` for quota-exhausted exits (#329, SP-806). Aborted,
58
+ * stall, launch and review failures keep their meaning; overload is not
59
+ * journaled. Callers must run this after finalizeWorkerOutput so output
60
+ * capture still sees the original `failed` (shouldCaptureWorkerOutput matches
61
+ * the literal) while consumers receive the provider-quota exit reason.
62
+ *
63
+ * @param {{ classification: string, rawOutput: string, workerModel?: string, projectRoot?: string, batchId?: string, taskId?: string, laneNumber?: number, laneCorrelationId?: string }} params
64
+ * @returns {{ classification: string, providerQuota: import("./provider-quota.mjs").ProviderQuotaError | null }}
65
+ */
66
+ function applyProviderQuotaClassification({ classification, rawOutput, workerModel, projectRoot, batchId, taskId, laneNumber, laneCorrelationId }) {
67
+ if (classification !== "failed") return { classification, providerQuota: null };
68
+ // SP-808 (#329): the caller resolves the effective model (fallback profile
69
+ // when a hop is active) so classification and the journal tell the truth.
70
+ const model = typeof workerModel === "string" ? workerModel : undefined;
71
+ const providerQuota = classifyProviderQuotaError(rawOutput, model);
72
+ if (!providerQuota) return { classification, providerQuota: null };
73
+ if (providerQuota.kind === "quota_exhausted" && projectRoot && batchId) {
74
+ appendJournalEvent(projectRoot, batchId, "worker.quota_exhausted", {
75
+ taskId, laneNumber, correlationId: laneCorrelationId, poolId: providerQuota.poolId,
76
+ providerCode: providerQuota.providerCode, httpStatus: providerQuota.httpStatus,
77
+ resetAtRaw: providerQuota.resetAtRaw, ...(model ? { model } : {}),
78
+ });
79
+ }
80
+ const reclassified = providerQuota.kind === "quota_exhausted" ? "provider_quota_exhausted" : "provider_overloaded";
81
+ return { classification: reclassified, providerQuota };
82
+ }
83
+
52
84
  /**
53
85
  * Force-terminate lane worker process trees tracked in batch state.
54
86
  * Reaps nested `pi` grandchildren, not only the tracked runner PID (SP-609 / #194).
@@ -99,6 +131,7 @@ function sleep(ms) {
99
131
  * @param {string} [params.taskId]
100
132
  * @param {string} [params.laneCorrelationId]
101
133
  * @param {object} [params.config]
134
+ * @param {string} [params.workerModel] Effective worker model (SP-808).
102
135
  * @param {number} [params.stallDeadline]
103
136
  * @param {object} [params.signals]
104
137
  */
@@ -114,6 +147,7 @@ function buildWorkerFailureResult({
114
147
  taskId,
115
148
  laneCorrelationId,
116
149
  config,
150
+ workerModel,
117
151
  stallDeadline,
118
152
  signals,
119
153
  }) {
@@ -131,6 +165,8 @@ function buildWorkerFailureResult({
131
165
  signals,
132
166
  config,
133
167
  });
168
+ // SP-806 (#329): post-finalize reclassification (see helper doc).
169
+ const quotaOutcome = applyProviderQuotaClassification({ classification, rawOutput, workerModel, projectRoot, batchId, taskId, laneNumber, laneCorrelationId });
134
170
  return {
135
171
  ok: false,
136
172
  exitCode,
@@ -138,8 +174,9 @@ function buildWorkerFailureResult({
138
174
  output: finalized.output,
139
175
  workerOutputLogPath: finalized.logPath,
140
176
  workerOutputLogRef: finalized.logRef,
141
- classification,
177
+ classification: quotaOutcome.classification,
142
178
  doneFound,
179
+ ...(quotaOutcome.providerQuota ? { providerQuota: quotaOutcome.providerQuota } : {}),
143
180
  };
144
181
  }
145
182
 
@@ -183,6 +220,9 @@ export async function runWorker({
183
220
  return { ok: true, exitCode: 0, mode: "already-done" };
184
221
  }
185
222
 
223
+ // SP-808 (#329): sticky quota fallback — read-only load; caller extraEnv wins.
224
+ const quotaCtx = resolveWorkerQuotaFallbackContext({ projectRoot, batchId, config, extraEnv });
225
+
186
226
  const stubExplicit =
187
227
  process.env.SPINE_WORKER_STUB === "1" || process.env.SPINE_WORKER_STUB === "true";
188
228
  // #299 (SP-801): the stub is opt-in only. The old implicit fallback
@@ -284,7 +324,7 @@ export async function runWorker({
284
324
  fileScopePaths,
285
325
  config,
286
326
  workerBackendDeps,
287
- extraEnv,
327
+ extraEnv: quotaCtx.extraEnv,
288
328
  });
289
329
  const workerChild = /** @type {WorkerChildHandle} */ (child);
290
330
  let childPastPreflight = isExecute ? true : !useLaunchScript;
@@ -337,6 +377,7 @@ export async function runWorker({
337
377
  taskId,
338
378
  laneCorrelationId,
339
379
  config,
380
+ workerModel: quotaCtx.workerModel,
340
381
  }),
341
382
  });
342
383
 
@@ -389,6 +430,7 @@ export async function runWorker({
389
430
  taskId,
390
431
  laneCorrelationId,
391
432
  config,
433
+ workerModel: quotaCtx.workerModel,
392
434
  });
393
435
  }
394
436
  // SP-738 (#273): the runner exits 124 when the `pi` spawn hit its wall-clock
@@ -440,6 +482,9 @@ export async function runWorker({
440
482
  config,
441
483
  });
442
484
 
485
+ // SP-806 (#329): main post-spawn failure path — post-finalize
486
+ // reclassification (see helper doc); only plain `failed` exits can match.
487
+ const quotaOutcome = applyProviderQuotaClassification({ classification, rawOutput: output, workerModel: quotaCtx.workerModel, projectRoot, batchId, taskId, laneNumber, laneCorrelationId });
443
488
  return {
444
489
  ok,
445
490
  exitCode,
@@ -447,7 +492,8 @@ export async function runWorker({
447
492
  output: finalized.output,
448
493
  workerOutputLogPath: finalized.logPath,
449
494
  workerOutputLogRef: finalized.logRef,
450
- classification,
495
+ classification: quotaOutcome.classification,
451
496
  doneFound,
497
+ ...(quotaOutcome.providerQuota ? { providerQuota: quotaOutcome.providerQuota } : {}),
452
498
  };
453
499
  }
@@ -48,6 +48,7 @@ export async function buildWorkerTailPrompt({
48
48
  taskIdHint = taskIdFromFolder(taskFolder),
49
49
  reviewLevel = 0,
50
50
  includePromptInclude = false,
51
+ includeAgentInclude = true,
51
52
  config = {},
52
53
  projectRoot = worktreePath || process.cwd(),
53
54
  taskFileScope = [],
@@ -58,7 +59,9 @@ export async function buildWorkerTailPrompt({
58
59
  : null;
59
60
  const promptPath = path.join(taskFolder, "PROMPT.md");
60
61
  const agentAppend =
61
- workerAgentPath && fs.existsSync(workerAgentPath) ? `\n\n@${workerAgentPath}` : "";
62
+ includeAgentInclude && workerAgentPath && fs.existsSync(workerAgentPath)
63
+ ? `\n\n@${workerAgentPath}`
64
+ : "";
62
65
  const promptInclude =
63
66
  includePromptInclude && fs.existsSync(promptPath) ? `\n\n@${promptPath}` : "";
64
67
 
@@ -70,7 +73,7 @@ export async function buildWorkerTailPrompt({
70
73
  });
71
74
 
72
75
  return (
73
- `Complete this task in the worktree (${worktreePath || "."}). Follow PROMPT.md, keep STATUS.md current, run npm test. ` +
76
+ `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
77
  WORKER_TOOLS_HINT +
75
78
  buildReviewLevelHint(reviewLevel) +
76
79
  buildCommitBoundaryHint(taskIdHint) +
@@ -7,7 +7,7 @@ import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { execFileSync } from "node:child_process";
9
9
 
10
- import micromatch from "micromatch";
10
+ import picomatch from "picomatch";
11
11
 
12
12
  import { writeJsonAtomic } from "../../fs/atomic-write.mjs";
13
13
 
@@ -97,7 +97,7 @@ export function getCursorRuleExclusionReason(discovery, relPath) {
97
97
  }
98
98
 
99
99
  for (const target of matchTargets) {
100
- if (micromatch.isMatch(target, discovery.excludePatterns)) {
100
+ if (picomatch(discovery.excludePatterns)(target)) {
101
101
  return "excludePattern";
102
102
  }
103
103
  }
@@ -181,6 +181,31 @@ export function writeRulesManifestAtomic(projectRoot, manifest) {
181
181
  return manifestPath;
182
182
  }
183
183
 
184
+ /**
185
+ * Read an existing rules manifest for fingerprint comparison. Returns null when
186
+ * the file is missing, unreadable, or not a parseable manifest — the caller then
187
+ * falls through to a normal write.
188
+ *
189
+ * @param {string} manifestPath
190
+ * @returns {CursorRulesManifest | null}
191
+ */
192
+ function loadExistingManifestForFingerprint(manifestPath) {
193
+ try {
194
+ const parsed = parseRulesManifestJson(fs.readFileSync(manifestPath, "utf-8"));
195
+ if (
196
+ !parsed.ok ||
197
+ !Array.isArray(parsed.manifest?.rules) ||
198
+ !Array.isArray(parsed.manifest?.excluded) ||
199
+ typeof parsed.manifest.generatedAt !== "string"
200
+ ) {
201
+ return null;
202
+ }
203
+ return parsed.manifest;
204
+ } catch {
205
+ return null;
206
+ }
207
+ }
208
+
184
209
  /**
185
210
  * @param {object} params
186
211
  * @param {string} params.projectRoot
@@ -256,7 +281,19 @@ export function discoverCursorRules({ projectRoot, profile, writeManifest = true
256
281
  /** @type {DiscoverCursorRulesResult} */
257
282
  const result = { ok: true, manifest };
258
283
  if (writeManifest) {
259
- result.manifestPath = writeRulesManifestAtomic(projectRoot, manifest);
284
+ const manifestPath = path.join(projectRoot, RULES_MANIFEST_REL_PATH);
285
+ const existing = loadExistingManifestForFingerprint(manifestPath);
286
+ if (
287
+ existing &&
288
+ fingerprintRulesManifest(existing) === fingerprintRulesManifest(manifest)
289
+ ) {
290
+ // Unchanged rules set: skip the write and keep the existing `generatedAt`
291
+ // so `spine rules sync` is idempotent (#315).
292
+ result.manifest = { ...manifest, generatedAt: existing.generatedAt };
293
+ result.manifestPath = manifestPath;
294
+ } else {
295
+ result.manifestPath = writeRulesManifestAtomic(projectRoot, manifest);
296
+ }
260
297
  }
261
298
  return result;
262
299
  }
@@ -1,9 +1,9 @@
1
1
  // @ts-nocheck
2
2
  /**
3
- * Micromatch helpers for PROMPT File Scope vs rule globs (SP-091).
3
+ * Glob helpers for PROMPT File Scope vs rule globs (SP-091).
4
4
  */
5
5
 
6
- import micromatch from "micromatch";
6
+ import picomatch from "picomatch";
7
7
 
8
8
  /** Synthetic extensions used when expanding directory or wildcard scope entries. */
9
9
  export const SYNTHETIC_PROBE_EXTENSIONS = Object.freeze([
@@ -120,11 +120,13 @@ export function ruleGlobsMatchFileScope(globs, fileScope) {
120
120
  return true;
121
121
  }
122
122
 
123
- if (scopeEntries.some((entry) => micromatch.isMatch(entry, glob))) {
123
+ const isMatch = picomatch(glob);
124
+
125
+ if (scopeEntries.some((entry) => isMatch(entry))) {
124
126
  return true;
125
127
  }
126
128
 
127
- if (probes.some((probe) => micromatch.isMatch(probe, glob))) {
129
+ if (probes.some((probe) => isMatch(probe))) {
128
130
  return true;
129
131
  }
130
132
  }
@@ -14,13 +14,18 @@ import { validateSettingValue } from "./settings-fields.mjs";
14
14
  * @typedef {object} EnvOverrideSpec
15
15
  * @property {string} envVar
16
16
  * @property {string} configPath Dotted path (e.g. paths.tasksRoot)
17
- * @property {"tasksRoot" | "maxParallel"} kind
17
+ * @property {"tasksRoot" | "maxParallel" | "agentProfile"} kind
18
18
  */
19
19
 
20
20
  /** @type {readonly EnvOverrideSpec[]} */
21
21
  export const ENV_OVERRIDE_SPECS = Object.freeze([
22
22
  { envVar: "SPINE_TASKS_ROOT", configPath: "paths.tasksRoot", kind: "tasksRoot" },
23
23
  { envVar: "SPINE_MAX_LANES", configPath: "lanes.maxParallel", kind: "maxParallel" },
24
+ {
25
+ envVar: "SPINE_AGENT_PROFILE_OVERRIDE",
26
+ configPath: "agents.activeProfile",
27
+ kind: "agentProfile",
28
+ },
24
29
  ]);
25
30
 
26
31
  /**
@@ -120,6 +125,7 @@ export function resolveTasksRootPath(projectRoot, config) {
120
125
  * config: object,
121
126
  * sources: Record<string, ConfigValueSource>,
122
127
  * envVars: Record<string, string>,
128
+ * warnings: Record<string, string>,
123
129
  * } | { ok: false, error: { code: string, message: string, suggestedCommand?: string } }}
124
130
  */
125
131
  export function applyEnvOverrides(config, projectRoot, env = process.env) {
@@ -127,6 +133,9 @@ export function applyEnvOverrides(config, projectRoot, env = process.env) {
127
133
  const sources = {};
128
134
  /** @type {Record<string, string>} */
129
135
  const envVars = {};
136
+ /** Reasons an env var was ignored (e.g. unknown agent profile), keyed by config path. */
137
+ /** @type {Record<string, string>} */
138
+ const warnings = {};
130
139
 
131
140
  for (const spec of ENV_OVERRIDE_SPECS) {
132
141
  sources[spec.configPath] = "file";
@@ -158,6 +167,28 @@ export function applyEnvOverrides(config, projectRoot, env = process.env) {
158
167
  continue;
159
168
  }
160
169
 
170
+ if (spec.kind === "agentProfile") {
171
+ // Schema validation ran on the file config before env overrides, so the override must
172
+ // check profile membership itself. Unknown names are ignored (soft-fail) so a stale
173
+ // export from a previous run cannot break config load; the reason is recorded for display.
174
+ const requested = String(raw).trim();
175
+ const profiles = merged?.agents?.profiles;
176
+ if (
177
+ profiles == null ||
178
+ typeof profiles !== "object" ||
179
+ Array.isArray(profiles) ||
180
+ !Object.prototype.hasOwnProperty.call(profiles, requested)
181
+ ) {
182
+ warnings[spec.configPath] =
183
+ `${spec.envVar} ignored: unknown profile "${requested}"`;
184
+ continue;
185
+ }
186
+ setValueAtPath(merged, spec.configPath, requested);
187
+ sources[spec.configPath] = "env";
188
+ envVars[spec.configPath] = spec.envVar;
189
+ continue;
190
+ }
191
+
161
192
  if (spec.kind === "maxParallel") {
162
193
  const validated = validateSettingValue("lanes.maxParallel", raw);
163
194
  if (!validated.ok) {
@@ -176,7 +207,7 @@ export function applyEnvOverrides(config, projectRoot, env = process.env) {
176
207
  }
177
208
  }
178
209
 
179
- return { ok: true, config: merged, sources, envVars };
210
+ return { ok: true, config: merged, sources, envVars, warnings };
180
211
  }
181
212
 
182
213
  /**
@@ -196,13 +227,19 @@ export function listEnvAwareDisplayFields() {
196
227
  * @param {Record<string, string> | undefined} envVars
197
228
  * @param {string} configPath
198
229
  * @param {unknown} value
230
+ * @param {Record<string, string> | undefined} [warnings] Reasons an env override was ignored,
231
+ * keyed by config path (e.g. an unknown SPINE_AGENT_PROFILE_OVERRIDE profile).
199
232
  * @returns {string}
200
233
  */
201
- export function formatConfigSourceDetail(sources, envVars, configPath, value) {
234
+ export function formatConfigSourceDetail(sources, envVars, configPath, value, warnings) {
202
235
  const display = value === undefined || value === null ? "(not set)" : String(value);
203
236
  const source = sources?.[configPath] ?? "file";
237
+ const warning = warnings?.[configPath];
204
238
  if (source === "env" && envVars?.[configPath]) {
205
- return `${display} (source: env, ${envVars[configPath]})`;
239
+ return `${display} (source: env, ${envVars[configPath]}${warning ? `, ${warning}` : ""})`;
240
+ }
241
+ if (warning) {
242
+ return `${display} (source: ${source}, ${warning})`;
206
243
  }
207
244
  return `${display} (source: ${source})`;
208
245
  }