pi-spine 2.27.1 → 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 (46) 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 +16 -3
  4. package/package.json +1 -1
  5. package/skills/create-spine-tasks/references/prompt-template.md +5 -0
  6. package/skills/spine-release-operator/SKILL.md +14 -2
  7. package/src/batch/contract-task-start.mjs +23 -1
  8. package/src/batch/diagnosis-handoff-packet.mjs +18 -0
  9. package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
  10. package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
  11. package/src/batch/engine-lanes/review-code.mjs +20 -0
  12. package/src/batch/engine-lanes/review-final.mjs +10 -2
  13. package/src/batch/engine-lanes/review-poll.mjs +33 -0
  14. package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
  15. package/src/batch/engine-lanes.mjs +18 -17
  16. package/src/batch/journal.mjs +5 -3
  17. package/src/batch/metrics-rollup.mjs +98 -4
  18. package/src/batch/metrics.mjs +134 -9
  19. package/src/batch/provider-quota.mjs +155 -6
  20. package/src/batch/quota-fallback.mjs +87 -6
  21. package/src/batch/resume-lane-reviews.mjs +11 -10
  22. package/src/batch/retry-profile.mjs +77 -0
  23. package/src/batch/retry.mjs +32 -1
  24. package/src/batch/review-step-run.mjs +4 -0
  25. package/src/batch/review-step.mjs +1 -0
  26. package/src/batch/worker-heartbeat.mjs +10 -2
  27. package/src/batch/worker-host.mjs +1 -1
  28. package/src/batch/worker-prompt.mjs +4 -5
  29. package/src/cli/deps.mjs +3 -2
  30. package/src/config/agent-model-resolve.mjs +144 -8
  31. package/src/config/model-family.mjs +60 -0
  32. package/src/config/preflight/discovery.mjs +1 -0
  33. package/src/config/settings-fields.mjs +6 -0
  34. package/src/config/spine-config-schema.mjs +49 -0
  35. package/src/doctor/agent-model-inherit.mjs +78 -1
  36. package/src/doctor/run-doctor-checks.mjs +4 -1
  37. package/src/metrics/quota-cli.mjs +16 -0
  38. package/src/metrics/quota-probes.mjs +228 -31
  39. package/src/metrics/quota-snapshot.mjs +21 -2
  40. package/src/planner/graph.mjs +7 -5
  41. package/src/planner/pending.mjs +2 -2
  42. package/src/planner/scope.mjs +3 -3
  43. package/src/tasks/packet/parse-prompt.mjs +47 -0
  44. package/src/tasks/packet/validate-prompt.mjs +156 -1
  45. package/templates/agents/reviewer.md +3 -1
  46. package/templates/agents/worker.md +15 -19
@@ -10,6 +10,7 @@ import fs from "node:fs";
10
10
  import path from "node:path";
11
11
  import { recordLaneTaskMetric } from "./queue.mjs";
12
12
  import { appendJournalEvent } from "../journal.mjs";
