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
@@ -3,7 +3,9 @@
3
3
  * Atomic task retry and skip (TP-017, PRD §18.5, FR-BATCH-09/10).
4
4
  */
5
5
 
6
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
6
7
  import { reconcileOrphanRunningState } from "./reconcile.mjs";
8
+ import { resolveRetryProfileOverride } from "./retry-profile.mjs";
7
9
  import {
8
10
  clearTaskFailureMetadata,
9
11
  countPendingSegments,
@@ -18,6 +20,7 @@ import {
18
20
  const RETRY_ALLOWED_PHASES = new Set(["paused", "failed"]);
19
21
  const RETRY_BLOCKED_PHASES = new Set(["running", "planning"]);
20
22
 
23
+ export { ESCALATION_ELIGIBLE_CLASSES, resolveRetryProfileOverride } from "./retry-profile.mjs";
21
24
 
22
25
  /**
23
26
  * Fail running tasks and clear dead engine/worker PIDs before retry/skip (#203 / SP-647).
@@ -201,8 +204,10 @@ export function detectSegmentDrift(state) {
201
204
  * @param {object} params
202
205
  * @param {string} params.projectRoot
203
206
  * @param {string} params.taskId
207
+ * @param {string|null} [params.profile] `--profile <name>`: run the retry on this profile (content/contract failures only).
208
+ * @param {boolean} [params.noEscalate] `--no-escalate`: skip `agents.escalatePolicy` for this retry.
204
209
  */
205
- export function retryTask({ projectRoot, taskId }) {
210
+ export function retryTask({ projectRoot, taskId, profile = null, noEscalate = false }) {
206
211
  const loadedBatch = loadMutableBatch(projectRoot);
207
212
  if (!loadedBatch.ok) return loadedBatch.result;
208
213
  const state = loadedBatch.state;
@@ -257,6 +262,24 @@ export function retryTask({ projectRoot, taskId }) {
257
262
  };
258
263
  }
259
264
 
265
+ // Classify before reset: `resetTaskForRetry` clears `exitReason` / `classification`.
266
+ const profileDecision = resolveRetryProfileOverride({
267
+ task,
268
+ config: loadSpineConfig(projectRoot).config,
269
+ profile,
270
+ noEscalate,
271
+ });
272
+ if (!profileDecision.ok) {
273
+ return {
274
+ ok: false,
275
+ exitCode: 1,
276
+ error: profileDecision.error,
277
+ output: profileDecision.output,
278
+ batchId: state.batchId,
279
+ taskId,
280
+ };
281
+ }
282
+
260
283
  const reset = resetTaskForRetry(state, taskId);
261
284
  if (!reset) {
262
285
  return {
@@ -267,6 +290,7 @@ export function retryTask({ projectRoot, taskId }) {
267
290
  batchId: state.batchId,
268
291
  };
269
292
  }
293
+ if (profileDecision.apply) task.profileOverride = profileDecision.profileOverride;
270
294
 
271
295
  // Matrix tasks (#230): succeeded rows carry over (never re-executed) and
272
296
  // canceled rows stay excluded — only failed rows re-enter the sweep.
@@ -294,6 +318,8 @@ export function retryTask({ projectRoot, taskId }) {
294
318
  taskId,
295
319
  previousClassification: reset.previousClassification,
296
320
  pendingSegments,
321
+ profileOverride: profileDecision.profileOverride,
322
+ escalation: profileDecision.escalation,
297
323
  ...(retriedRowIds.length > 0 ? { retriedRowIds } : {}),
298
324
  },
299
325
  });
@@ -317,6 +343,9 @@ export function retryTask({ projectRoot, taskId }) {
317
343
  if (retriedRowIds.length > 0) {
318
344
  output += `\n Matrix rows re-running: ${retriedRowIds.join(", ")} (succeeded rows carry over).`;
319
345
  }
346
+ if (profileDecision.escalation) {
347
+ output += `\n Profile override: ${profileDecision.profileOverride} (${profileDecision.escalation === "auto" ? "escalatePolicy" : "--profile"}).`;
348
+ }
320
349
  output += `\n → ${resumeHint}\n`;
321
350
 
322
351
  return {
@@ -326,6 +355,8 @@ export function retryTask({ projectRoot, taskId }) {
326
355
  taskId,
327
356
  pendingSegments,
328
357
  unblocked,
358
+ profileOverride: profileDecision.profileOverride,
359
+ escalation: profileDecision.escalation,
329
360
  ...(retriedRowIds.length > 0 ? { retriedRowIds } : {}),
330
361
  output,
331
362
  };
@@ -6,6 +6,7 @@
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
+ import { resolveReviewerModelPin, resolveReviewerThinkingPin } from "../config/agent-model-resolve.mjs";
9
10
  import { readJournalEvents } from "./journal.mjs";
10
11
  import {
11
12
  ARTIFACT_READY_HONOR_REASON,
@@ -127,11 +128,14 @@ export async function runStepReview({
127
128
  contractVerifyResult,
128
129
  });
129
130
 
131
+ // SP-834 (#355): effective reviewer of the (per-task) config; null means inherit.
130
132
  journalReviewEvent("review.started", journal, {
131
133
  stepNumber,
132
134
  reviewType,
133
135
  reviewLevel,
134
136
  artifactPath,
137
+ reviewerModel: resolveReviewerModelPin(config, reviewType),
138
+ reviewerThinking: resolveReviewerThinkingPin(config, reviewType),
135
139
  });
136
140
 
137
141
  const useStub =
@@ -140,6 +140,7 @@ export function buildReviewRequest({
140
140
  "## Output",
141
141
  `Write your review to: \`${outputPath}\``,
142
142
  "Include `### Verdict: PASS`, `### Verdict: REVISE`, or `### Verdict: REPLAN` and a JSON block.",
143
+ 'Final verdicts are PASS, REVISE, or REPLAN only — APPROVE is rejected. JSON shape: `{"verdict":"PASS","feedback":"..."}`',
143
144
  ].join("\n");
144
145
  }
145
146
  if (reviewType === "plan") {
@@ -110,7 +110,8 @@ export function createWorkerPollState(startedAt, workerPhase) {
110
110
  * @param {string} [params.laneCorrelationId]
111
111
  * @param {boolean} params.useStub
112
112
  * @param {string} params.workerBackend
113
- * @param {boolean} params.childPastPreflight
113
+ * @param {boolean} [params.childPastPreflight] Static snapshot of preflight state; kept for existing callers.
114
+ * @param {() => boolean} [params.isPastPreflight] Live preflight getter read on every poll (#353); wins over `childPastPreflight`.
114
115
  * @param {(timestamp: number) => void} [params.onHeartbeat]
115
116
  * @param {(failure: {
116
117
  * rawOutput: string;
@@ -147,6 +148,7 @@ export async function pollWorkerUntilSettled({
147
148
  useStub,
148
149
  workerBackend,
149
150
  childPastPreflight,
151
+ isPastPreflight,
150
152
  onHeartbeat,
151
153
  buildFailureResult,
152
154
  workerMode,
@@ -240,7 +242,13 @@ export async function pollWorkerUntilSettled({
240
242
  : undefined,
241
243
  }),
242
244
  );
243
- const nextWorkerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
245
+ const pastPreflight =
246
+ typeof isPastPreflight === "function" ? isPastPreflight() : Boolean(childPastPreflight);
247
+ const nextWorkerPhase = resolveWorkerPhase({
248
+ childPastPreflight: pastPreflight,
249
+ useStub,
250
+ workerBackend,
251
+ });
244
252
  if (nextWorkerPhase !== "launching" && workerPhase === "launching") {
245
253
  stallAnchorAt = now;
246
254
  lastCheckpointAt = now;
@@ -363,7 +363,7 @@ export async function runWorker({
363
363
  laneCorrelationId,
364
364
  useStub,
365
365
  workerBackend,
366
- childPastPreflight,
366
+ isPastPreflight: () => childPastPreflight,
367
367
  onHeartbeat,
368
368
  workerMode,
369
369
  buildFailureResult: (
@@ -13,16 +13,15 @@ export function buildReviewLevelHint(reviewLevel) {
13
13
  return "";
14
14
  }
15
15
  let hint =
16
- "When Review Level ≥ 1, run plan review only at step checkpoints: spine review step --step N --type plan (or spine_review_step with type=plan). ";
16
+ "Reviews run in the batch engine after .DONE, not in the worker: do not call spine_review_step or spine review step from the worker. ";
17
17
  if (reviewLevel >= 2) {
18
18
  hint +=
19
- "Do not run code or final review from inside the worker — the batch engine runs those after .DONE. ";
19
+ "At Review Level 2 the engine runs plan review, code review, and final review after .DONE. ";
20
20
  } else {
21
- hint +=
22
- "Do not run final review from the worker — the batch engine runs final review after .DONE. ";
21
+ hint += "At Review Level 1 the engine runs plan review and final review after .DONE. ";
23
22
  }
24
23
  hint +=
25
- "On REVISE, fix feedback before continuing. On review spawn failure, stop with non-zero exit. After creating .DONE, exit immediately with no further tool calls or reviewer spawns. ";
24
+ "If the engine returns REVISE feedback, address it when resumed. After creating .DONE, exit immediately with no further tool calls or reviewer spawns. ";
26
25
  return hint;
27
26
  }
28
27
 
package/src/cli/deps.mjs CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  import { buildGraph, topoWaves } from '../planner/graph.mjs';
13
13
  import { findCyclePath } from '../planner/cycles.mjs';
14
14
  import { parseScope } from '../planner/scope.mjs';
15
+ import { compareTaskIds } from '../tasks/packet/discover.mjs';
15
16
 
16
17
  /**
17
18
  * @param {string} projectRoot
@@ -42,7 +43,7 @@ export function depsToEdges(depsByTask) {
42
43
  }
43
44
  }
44
45
 
45
- edges.sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to));
46
+ edges.sort((a, b) => compareTaskIds(a.from, b.from) || compareTaskIds(a.to, b.to));
46
47
  return edges;
47
48
  }
48
49
 
@@ -55,7 +56,7 @@ export function cycleNodesFromPath(cyclePath) {
55
56
  const nodes = cyclePath[cyclePath.length - 1] === cyclePath[0]
56
57
  ? cyclePath.slice(0, -1)
57
58
  : cyclePath;
58
- return [...new Set(nodes.map(String))].sort();
59
+ return [...new Set(nodes.map(String))].sort(compareTaskIds);
59
60
  }
60
61
 
61
62
  /**
@@ -3,13 +3,17 @@
3
3
  * Agent model/thinking pin resolution for reviewer spawns (issue #53 / SP-369).
4
4
  */
5
5
 
6
+ import { isSameModelFamily } from "./model-family.mjs";
7
+
8
+ /** @type {readonly ("plan"|"code"|"final")[]} */
9
+ const REVIEW_TYPES = ["plan", "code", "final"];
10
+
6
11
  /**
7
- * @param {object} config
12
+ * @param {unknown} reviewer A reviewer block (`agents.reviewer` or `profile.reviewer`).
8
13
  * @param {"plan"|"code"|"final"} reviewType
9
- * @returns {string|null} Pin value or null to omit `--model`
14
+ * @returns {string|null}
10
15
  */
11
- export function resolveReviewerModelPin(config, reviewType) {
12
- const reviewer = config?.agents?.reviewer;
16
+ function pickModelPin(reviewer, reviewType) {
13
17
  if (!reviewer) return null;
14
18
 
15
19
  const typePin = reviewer[reviewType]?.model;
@@ -26,12 +30,11 @@ export function resolveReviewerModelPin(config, reviewType) {
26
30
  }
27
31
 
28
32
  /**
29
- * @param {object} config
33
+ * @param {unknown} reviewer A reviewer block (`agents.reviewer` or `profile.reviewer`).
30
34
  * @param {"plan"|"code"|"final"} reviewType
31
- * @returns {string|null} Pin value or null to omit `--thinking`
35
+ * @returns {string|null}
32
36
  */
33
- export function resolveReviewerThinkingPin(config, reviewType) {
34
- const reviewer = config?.agents?.reviewer;
37
+ function pickThinkingPin(reviewer, reviewType) {
35
38
  if (!reviewer) return null;
36
39
 
37
40
  const typePin = reviewer[reviewType]?.thinking;
@@ -47,3 +50,136 @@ export function resolveReviewerThinkingPin(config, reviewType) {
47
50
 
48
51
  return null;
49
52
  }
53
+
54
+ /**
55
+ * @param {object} config
56
+ * @param {"plan"|"code"|"final"} reviewType
57
+ * @returns {string|null} Pin value or null to omit `--model`
58
+ */
59
+ export function resolveReviewerModelPin(config, reviewType) {
60
+ return pickModelPin(config?.agents?.reviewer, reviewType);
61
+ }
62
+
63
+ /**
64
+ * @param {object} config
65
+ * @param {"plan"|"code"|"final"} reviewType
66
+ * @returns {string|null} Pin value or null to omit `--thinking`
67
+ */
68
+ export function resolveReviewerThinkingPin(config, reviewType) {
69
+ return pickThinkingPin(config?.agents?.reviewer, reviewType);
70
+ }
71
+
72
+ /**
73
+ * @param {unknown} value
74
+ * @returns {string|null} Trimmed non-empty string, else null
75
+ */
76
+ function nonEmptyName(value) {
77
+ if (typeof value !== "string") return null;
78
+ const trimmed = value.trim();
79
+ return trimmed === "" ? null : trimmed;
80
+ }
81
+
82
+ /**
83
+ * Resolve the effective reviewer (model + thinking) per review type (SP-832 / #355).
84
+ *
85
+ * Candidate order (first cross-family usable candidate wins, per review type):
86
+ * 1. `promptReviewerProfile`
87
+ * 2. `agents.profiles[workerProfile].reviewerProfile`
88
+ * 3. `agents.reviewerProfile`
89
+ * 4. the already-merged `agents.reviewer` block
90
+ *
91
+ * A named profile that does not exist is reported in `blocked` (`unknown_reviewer_profile`);
92
+ * one without a `reviewer` block is skipped with a warning. A candidate whose model shares a
93
+ * family with `workerModel` is skipped for that review type; when none is cross-family the
94
+ * type is reported in `blocked` (`same_model_family`) and the last candidate's pins are kept.
95
+ *
96
+ * Pure: no I/O, never mutates `config`.
97
+ *
98
+ * @param {object} config Effective config (active profile already merged into `agents.reviewer`).
99
+ * @param {object} [options]
100
+ * @param {string|null} [options.promptReviewerProfile]
101
+ * @param {string|null} [options.workerProfile]
102
+ * @param {string|null} [options.workerModel]
103
+ * @returns {{
104
+ * plan: { model: string|null, thinking: string|null, profile: string|null, source: string },
105
+ * code: { model: string|null, thinking: string|null, profile: string|null, source: string },
106
+ * final: { model: string|null, thinking: string|null, profile: string|null, source: string },
107
+ * warnings: string[],
108
+ * blocked: Array<{ reviewType: "plan"|"code"|"final", reason: string }>,
109
+ * }}
110
+ */
111
+ export function resolveEffectiveReviewer(
112
+ config,
113
+ { promptReviewerProfile = null, workerProfile = null, workerModel = null } = {},
114
+ ) {
115
+ const agents = config?.agents ?? {};
116
+ const profiles = agents.profiles && typeof agents.profiles === "object" ? agents.profiles : {};
117
+ const workerProfileName = nonEmptyName(workerProfile);
118
+ /** @type {string[]} */
119
+ const warnings = [];
120
+ /** @type {Array<{ reviewType: "plan"|"code"|"final", reason: string }>} */
121
+ const blocked = [];
122
+
123
+ /** @type {Array<{ profile: string|null, source: string, reviewer: unknown }>} */
124
+ const candidates = [];
125
+ /** @type {Set<string>} */
126
+ const seenNames = new Set();
127
+ /** @type {Array<[string|null, string]>} */
128
+ const named = [
129
+ [nonEmptyName(promptReviewerProfile), "prompt.reviewerProfile"],
130
+ [
131
+ workerProfileName ? nonEmptyName(profiles[workerProfileName]?.reviewerProfile) : null,
132
+ `agents.profiles.${workerProfileName}.reviewerProfile`,
133
+ ],
134
+ [nonEmptyName(agents.reviewerProfile), "agents.reviewerProfile"],
135
+ ];
136
+ for (const [name, source] of named) {
137
+ if (name === null || seenNames.has(name)) continue;
138
+ seenNames.add(name);
139
+ const profile = Object.hasOwn(profiles, name) ? profiles[name] : undefined;
140
+ if (!profile || typeof profile !== "object") {
141
+ for (const reviewType of REVIEW_TYPES) {
142
+ blocked.push({ reviewType, reason: "unknown_reviewer_profile" });
143
+ }
144
+ warnings.push(`reviewer profile "${name}" (${source}) is not defined in agents.profiles`);
145
+ continue;
146
+ }
147
+ if (!profile.reviewer || typeof profile.reviewer !== "object") {
148
+ warnings.push(`reviewer profile "${name}" has no reviewer block; falling back`);
149
+ continue;
150
+ }
151
+ candidates.push({ profile: name, source, reviewer: profile.reviewer });
152
+ }
153
+ candidates.push({ profile: null, source: "agents.reviewer", reviewer: agents.reviewer });
154
+
155
+ /** @type {Record<string, { model: string|null, thinking: string|null, profile: string|null, source: string }>} */
156
+ const resolved = {};
157
+ for (const reviewType of REVIEW_TYPES) {
158
+ let chosen = null;
159
+ let sameFamily = false;
160
+ for (const candidate of candidates) {
161
+ const model = pickModelPin(candidate.reviewer, reviewType);
162
+ chosen = {
163
+ model,
164
+ thinking: pickThinkingPin(candidate.reviewer, reviewType),
165
+ profile: candidate.profile,
166
+ source: candidate.source,
167
+ };
168
+ sameFamily = isSameModelFamily(model, workerModel);
169
+ if (!sameFamily) break;
170
+ warnings.push(
171
+ `${reviewType} reviewer "${model}" (${candidate.source}) shares a model family with worker "${workerModel}"; skipping`,
172
+ );
173
+ }
174
+ if (sameFamily) blocked.push({ reviewType, reason: "same_model_family" });
175
+ resolved[reviewType] = chosen;
176
+ }
177
+
178
+ return {
179
+ plan: resolved.plan,
180
+ code: resolved.code,
181
+ final: resolved.final,
182
+ warnings: [...new Set(warnings)],
183
+ blocked,
184
+ };
185
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Model family classification for reviewer/worker independence checks (SP-832 / #355).
3
+ *
4
+ * Families are coarser than providers (`cursor/gemini-3.1-pro` and `google/gemini-2.5-pro`
5
+ * are both "gemini"). Do not reuse `resolvePoolId` from quota-snapshot — that is provider-keyed.
6
+ */
7
+
8
+ /** @typedef {"gemini"|"claude"|"glm"|"kimi"|"gpt"|"qwen"|"unknown"} ModelFamily */
9
+
10
+ /** @type {ReadonlyArray<readonly [RegExp, ModelFamily]>} */
11
+ const NAME_FAMILY_RULES = Object.freeze([
12
+ [/^gemini/, "gemini"],
13
+ [/^claude/, "claude"],
14
+ [/^glm/, "glm"],
15
+ [/^kimi/, "kimi"],
16
+ [/^k\d/, "kimi"],
17
+ [/^gpt/, "gpt"],
18
+ [/^o\d/, "gpt"],
19
+ [/^qwen/, "qwen"],
20
+ ]);
21
+
22
+ /** @type {Readonly<Record<string, ModelFamily>>} */
23
+ const PROVIDER_FAMILY = Object.freeze({
24
+ google: "gemini",
25
+ anthropic: "claude",
26
+ zai: "glm",
27
+ "kimi-coding": "kimi",
28
+ });
29
+
30
+ /**
31
+ * @param {unknown} model Model id such as `google/gemini-2.5-pro`, `inherit`, or null.
32
+ * @returns {ModelFamily}
33
+ */
34
+ export function resolveModelFamily(model) {
35
+ if (typeof model !== "string") return "unknown";
36
+ const normalized = model.trim().toLowerCase();
37
+ if (normalized === "") return "unknown";
38
+
39
+ const slash = normalized.indexOf("/");
40
+ const provider = slash === -1 ? "" : normalized.slice(0, slash);
41
+ const name = normalized.slice(normalized.lastIndexOf("/") + 1);
42
+
43
+ for (const [pattern, family] of NAME_FAMILY_RULES) {
44
+ if (pattern.test(name)) return family;
45
+ }
46
+ return PROVIDER_FAMILY[provider] ?? "unknown";
47
+ }
48
+
49
+ /**
50
+ * True only when both models resolve to the same known family.
51
+ *
52
+ * @param {unknown} a
53
+ * @param {unknown} b
54
+ * @returns {boolean}
55
+ */
56
+ export function isSameModelFamily(a, b) {
57
+ const familyA = resolveModelFamily(a);
58
+ if (familyA === "unknown") return false;
59
+ return familyA === resolveModelFamily(b);
60
+ }
@@ -311,6 +311,7 @@ export function checkTasksValidate(ctx) {
311
311
  const validation = validatePrompt(promptMarkdown, {
312
312
  taskId: discoveredTask.taskId,
313
313
  contract: config.contract,
314
+ agents: config.agents,
314
315
  });
315
316
  if (!validation.ok) {
316
317
  failures.push(
@@ -162,6 +162,12 @@ export const SETTINGS_FIELDS = Object.freeze([
162
162
  type: "string",
163
163
  optional: true,
164
164
  },
165
+ {
166
+ path: "agents.reviewerProfile",
167
+ label: "Reviewer agent model profile (cross-family review)",
168
+ type: "string",
169
+ optional: true,
170
+ },
165
171
  {
166
172
  path: "dashboard.port",
167
173
  label: "Dashboard port",
@@ -308,6 +308,31 @@ export function validateAgentProfilesConfig(config) {
308
308
  "spine init --force",
309
309
  );
310
310
  if (profileReviewerError) return profileReviewerError;
311
+ // SP-832 / #355: profile-level reviewer profile; must name another defined profile.
312
+ if (profile.reviewerProfile != null) {
313
+ if (typeof profile.reviewerProfile !== "string") {
314
+ return {
315
+ code: "CONFIG_AGENT_PROFILE_INVALID",
316
+ message: `agents.profiles.${name}.reviewerProfile must be a string when set`,
317
+ suggestedCommand: "spine init --force",
318
+ };
319
+ }
320
+ const reviewerTarget = profile.reviewerProfile.trim();
321
+ if (reviewerTarget !== "" && reviewerTarget === name) {
322
+ return {
323
+ code: "CONFIG_AGENT_PROFILE_INVALID",
324
+ message: `agents.profiles.${name}.reviewerProfile must not name the profile itself`,
325
+ suggestedCommand: "spine settings set agents.reviewerProfile default",
326
+ };
327
+ }
328
+ if (reviewerTarget !== "" && !Object.prototype.hasOwnProperty.call(profiles, reviewerTarget)) {
329
+ return {
330
+ code: "CONFIG_AGENT_PROFILE_INVALID",
331
+ message: `agents.profiles.${name}.reviewerProfile "${reviewerTarget}" does not match a defined agents.profiles entry`,
332
+ suggestedCommand: "spine settings set agents.reviewerProfile default",
333
+ };
334
+ }
335
+ }
311
336
  }
312
337
  }
313
338
 
@@ -358,6 +383,30 @@ export function validateAgentProfilesConfig(config) {
358
383
  }
359
384
  }
360
385
 
386
+ // SP-832 / #355: profile whose reviewer block reviews all workers; same membership rule as quotaFallbackProfile.
387
+ const reviewerProfile = agents.reviewerProfile;
388
+ if (reviewerProfile != null) {
389
+ if (typeof reviewerProfile !== "string") {
390
+ return {
391
+ code: "CONFIG_AGENT_PROFILE_INVALID",
392
+ message: "agents.reviewerProfile must be a string when set",
393
+ suggestedCommand: "spine settings set agents.reviewerProfile default",
394
+ };
395
+ }
396
+ const reviewerTarget = reviewerProfile.trim();
397
+ // An empty string unsets the reviewer profile; otherwise it must name a real profile.
398
+ if (
399
+ reviewerTarget !== "" &&
400
+ (!isPlainObject(profiles) || !Object.prototype.hasOwnProperty.call(profiles, reviewerTarget))
401
+ ) {
402
+ return {
403
+ code: "CONFIG_AGENT_PROFILE_INVALID",
404
+ message: `agents.reviewerProfile "${reviewerTarget}" does not match a defined agents.profiles entry`,
405
+ suggestedCommand: "spine settings set agents.reviewerProfile default",
406
+ };
407
+ }
408
+ }
409
+
361
410
  const escalatePolicy = agents.escalatePolicy;
362
411
  if (escalatePolicy != null) {
363
412
  if (!isPlainObject(escalatePolicy)) {
@@ -9,6 +9,7 @@ import os from "node:os";
9
9
  import path from "node:path";
10
10
 
11
11
  import {
12
+ resolveEffectiveReviewer,
12
13
  resolveReviewerModelPin,
13
14
  resolveReviewerThinkingPin,
14
15
  } from "../config/agent-model-resolve.mjs";
@@ -100,14 +101,90 @@ export function formatReviewerEffectivePins(config = {}) {
100
101
  }
101
102
 
102
103
  /**
104
+ * @param {unknown} value
105
+ * @returns {string|null}
106
+ */
107
+ function nonEmptyString(value) {
108
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : null;
109
+ }
110
+
111
+ /**
112
+ * Worker pairings to report: active profile, quota fallback, escalate target (deduped, in that order).
113
+ *
114
+ * @param {object} config
115
+ * @returns {Array<{ profile: string|null, label: string, workerModel: string|null }>}
116
+ */
117
+ function listWorkerPairings(config) {
118
+ const agents = config?.agents ?? {};
119
+ const profiles = agents.profiles ?? {};
120
+ const active = nonEmptyString(agents.activeProfile);
121
+ const names = [active];
122
+ names.push(nonEmptyString(agents.quotaFallbackProfile));
123
+ if (agents.escalatePolicy?.toProfile != null) {
124
+ names.push(nonEmptyString(agents.escalatePolicy.toProfile));
125
+ }
126
+
127
+ const seen = new Set();
128
+ const pairings = [];
129
+ for (const [index, name] of names.entries()) {
130
+ if (index > 0 && name === null) continue;
131
+ const key = name ?? "";
132
+ if (seen.has(key)) continue;
133
+ seen.add(key);
134
+ // The active profile is already merged into agents.worker; other profiles overlay their own worker pin.
135
+ const profileWorkerModel = name && name !== active ? profiles[name]?.worker?.model : undefined;
136
+ const workerModel = nonEmptyString(profileWorkerModel) ?? nonEmptyString(agents.worker?.model);
137
+ pairings.push({
138
+ profile: name,
139
+ label: name ?? "default",
140
+ workerModel: workerModel === "inherit" ? null : workerModel,
141
+ });
142
+ }
143
+ return pairings;
144
+ }
145
+
146
+ /**
147
+ * Effective reviewer per worker pairing (SP-832 / #355). Fails when a pairing is blocked
148
+ * (same model family or unknown reviewer profile); warnings keep the check `ok`.
149
+ *
103
150
  * @param {object} params
104
151
  * @param {object} [params.config]
105
152
  */
106
153
  export function buildReviewerPerTypePinsDoctorCheck({ config = {} } = {}) {
154
+ const details = [];
155
+ const warnings = [];
156
+ const problems = [];
157
+
158
+ for (const pairing of listWorkerPairings(config)) {
159
+ const effective = resolveEffectiveReviewer(config, {
160
+ workerProfile: pairing.profile,
161
+ workerModel: pairing.workerModel,
162
+ });
163
+ const pins = REVIEW_TYPES.map((reviewType) => {
164
+ const entry = effective[reviewType];
165
+ return `${reviewType}=${entry.model ?? "inherit"}/${entry.thinking ?? "inherit"}`;
166
+ }).join(", ");
167
+ details.push(`${pairing.label}: worker=${pairing.workerModel ?? "inherit"} → ${pins}`);
168
+ warnings.push(...effective.warnings);
169
+ for (const entry of effective.blocked) {
170
+ problems.push(`${pairing.label}: ${entry.reviewType} reviewer blocked (${entry.reason})`);
171
+ }
172
+ }
173
+
174
+ const detail = [...details, ...warnings.map((w) => `warning: ${w}`)].join("; ");
175
+ if (problems.length > 0) {
176
+ return {
177
+ label: "reviewer model pins (per-type)",
178
+ ok: false,
179
+ detail: `${detail}; ${[...new Set(problems)].join("; ")}`,
180
+ suggestedCommand: "spine settings set agents.reviewerProfile <name>",
181
+ };
182
+ }
107
183
  return {
108
184
  label: "reviewer model pins (per-type)",
109
185
  ok: true,
110
- detail: formatReviewerEffectivePins(config),
186
+ ...(warnings.length > 0 ? { warning: true } : {}),
187
+ detail,
111
188
  };
112
189
  }
113
190
 
@@ -460,7 +460,10 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
460
460
  );
461
461
  checks.push(buildStallConfigDoctorCheck({ config: configResult.config }));
462
462
  checks.push(buildPiWorkerTimeoutDoctorCheck({ config: configResult.config }));
463
- checks.push(buildReviewerPerTypePinsDoctorCheck({ config: configResult.config }));
463
+ const reviewerPinsCheck = buildReviewerPerTypePinsDoctorCheck({ config: configResult.config });
464
+ checks.push(reviewerPinsCheck);
465
+ // SP-832 / #355: same-family worker/reviewer pairing blocks doctor and (via doctor) preflight.
466
+ if (!reviewerPinsCheck.ok) issueCount++;
464
467
  checks.push(buildAgentModelInheritDoctorCheck({
465
468
  config: configResult.config,
466
469
  projectRoot,
@@ -32,6 +32,18 @@ function formatReportFilename(now) {
32
32
  return `quota-snapshot-${iso}.json`;
33
33
  }
34
34
 
35
+ /**
36
+ * Format one quota window as `5h 63% (resets 2026-10-15T06:28:41Z)`.
37
+ *
38
+ * @param {import("./quota-probes.mjs").QuotaWindow} win
39
+ * @returns {string}
40
+ */
41
+ function formatWindow(win) {
42
+ let text = `${win.window} ${Math.round(win.percentUsed)}%`;
43
+ if (win.resetAt) text += ` (resets ${win.resetAt.replace(/\.\d+Z$/, "Z")})`;
44
+ return text;
45
+ }
46
+
35
47
  /**
36
48
  * Format a short human-readable summary of the snapshot.
37
49
  *
@@ -55,11 +67,15 @@ function formatHumanSummary(snapshot, reportPath) {
55
67
  for (const pool of pools) {
56
68
  const usage = pool.usage;
57
69
  const parts = [`${pool.poolId}: ${usage.taskCount} tasks`];
70
+ if (usage.reviewCount) parts.push(`${usage.reviewCount} reviews`);
58
71
  if (usage.durationMs > 0) parts.push(`${usage.durationMs}ms`);
59
72
  if (usage.tokensIn) parts.push(`${usage.tokensIn} in-tokens`);
60
73
  if (usage.tokensOut) parts.push(`${usage.tokensOut} out-tokens`);
61
74
  if (usage.estimatedUsd) parts.push(`$${usage.estimatedUsd.toFixed(4)} est`);
62
75
  lines.push(` ${parts.join(", ")}`);
76
+ for (const win of pool.windows ?? []) {
77
+ lines.push(` ${formatWindow(win)}`);
78
+ }
63
79
  }
64
80
 
65
81
  if (reportPath) {