pi-spine 2.27.1 → 2.28.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 (64) hide show
  1. package/bin/spine-batch.mjs +46 -4
  2. package/bin/spine-cli/cli-args.mjs +117 -0
  3. package/bin/spine-gate.mjs +28 -21
  4. package/bin/spine-integrate.mjs +28 -7
  5. package/bin/spine-issue.mjs +2 -1
  6. package/bin/spine-settings.mjs +7 -9
  7. package/bin/spine-tasks.mjs +1 -0
  8. package/bin/spine-worker-runner.mjs +21 -8
  9. package/bin/spine.mjs +10 -3
  10. package/package.json +1 -1
  11. package/skills/create-spine-tasks/references/prompt-template.md +5 -0
  12. package/skills/spine-release-operator/SKILL.md +14 -2
  13. package/src/batch/contract-exec.mjs +2 -3
  14. package/src/batch/contract-task-start.mjs +23 -1
  15. package/src/batch/diagnosis-handoff-packet.mjs +18 -0
  16. package/src/batch/diagnosis-primary-failure.mjs +35 -0
  17. package/src/batch/engine-lanes/matrix-run.mjs +2 -0
  18. package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
  19. package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
  20. package/src/batch/engine-lanes/review-code.mjs +20 -0
  21. package/src/batch/engine-lanes/review-final.mjs +10 -2
  22. package/src/batch/engine-lanes/review-poll.mjs +33 -0
  23. package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
  24. package/src/batch/engine-lanes.mjs +18 -17
  25. package/src/batch/evidence-command.mjs +18 -21
  26. package/src/batch/evidence-exec.mjs +79 -0
  27. package/src/batch/journal.mjs +5 -3
  28. package/src/batch/metrics-rollup.mjs +98 -4
  29. package/src/batch/metrics.mjs +134 -9
  30. package/src/batch/provider-quota.mjs +174 -6
  31. package/src/batch/quota-fallback.mjs +87 -6
  32. package/src/batch/reconcile-classify.mjs +28 -1
  33. package/src/batch/reconcile-diagnosis-context.mjs +2 -0
  34. package/src/batch/resume-lane-reviews.mjs +11 -10
  35. package/src/batch/retry-profile.mjs +77 -0
  36. package/src/batch/retry.mjs +32 -1
  37. package/src/batch/review-step-run.mjs +4 -0
  38. package/src/batch/review-step.mjs +1 -0
  39. package/src/batch/sequence-wait.mjs +7 -5
  40. package/src/batch/state-io.mjs +29 -3
  41. package/src/batch/worker-heartbeat.mjs +10 -2
  42. package/src/batch/worker-host.mjs +1 -1
  43. package/src/batch/worker-prompt.mjs +4 -5
  44. package/src/cli/deps.mjs +3 -2
  45. package/src/config/agent-model-resolve.mjs +144 -8
  46. package/src/config/contract.mjs +20 -0
  47. package/src/config/model-family.mjs +60 -0
  48. package/src/config/preflight/discovery.mjs +1 -0
  49. package/src/config/settings-fields.mjs +15 -0
  50. package/src/config/spine-config-schema.mjs +49 -0
  51. package/src/doctor/agent-model-inherit.mjs +78 -1
  52. package/src/doctor/agent-template-drift.mjs +65 -0
  53. package/src/doctor/run-doctor-checks.mjs +8 -1
  54. package/src/doctor/stet-capacity.mjs +171 -0
  55. package/src/metrics/quota-cli.mjs +16 -0
  56. package/src/metrics/quota-probes.mjs +228 -31
  57. package/src/metrics/quota-snapshot.mjs +21 -2
  58. package/src/planner/graph.mjs +7 -5
  59. package/src/planner/pending.mjs +2 -2
  60. package/src/planner/scope.mjs +3 -3
  61. package/src/tasks/packet/parse-prompt.mjs +47 -0
  62. package/src/tasks/packet/validate-prompt.mjs +156 -1
  63. package/templates/agents/reviewer.md +3 -1
  64. package/templates/agents/worker.md +15 -19