13
+ import { recordReviewMetric } from "../metrics.mjs";
13
14
  import {
14
15
  recomputeTaskCounters,
15
16
  saveSpineBatchState,
@@ -317,6 +318,7 @@ export async function runReviewPollLoop({
317
318
  extraReviewParams = gate?.extraReviewParams ?? {};
318
319
  }
319
320
 
321
+ const reviewStartedAt = Date.now();
320
322
  const reviewResult = await runEngineReview({
321
323
  taskFolder: taskFolderInWorktree,
322
324
  worktreePath: wt,
@@ -333,6 +335,24 @@ export async function runReviewPollLoop({
333
335
  : reviewResult.reason === REVIEW_PROVIDER_ERROR_REASON
334
336
  ? `${reviewType}_review_provider_error`
335
337
  : `${reviewType}_review_spawn_failed`;
338
+ // SP-837 (#325): one reviewer row per spawn failure / timeout / provider error.
339
+ recordReviewMetric({
340
+ projectRoot,
341
+ config,
342
+ batchId,
343
+ taskId,
344
+ laneNumber,
345
+ reviewType,
346
+ attempt: reviewAttempt + 1,
347
+ durationMs: Date.now() - reviewStartedAt,
348
+ outcome:
349
+ reviewResult.reason === REVIEW_TIMEOUT_REASON
350
+ ? "timeout"
351
+ : reviewResult.reason === REVIEW_PROVIDER_ERROR_REASON
352
+ ? "provider_error"
353
+ : "spawn_failed",
354
+ failureReason: typeof reviewResult.reason === "string" ? reviewResult.reason : undefined,
355
+ });
336
356
  recordReviewTaskFailure({
337
357
  projectRoot,
338
358
  state,
@@ -368,6 +388,19 @@ export async function runReviewPollLoop({
368
388
  artifactPath: reviewResult.artifactPath,
369
389
  [attemptKey]: reviewAttempt + 1,
370
390
  });
391
+ // SP-837 (#325): one reviewer row per recorded verdict (attempt is 1-based).
392
+ recordReviewMetric({
393
+ projectRoot,
394
+ config,
395
+ batchId,
396
+ taskId,
397
+ laneNumber,
398
+ reviewType,
399
+ verdict: typeof reviewResult.verdict === "string" ? reviewResult.verdict : undefined,
400
+ attempt: reviewAttempt + 1,
401
+ durationMs: Date.now() - reviewStartedAt,
402
+ outcome: "verdict",
403
+ });
371
404
 
372
405
  if (reviewResult.verdict === passVerdict) {
373
406
  task[attemptField] = reviewAttempt + 1;
@@ -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,
@@ -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",
@@ -8,10 +8,72 @@
8
8
  */
9
9
 
10
10
  const USAGE_FIELDS = ["tokensIn", "tokensOut", "estimatedUsd"];
11
+ const REVIEW_TYPE_ORDER = ["plan", "code", "final"];
11
12
 
12
13
  /**
14
+ * Group `recordType: "review"` rows by `(reviewType, model)` (SP-837 / #325).
15
+ * Tolerates rows missing any new field (`—` / `inherit` buckets, zero counts).
16
+ *
13
17
  * @param {object[]} lines
14
- * @returns {{ byBatch: Record<string, object>, byModel: Record<string, object>, byRole: Record<string, object> } | null}
18
+ * @returns {Array<{ reviewType: string, model: string, count: number, verdicts: Record<string, number>, meanAttempts: number | null, failures: Record<string, number>, failureCount: number }>}
19
+ */
20
+ export function rollupReviews(lines) {
21
+ /** @type {Map<string, { reviewType: string, model: string, count: number, verdicts: Record<string, number>, attemptSum: number, attemptCount: number, failures: Record<string, number>, failureCount: number }>} */
22
+ const groups = new Map();
23
+ for (const line of lines) {
24
+ if (!line || typeof line !== "object" || line.recordType !== "review") continue;
25
+ const reviewType = typeof line.reviewType === "string" ? line.reviewType : "—";
26
+ const model = typeof line.model === "string" && line.model !== "" ? line.model : "inherit";
27
+ const key = `${reviewType}\u0000${model}`;
28
+ let group = groups.get(key);
29
+ if (!group) {
30
+ group = {
31
+ reviewType,
32
+ model,
33
+ count: 0,
34
+ verdicts: {},
35
+ attemptSum: 0,
36
+ attemptCount: 0,
37
+ failures: {},
38
+ failureCount: 0,
39
+ };
40
+ groups.set(key, group);
41
+ }
42
+ group.count += 1;
43
+ const isFailure = typeof line.outcome === "string" && line.outcome !== "verdict";
44
+ if (isFailure) {
45
+ group.failures[line.outcome] = (group.failures[line.outcome] ?? 0) + 1;
46
+ group.failureCount += 1;
47
+ } else {
48
+ const verdict = typeof line.verdict === "string" && line.verdict !== "" ? line.verdict : "—";
49
+ group.verdicts[verdict] = (group.verdicts[verdict] ?? 0) + 1;
50
+ if (Number.isFinite(line.attempt)) {
51
+ group.attemptSum += line.attempt;
52
+ group.attemptCount += 1;
53
+ }
54
+ }
55
+ }
56
+
57
+ const orderOf = (type) => {
58
+ const index = REVIEW_TYPE_ORDER.indexOf(type);
59
+ return index === -1 ? REVIEW_TYPE_ORDER.length : index;
60
+ };
61
+ return [...groups.values()]
62
+ .sort(
63
+ (a, b) =>
64
+ orderOf(a.reviewType) - orderOf(b.reviewType) ||
65
+ a.reviewType.localeCompare(b.reviewType) ||
66
+ a.model.localeCompare(b.model),
67
+ )
68
+ .map(({ attemptSum, attemptCount, ...group }) => ({
69
+ ...group,
70
+ meanAttempts: attemptCount > 0 ? attemptSum / attemptCount : null,
71
+ }));
72
+ }
73
+
74
+ /**
75
+ * @param {object[]} lines
76
+ * @returns {{ byBatch: Record<string, object>, byModel: Record<string, object>, byRole: Record<string, object>, reviews: ReturnType<typeof rollupReviews> } | null}
15
77
  */
16
78
  export function rollupMetrics(lines) {
17
79
  /** @type {Record<string, Record<string, number>>} */
@@ -31,8 +93,9 @@ export function rollupMetrics(lines) {
31
93
  if (hitBatch || hitModel || hitRole) anyUsage = true;
32
94
  }
33
95
 
34
- if (!anyUsage) return null;
35
- return { byBatch, byModel, byRole };
96
+ const reviews = rollupReviews(lines);
97
+ if (!anyUsage && reviews.length === 0) return null;
98
+ return { byBatch, byModel, byRole, reviews };
36
99
  }
37
100
 
38
101
  /**
@@ -64,7 +127,7 @@ function addUsage(store, key, line) {
64
127
  /**
65
128
  * Format rollups as a short human-readable section with one table per grouping.
66
129
  *
67
- * @param {{ byBatch: Record<string, object>, byModel: Record<string, object>, byRole: Record<string, object> }} rollups
130
+ * @param {{ byBatch: Record<string, object>, byModel: Record<string, object>, byRole: Record<string, object>, reviews?: ReturnType<typeof rollupReviews> }} rollups
68
131
  * @returns {string}
69
132
  */
70
133
  export function formatMetricsRollups(rollups) {
@@ -74,12 +137,43 @@ export function formatMetricsRollups(rollups) {
74
137
  formatRollupTable("Usage by batch", rollups.byBatch),
75
138
  formatRollupTable("Usage by model", rollups.byModel),
76
139
  formatRollupTable("Usage by role", rollups.byRole),
140
+ formatReviewRollupTable(rollups.reviews),
77
141
  ];
78
142
  const body = sections.filter(Boolean).join("\n");
79
143
  if (!body) return "";
80
144
  return `\n${body}`;
81
145
  }
82
146
 
147
+ /**
148
+ * @param {ReturnType<typeof rollupReviews> | undefined} reviews
149
+ * @returns {string}
150
+ */
151
+ function formatReviewRollupTable(reviews) {
152
+ if (!Array.isArray(reviews) || reviews.length === 0) return "";
153
+
154
+ const header = ["Review", "Model", "Records", "Verdicts", "Mean Attempts", "Failures"];
155
+ const formatCounts = (counts) =>
156
+ Object.entries(counts)
157
+ .map(([name, count]) => `${name}=${count}`)
158
+ .join(" ") || "—";
159
+ const rows = reviews.map((group) => [
160
+ group.reviewType,
161
+ group.model,
162
+ String(group.count),
163
+ formatCounts(group.verdicts),
164
+ group.meanAttempts == null ? "—" : group.meanAttempts.toFixed(2),
165
+ group.failureCount > 0 ? formatCounts(group.failures) : "0",
166
+ ]);
167
+
168
+ const widths = header.map((col, index) =>
169
+ Math.max(col.length, ...rows.map((row) => String(row[index]).length)),
170
+ );
171
+ const formatRow = (row) =>
172
+ row.map((cell, index) => String(cell).padStart(widths[index])).join(" ");
173
+
174
+ return `Reviews by type and model:\n${[formatRow(header), ...rows.map(formatRow)].join("\n")}`;
175
+ }
176
+
83
177
  /**
84
178
  * @param {string} title
85
179
  * @param {Record<string, object>} groups