@@ -0,0 +1,324 @@
1
+ /**
2
+ * Per-task agent context for engine reviews (SP-834 / #355).
3
+ *
4
+ * Engine review spawns used the batch-wide `config` loaded at engine start. This module
5
+ * resolves, per task, the worker profile in effect (retry override, PROMPT `**Profile:**`,
6
+ * quota fallback hop, `agents.activeProfile`) and the reviewer chosen by `resolveEffectiveReviewer`
7
+ * (SP-832), then hands the review phases a config whose `agents.reviewer` carries those
8
+ * pins. `resolveTaskWorkerProfile` and `buildTaskReviewConfig` are pure;
9
+ * `applyTaskReviewProfile` adds the I/O (PROMPT load, journal, runtime family guard).
10
+ */
11
+
12
+ import { resolveEffectiveReviewer } from "../../config/agent-model-resolve.mjs";
13
+ import { resolveWorkerBackend } from "../../config/worker-backend.mjs";
14
+ import { resolvePoolId } from "../../metrics/quota-snapshot.mjs";
15
+ import { loadTaskPacket } from "../../tasks/packet/index.mjs";
16
+ import { appendJournalEvent } from "../journal.mjs";
17
+ import { recordReviewMetric } from "../metrics.mjs";
18
+ import { saveEngineBatchState } from "../pause.mjs";
19
+ import { readReviewLevel } from "../review.mjs";
20
+ import { isReviewTypeRequired, shouldRunCodeReview, shouldRunFinalReview } from "../review-shared.mjs";
21
+ import { recomputeTaskCounters, updateSegmentForTask } from "../state.mjs";
22
+ import { recordLaneTaskMetric } from "./queue.mjs";
23
+ import { loadQuotaFallbackForWorker } from "./quota-fallback-state.mjs";
24
+
25
+ /** @type {readonly ("plan"|"code"|"final")[]} */
26
+ const REVIEW_TYPES = ["plan", "code", "final"];
27
+
28
+ /**
29
+ * @param {unknown} value
30
+ * @returns {string|null}
31
+ */
32
+ function nonEmpty(value) {
33
+ if (typeof value !== "string") return null;
34
+ const trimmed = value.trim();
35
+ return trimmed === "" ? null : trimmed;
36
+ }
37
+
38
+ /**
39
+ * @param {Record<string, any>} agents
40
+ * @param {string|null} profile
41
+ * @returns {{ model: string|null, thinking: string|null }}
42
+ */
43
+ function pickWorkerPins(agents, profile) {
44
+ const profiles = agents?.profiles && typeof agents.profiles === "object" ? agents.profiles : {};
45
+ const named = profile && Object.hasOwn(profiles, profile) ? profiles[profile]?.worker : undefined;
46
+ return {
47
+ model: nonEmpty(named?.model) ?? nonEmpty(agents?.worker?.model),
48
+ thinking: nonEmpty(named?.thinking) ?? nonEmpty(agents?.worker?.thinking),
49
+ };
50
+ }
51
+
52
+ /**
53
+ * Worker profile / model / thinking in effect for one task.
54
+ *
55
+ * Profile order: active quota fallback hop (when its `exhaustedPool` is the pool of the
56
+ * candidate profile's worker model), then `task.profileOverride` (`spine batch retry
57
+ * --profile`, SP-836), then `prompt.profile`, then `agents.activeProfile`. `model` comes
58
+ * from `agents.profiles[profile].worker`, falling back to `agents.worker`. Thinking order:
59
+ * `prompt.thinking`, then the resolved profile's `worker.thinking`, then
60
+ * `agents.worker.thinking` (SP-835 / #340).
61
+ *
62
+ * Pure: no I/O.
63
+ *
64
+ * @param {object} params
65
+ * @param {Record<string, any>} [params.config]
66
+ * @param {{ profile?: string|null, thinking?: string|null }|null} [params.prompt] Parsed PROMPT (SP-833).
67
+ * @param {{ toProfile?: string, exhaustedPool?: string }|null} [params.quotaFallback] `state.resilience.quotaFallback`.
68
+ * @param {{ profileOverride?: string|null }|null} [params.task] Batch-state task row.
69
+ * @returns {{ profile: string|null, model: string|null, thinking: string|null, source: "quota_fallback"|"retry_override"|"prompt"|"active_profile" }}
70
+ */
71
+ export function resolveTaskWorkerProfile({ config, prompt = null, quotaFallback = null, task = null } = {}) {
72
+ const agents = config?.agents ?? {};
73
+ const retryProfile = nonEmpty(task?.profileOverride);
74
+ const promptProfile = nonEmpty(prompt?.profile);
75
+ const ownProfile = retryProfile ?? promptProfile ?? nonEmpty(agents.activeProfile);
76
+ const ownSource = retryProfile ? "retry_override" : promptProfile ? "prompt" : "active_profile";
77
+ const promptThinking = nonEmpty(prompt?.thinking);
78
+
79
+ /** @param {string|null} profile @param {"quota_fallback"|"retry_override"|"prompt"|"active_profile"} source */
80
+ const resolved = (profile, source) => {
81
+ const pins = pickWorkerPins(agents, profile);
82
+ return { profile, model: pins.model, thinking: promptThinking ?? pins.thinking, source };
83
+ };
84
+
85
+ const hopProfile = nonEmpty(quotaFallback?.toProfile);
86
+ const hopPool = nonEmpty(quotaFallback?.exhaustedPool);
87
+ if (hopProfile && hopPool && resolvePoolId(pickWorkerPins(agents, ownProfile).model ?? undefined) === hopPool) {
88
+ return resolved(hopProfile, "quota_fallback");
89
+ }
90
+ return resolved(ownProfile, ownSource);
91
+ }
92
+
93
+ /**
94
+ * Per-attempt worker spawn context (SP-835 / #340): resolves the effective worker
95
+ * profile / model / thinking, records them on the task row (metrics read them), builds the
96
+ * child `extraEnv` overrides, and journals `worker.profile_override_ignored` on the
97
+ * `agentSession` backend (which drops `extraEnv`, #317). Called once per worker attempt,
98
+ * inside the path `runWithQuotaFallback` re-runs, so a hop applied mid-task is picked up.
99
+ *
100
+ * @param {Record<string, any>} params Lane-run params bag (`projectRoot`, `state`, `batchId`,
101
+ * `config`, `task`, `lane`, `taskFolderInWorktree`, `laneCorrelationId`).
102
+ * @returns {{
103
+ * context: ReturnType<typeof resolveTaskWorkerProfile>,
104
+ * extraEnv: Record<string, string>,
105
+ * startedPayload: Record<string, string|null>,
106
+ * }}
107
+ */
108
+ export function prepareWorkerAttempt(params) {
109
+ const { projectRoot, state, batchId, config, task, lane, taskFolderInWorktree, laneCorrelationId } = params;
110
+ const prompt = loadPromptSafely(taskFolderInWorktree);
111
+ const quotaFallback =
112
+ state?.resilience?.quotaFallback ?? loadQuotaFallbackForWorker({ projectRoot, batchId });
113
+ const context = resolveTaskWorkerProfile({ config, prompt, quotaFallback, task });
114
+
115
+ // A sticky hop that does not apply to this task's pool must not leak into the child
116
+ // (`runWorker` merges the hop env under caller keys), so pin the resolved profile then too.
117
+ const activeProfile = nonEmpty(config?.agents?.activeProfile);
118
+ const hopProfile = nonEmpty(quotaFallback?.toProfile);
119
+ /** @type {Record<string, string>} */
120
+ const extraEnv = {};
121
+ if (context.profile && (context.profile !== activeProfile || (hopProfile && hopProfile !== context.profile))) {
122
+ extraEnv.SPINE_AGENT_PROFILE_OVERRIDE = context.profile;
123
+ }
124
+ const promptThinking = nonEmpty(prompt?.thinking);
125
+ if (promptThinking) extraEnv.SPINE_WORKER_THINKING_OVERRIDE = promptThinking;
126
+
127
+ if (context.profile) task.workerProfile = context.profile;
128
+ else delete task.workerProfile;
129
+ if (context.thinking) task.workerThinking = context.thinking;
130
+ else delete task.workerThinking;
131
+ if (context.model) task.workerModel = context.model;
132
+ else delete task.workerModel;
133
+
134
+ if (Object.keys(extraEnv).length > 0 && resolveWorkerBackend(config) === "agentSession") {
135
+ appendJournalEvent(projectRoot, batchId, "worker.profile_override_ignored", {
136
+ taskId: task.taskId,
137
+ laneNumber: lane?.laneNumber,
138
+ laneId: lane?.laneId,
139
+ correlationId: laneCorrelationId,
140
+ backend: "agentSession",
141
+ reason: "agentSession backend drops extraEnv (#317)",
142
+ profile: context.profile,
143
+ thinking: promptThinking,
144
+ });
145
+ }
146
+ return {
147
+ context,
148
+ extraEnv,
149
+ startedPayload: {
150
+ workerProfile: context.profile,
151
+ workerModel: context.model,
152
+ workerThinking: context.thinking,
153
+ workerProfileSource: context.source,
154
+ },
155
+ };
156
+ }
157
+
158
+ /**
159
+ * Clone `config` with `agents.reviewer` replaced by the effective per-type reviewer pins.
160
+ * `null` pins become `"inherit"`, which `resolveReviewerModelPin` reads back as `null`.
161
+ *
162
+ * Pure: no I/O, never mutates `config`.
163
+ *
164
+ * @param {object} params
165
+ * @param {Record<string, any>} [params.config]
166
+ * @param {{ reviewerProfile?: string|null }|null} [params.prompt] Parsed PROMPT (SP-833).
167
+ * @param {{ profile?: string|null, model?: string|null }} [params.workerContext] From `resolveTaskWorkerProfile`.
168
+ * @returns {{
169
+ * config: Record<string, any>,
170
+ * reviewer: ReturnType<typeof resolveEffectiveReviewer>,
171
+ * blocked: ReturnType<typeof resolveEffectiveReviewer>["blocked"],
172
+ * warnings: string[],
173
+ * }}
174
+ */
175
+ export function buildTaskReviewConfig({ config, prompt = null, workerContext = {} } = {}) {
176
+ const base = config ?? {};
177
+ const reviewer = resolveEffectiveReviewer(base, {
178
+ promptReviewerProfile: prompt?.reviewerProfile ?? null,
179
+ workerProfile: workerContext.profile ?? null,
180
+ workerModel: workerContext.model ?? null,
181
+ });
182
+
183
+ /** @type {Record<string, any>} */
184
+ let reviewConfig;
185
+ try {
186
+ reviewConfig = structuredClone(base);
187
+ } catch {
188
+ reviewConfig = { ...base, agents: { ...(base.agents ?? {}) } };
189
+ }
190
+
191
+ /** @type {Record<string, any>} */
192
+ const pins = {};
193
+ for (const reviewType of REVIEW_TYPES) {
194
+ pins[reviewType] = {
195
+ model: reviewer[reviewType].model ?? "inherit",
196
+ thinking: reviewer[reviewType].thinking ?? "inherit",
197
+ };
198
+ }
199
+ const common = (/** @type {"model"|"thinking"} */ key) =>
200
+ pins.plan[key] === pins.code[key] && pins.code[key] === pins.final[key] ? pins.plan[key] : "inherit";
201
+ const originalReviewer =
202
+ reviewConfig.agents?.reviewer && typeof reviewConfig.agents.reviewer === "object"
203
+ ? reviewConfig.agents.reviewer
204
+ : {};
205
+ reviewConfig.agents = {
206
+ ...(reviewConfig.agents ?? {}),
207
+ reviewer: { ...originalReviewer, model: common("model"), thinking: common("thinking"), ...pins },
208
+ };
209
+
210
+ return { config: reviewConfig, reviewer, blocked: reviewer.blocked, warnings: reviewer.warnings };
211
+ }
212
+
213
+ /**
214
+ * @param {string} taskFolder
215
+ * @returns {Record<string, any>|null}
216
+ */
217
+ function loadPromptSafely(taskFolder) {
218
+ try {
219
+ return loadTaskPacket(taskFolder).prompt ?? null;
220
+ } catch {
221
+ return null;
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Resolve the per-task review config for the engine / resume review phases, journal the
227
+ * resolution once, and enforce the runtime family guard: a blocked review type that will
228
+ * run fails the task (`review_blocked`) before any reviewer spawns.
229
+ *
230
+ * @param {Record<string, any>} params Review-phase params bag (`projectRoot`, `state`,
231
+ * `batchId`, `config`, `task`, `lane`, `taskFolderInWorktree`, `laneCorrelationId`).
232
+ * @returns {Promise<{ ok: true, config: Record<string, any> } | { ok: false, error: string, output: string, reviewBlocked: true }>}
233
+ */
234
+ export async function applyTaskReviewProfile(params) {
235
+ const { projectRoot, state, batchId, config, task, lane, taskFolderInWorktree, laneCorrelationId } = params;
236
+ const taskId = task?.taskId;
237
+ if (!taskFolderInWorktree || !taskId) return { ok: true, config };
238
+
239
+ const prompt = loadPromptSafely(taskFolderInWorktree);
240
+ const quotaFallback =
241
+ state?.resilience?.quotaFallback ?? loadQuotaFallbackForWorker({ projectRoot, batchId });
242
+ const workerContext = resolveTaskWorkerProfile({ config, prompt, quotaFallback, task });
243
+ const built = buildTaskReviewConfig({ config, prompt, workerContext });
244
+
245
+ const meta = {
246
+ taskId,
247
+ laneNumber: lane?.laneNumber,
248
+ laneId: lane?.laneId,
249
+ correlationId: laneCorrelationId,
250
+ };
251
+ const summarize = (/** @type {"plan"|"code"|"final"} */ reviewType) => ({
252
+ model: built.reviewer[reviewType].model,
253
+ thinking: built.reviewer[reviewType].thinking,
254
+ profile: built.reviewer[reviewType].profile,
255
+ source: built.reviewer[reviewType].source,
256
+ });
257
+ appendJournalEvent(projectRoot, batchId, "review.reviewer_resolved", {
258
+ ...meta,
259
+ plan: summarize("plan"),
260
+ code: summarize("code"),
261
+ final: summarize("final"),
262
+ warnings: built.warnings,
263
+ });
264
+
265
+ const reviewLevel = readReviewLevel(taskFolderInWorktree);
266
+ /** @type {Record<"plan"|"code"|"final", boolean>} */
267
+ const willRun = {
268
+ plan: isReviewTypeRequired(reviewLevel, "plan"),
269
+ code: shouldRunCodeReview({ reviewLevel }),
270
+ final: shouldRunFinalReview({ config, reviewLevel }),
271
+ };
272
+ /** @type {Array<{ reviewType: "plan"|"code"|"final", reason: string }>} */
273
+ const blocking = [];
274
+ for (const reviewType of REVIEW_TYPES) {
275
+ const entry = built.blocked.find((candidate) => candidate.reviewType === reviewType);
276
+ if (entry && willRun[reviewType]) blocking.push(entry);
277
+ }
278
+ if (blocking.length === 0) return { ok: true, config: built.config };
279
+
280
+ const workerProfileLabel = workerContext.profile ?? "<workerProfile>";
281
+ const fix =
282
+ `set agents.profiles.${workerProfileLabel}.reviewerProfile or agents.reviewerProfile ` +
283
+ "to a profile from another model family";
284
+ for (const { reviewType, reason } of blocking) {
285
+ appendJournalEvent(projectRoot, batchId, "review.blocked", {
286
+ ...meta,
287
+ reviewType,
288
+ reason,
289
+ workerModel: workerContext.model,
290
+ reviewerModel: built.reviewer[reviewType].model,
291
+ });
292
+ // SP-837 (#325): reviewer row for the blocked pairing (no reviewer spawns).
293
+ recordReviewMetric({
294
+ projectRoot,
295
+ config: built.config,
296
+ batchId,
297
+ taskId,
298
+ laneNumber: lane?.laneNumber,
299
+ reviewType,
300
+ outcome: "blocked",
301
+ failureReason: reason,
302
+ });
303
+ }
304
+ const first = blocking[0];
305
+ const exitReason = `${first.reviewType}_review_blocked`;
306
+ const output =
307
+ `${first.reviewType} review blocked (${first.reason}): worker "${workerContext.model ?? "inherit"}" ` +
308
+ `and reviewer "${built.reviewer[first.reviewType].model ?? "inherit"}" cannot be paired; ${fix}`;
309
+
310
+ task.status = "failed";
311
+ task.endedAt = Date.now();
312
+ task.exitReason = exitReason;
313
+ updateSegmentForTask(state, taskId, "failed");
314
+ recomputeTaskCounters(state);
315
+ await saveEngineBatchState(projectRoot, state);
316
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
317
+ ...meta,
318
+ classification: "review_blocked",
319
+ exitCode: 1,
320
+ output,
321
+ });
322
+ recordLaneTaskMetric({ projectRoot, batchId, task, config, taskFolder: taskFolderInWorktree });
323
+ return { ok: false, error: exitReason, output, reviewBlocked: true };
324
+ }
@@ -12,11 +12,7 @@
12
12
 
13
13
  import fs from "node:fs";
14
14
  import path from "node:path";
15
- import {
16
- loadTaskFileScopePaths,
17
- recordLaneTaskMetric,
18
- recordPromptParseFailure,
19
- } from "./engine-lanes/queue.mjs";
15
+ import { loadTaskFileScopePaths, recordLaneTaskMetric, recordPromptParseFailure } from "./engine-lanes/queue.mjs";
20
16
  import { appendJournalEvent } from "./journal.mjs";
21
17
  import { commitLaneAndValidateWorktree } from "./engine-lanes/commit.mjs";
22
18
  import { recordTaskFailureSalvage } from "./salvage.mjs";
@@ -35,12 +31,9 @@ import { resolveWorkerBackend } from "../config/worker-backend.mjs";
35
31
  import { acquireLaneSlot, loadMatrixTaskRows, releaseLaneSlot } from "./engine-lanes/matrix.mjs";
36
32
  import { runMatrixTaskOnLane } from "./engine-lanes/matrix-run.mjs";
37
33
  import { runWithQuotaFallback } from "./engine-lanes/quota-fallback-run.mjs";
34
+ import { applyTaskReviewProfile, prepareWorkerAttempt } from "./engine-lanes/task-agent-profile.mjs";
38
35
 
39
- export {
40
- buildTasksAndLanesFromPlan,
41
- loadTaskFileScopePaths,
42
- skipTaskDoneOnDisk,
43
- } from "./engine-lanes/queue.mjs";
36
+ export { buildTasksAndLanesFromPlan, loadTaskFileScopePaths, skipTaskDoneOnDisk } from "./engine-lanes/queue.mjs";
44
37
 
45
38
  export {
46
39
  buildFinalReviewArtifactPath,
@@ -60,10 +53,7 @@ export {
60
53
  } from "./engine-lanes/merge.mjs";
61
54
 
62
55
  export { syncLaneWorktreeFromOrch } from "./worktree.mjs";
63
- export {
64
- collectSharedScopeSatisfiedDeps,
65
- ensureLaneSyncedForSharedScopeDeps,
66
- } from "./engine-lanes/orch-sync.mjs";
56
+ export { collectSharedScopeSatisfiedDeps, ensureLaneSyncedForSharedScopeDeps } from "./engine-lanes/orch-sync.mjs";
67
57
 
68
58
  export {
69
59
  acquireLaneSlot,
@@ -275,11 +265,14 @@ async function runNonMatrixTaskOnLane({
275
265
  if (!task.startedAt) task.startedAt = Date.now();
276
266
  updateSegmentForTask(state, taskId, "running");
277
267
  await saveEngineBatchState(projectRoot, state);
268
+ // SP-835 (#340): per-attempt worker profile/thinking. runWithQuotaFallback re-enters this function on a retry, so a hop is re-resolved.
269
+ const attempt = prepareWorkerAttempt({ projectRoot, state, batchId, config, task, lane, taskFolderInWorktree, laneCorrelationId });
278
270
  appendJournalEvent(projectRoot, batchId, "task.started", {
279
271
  taskId,
280
272
  laneNumber,
281
273
  laneId: lane.laneId,
282
274
  correlationId: laneCorrelationId,
275
+ ...attempt.startedPayload,
283
276
  });
284
277
 
285
278
  const workerResult = /** @type {any} */ (await runWorker({
@@ -293,6 +286,7 @@ async function runNonMatrixTaskOnLane({
293
286
  laneCorrelationId,
294
287
  fileScopePaths,
295
288
  config,
289
+ extraEnv: attempt.extraEnv,
296
290
  // Fire-and-forget saves (SP-797 / #302): the host never awaits these callbacks.
297
291
  // Safe — the save serializes live state at lock-acquire time, never a stale snapshot.
298
292
  onHeartbeat: async (timestamp) => {
@@ -388,11 +382,18 @@ async function runNonMatrixTaskOnLane({
388
382
  correlationId: laneCorrelationId,
389
383
  });
390
384
 
385
+ // SP-834 (#355): per-task effective reviewer config; blocked pairings fail before any spawn.
386
+ const reviewProfile = await applyTaskReviewProfile({
387
+ projectRoot, state, batchId, config, task, lane, taskFolderInWorktree, laneCorrelationId,
388
+ });
389
+ if (!reviewProfile.ok) return reviewProfile;
390
+ const reviewConfig = reviewProfile.config;
391
+
391
392
  const planReview = await runPlanReviewPhase({
392
393
  projectRoot,
393
394
  state,
394
395
  batchId,
395
- config,
396
+ config: reviewConfig,
396
397
  task,
397
398
  lane,
398
399
  taskFolderInWorktree,
@@ -409,7 +410,7 @@ async function runNonMatrixTaskOnLane({
409
410
  projectRoot,
410
411
  state,
411
412
  batchId,
412
- config,
413
+ config: reviewConfig,
413
414
  task,
414
415
  lane,
415
416
  taskFolderInWorktree,
@@ -426,7 +427,7 @@ async function runNonMatrixTaskOnLane({
426
427
  projectRoot,
427
428
  state,
428
429
  batchId,
429
- config,
430
+ config: reviewConfig,
430
431
  task,
431
432
  lane,
432
433
  taskFolderInWorktree,
@@ -5,9 +5,9 @@
5
5
  */
6
6
 
7
7
  import path from "node:path";
8
- import { execFileSync } from "node:child_process";
9
8
  import { validateWorkerLaunchScriptPath } from "../config/worker-launch-script.mjs";
10
9
  import { EvidenceCommandError } from "./evidence-command-error.mjs";
10
+ import { EVIDENCE_DEFAULT_MAX_BYTES, runEvidenceArgvToFile } from "./evidence-exec.mjs";
11
11
  import {
12
12
  expandEvidencePathEntries,
13
13
  isAllowedEvidencePathEntry,
@@ -376,8 +376,8 @@ function collectEvidencePathPrefixEntries(command) {
376
376
  * @param {string} command
377
377
  * @param {number} [maxBytes]
378
378
  */
379
- export function runEvidenceCommand(projectRoot, command, maxBytes = 256 * 1024) {
380
- if (!command) return { ok: false, skipped: true, output: "" };
379
+ export function runEvidenceCommand(projectRoot, command, maxBytes = EVIDENCE_DEFAULT_MAX_BYTES) {
380
+ if (!command) return { ok: false, skipped: true, output: "", truncated: false };
381
381
 
382
382
  try {
383
383
  const chain = parseEvidenceCommandChain(command);
@@ -393,35 +393,32 @@ export function runEvidenceCommand(projectRoot, command, maxBytes = 256 * 1024)
393
393
  }
394
394
  /** @type {string[]} */
395
395
  const outputs = [];
396
+ let truncated = false;
396
397
  for (const argv of chain) {
397
398
  const execArgv = resolveEvidenceScriptsArgv(projectRoot, argv);
398
- const output = execFileSync(execArgv[0], execArgv.slice(1), {
399
- cwd: projectRoot,
400
- encoding: "utf-8",
401
- stdio: ["ignore", "pipe", "pipe"],
402
- timeout: 10 * 60 * 1000,
403
- maxBuffer: maxBytes,
404
- ...(env ? { env } : {}),
405
- });
406
- outputs.push(String(output ?? ""));
399
+ const step = runEvidenceArgvToFile({ projectRoot, argv: execArgv, env, maxBytes });
400
+ outputs.push(step.output);
401
+ truncated = truncated || step.truncated;
402
+ if (!step.ok) {
403
+ return {
404
+ ok: false,
405
+ skipped: false,
406
+ output: `${outputs.join("")}\n[exit] ${step.exitDetail}`.trim(),
407
+ truncated,
408
+ };
409
+ }
407
410
  }
408
- return { ok: true, skipped: false, output: outputs.join("") };
411
+ return { ok: true, skipped: false, output: outputs.join(""), truncated };
409
412
  } catch (err) {
410
413
  if (err instanceof EvidenceCommandError) {
411
414
  return {
412
415
  ok: false,
413
416
  skipped: false,
414
417
  output: `[rejected] ${err.message}`,
418
+ truncated: false,
415
419
  };
416
420
  }
417
-
418
- const stdout = err && typeof err === "object" && "stdout" in err ? String(err.stdout ?? "") : "";
419
- const stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr ?? "") : "";
420
421
  const message = err instanceof Error ? err.message : String(err);
421
- return {
422
- ok: false,
423
- skipped: false,
424
- output: `${stdout}${stderr}\n[exit] ${message}`.trim(),
425
- };
422
+ return { ok: false, skipped: false, output: `[exit] ${message}`, truncated: false };
426
423
  }
427
424
  }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Run one validated evidence argv with stdout+stderr streamed to a temp file.
3
+ * Pipe buffers (execFileSync maxBuffer) kill the child with ENOBUFS on large
4
+ * test logs and lose the exit status; a file sink keeps the true exit status
5
+ * and lets us retain only the tail, which is where test failures summarize.
6
+ */
7
+
8
+ import fs from "node:fs";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ import { spawnSync } from "node:child_process";
12
+
13
+ export const EVIDENCE_TIMEOUT_MS = 10 * 60 * 1000;
14
+ export const EVIDENCE_DEFAULT_MAX_BYTES = 256 * 1024;
15
+
16
+ /**
17
+ * @param {string} filePath
18
+ * @param {number} maxBytes
19
+ * @returns {{ text: string, totalBytes: number, truncated: boolean }}
20
+ */
21
+ function readFileTail(filePath, maxBytes) {
22
+ const totalBytes = fs.statSync(filePath).size;
23
+ if (totalBytes <= maxBytes) {
24
+ return { text: fs.readFileSync(filePath, "utf-8"), totalBytes, truncated: false };
25
+ }
26
+ const fd = fs.openSync(filePath, "r");
27
+ try {
28
+ const buffer = Buffer.alloc(maxBytes);
29
+ fs.readSync(fd, buffer, 0, maxBytes, totalBytes - maxBytes);
30
+ return { text: buffer.toString("utf-8"), totalBytes, truncated: true };
31
+ } finally {
32
+ fs.closeSync(fd);
33
+ }
34
+ }
35
+
36
+ /**
37
+ * @param {object} opts
38
+ * @param {string} opts.projectRoot
39
+ * @param {string[]} opts.argv
40
+ * @param {NodeJS.ProcessEnv | undefined} opts.env
41
+ * @param {number} opts.maxBytes Tail bytes retained from combined output.
42
+ * @param {number} [opts.timeoutMs]
43
+ * @returns {{ ok: boolean, output: string, truncated: boolean, exitDetail: string|null }}
44
+ */
45
+ export function runEvidenceArgvToFile({ projectRoot, argv, env, maxBytes, timeoutMs = EVIDENCE_TIMEOUT_MS }) {
46
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "spine-evidence-"));
47
+ const outPath = path.join(dir, "output.log");
48
+ const fd = fs.openSync(outPath, "w");
49
+ let fdOpen = true;
50
+ try {
51
+ const result = spawnSync(argv[0], argv.slice(1), {
52
+ cwd: projectRoot,
53
+ stdio: ["ignore", fd, fd],
54
+ timeout: timeoutMs,
55
+ ...(env ? { env } : {}),
56
+ });
57
+ fs.closeSync(fd);
58
+ fdOpen = false;
59
+ const tail = readFileTail(outPath, maxBytes);
60
+ const marker = tail.truncated
61
+ ? `[evidence truncated: kept last ${maxBytes} of ${tail.totalBytes} bytes]\n`
62
+ : "";
63
+ const output = `${marker}${tail.text}`;
64
+ if (result.error) {
65
+ return { ok: false, output, truncated: tail.truncated, exitDetail: result.error.message };
66
+ }
67
+ if (result.status === 0) {
68
+ return { ok: true, output, truncated: tail.truncated, exitDetail: null };
69
+ }
70
+ const exitDetail =
71
+ result.signal !== null
72
+ ? `Command terminated by ${result.signal}: ${argv.join(" ")}`
73
+ : `Command failed with exit code ${result.status}: ${argv.join(" ")}`;
74
+ return { ok: false, output, truncated: tail.truncated, exitDetail };
75
+ } finally {
76
+ if (fdOpen) fs.closeSync(fd);
77
+ fs.rmSync(dir, { recursive: true, force: true });
78
+ }
79
+ }
@@ -412,9 +412,6 @@ export function summarizeJournalEvent(event) {
412
412
  return parts.join("; ") || "—";
413
413
  }
414
414
 
415
- /**
416
- * @param {object[]} events
417
- */
418
415
  const JOURNAL_HINT_RECENT_MS = 30 * 60 * 1000;
419
416
 
420
417
  /**
@@ -442,13 +439,18 @@ export function extractJournalDiagnosisHints(events) {
442
439
  // SP-810 (partial #329): quota events decide retry-vs-wait — rank with failures.
443
440
  "batch.quota_fallback_applied",
444
441
  "batch.quota_fallback_exhausted",
442
+ "batch.quota_fallback_cleared",
445
443
  "worker.quota_exhausted",
444
+ // SP-835 (#340): override dropped by the agentSession backend — operator-visible, rank with quota events.
445
+ "worker.profile_override_ignored",
446
446
  "review.crash_recovered",
447
447
  "review.skipped_fresh_artifact",
448
448
  "review.resumed",
449
449
  "lane.setup_hook.failed",
450
450
  "lane.stall_killed",
451
+ "review.blocked",
451
452
  "review.failed",
453
+ "review.baseline_missing",
452
454
  "lane.salvage_inspection",
453
455
  "lane.salvage_commit",
454
456
  "lane.checkpoint_warning",