pi-spine 2.27.0 → 2.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/bin/spine-batch.mjs +46 -4
  2. package/bin/spine-tasks.mjs +1 -0
  3. package/bin/spine-worker-runner.mjs +17 -3
  4. package/package.json +1 -1
  5. package/skills/create-spine-tasks/SKILL.md +60 -33
  6. package/skills/create-spine-tasks/references/authoring-evidence.md +58 -0
  7. package/skills/create-spine-tasks/references/contract-template.md +52 -7
  8. package/skills/create-spine-tasks/references/prompt-template.md +77 -8
  9. package/skills/spine-release-operator/SKILL.md +43 -52
  10. package/skills/spine-release-operator/references/issue-intake-checklist.md +3 -1
  11. package/skills/spine-release-operator/references/pi-async-orchestration.md +13 -9
  12. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +8 -1
  13. package/skills/spine-release-operator/references/publish-recovery.md +62 -0
  14. package/src/batch/contract-task-start.mjs +23 -1
  15. package/src/batch/diagnosis-alternatives.mjs +16 -1
  16. package/src/batch/diagnosis-handoff-packet.mjs +18 -0
  17. package/src/batch/diagnosis-pending-lane.mjs +18 -0
  18. package/src/batch/diagnosis-review-infra.mjs +144 -0
  19. package/src/batch/diagnosis-suggested-command.mjs +9 -0
  20. package/src/batch/diagnosis.mjs +19 -20
  21. package/src/batch/engine-lanes/merge.mjs +0 -8
  22. package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
  23. package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
  24. package/src/batch/engine-lanes/review-code.mjs +20 -0
  25. package/src/batch/engine-lanes/review-final.mjs +10 -2
  26. package/src/batch/engine-lanes/review-poll.mjs +37 -1
  27. package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
  28. package/src/batch/engine-lanes.mjs +18 -18
  29. package/src/batch/gate-posture-approve.mjs +154 -15
  30. package/src/batch/integrate-path-delete.mjs +85 -0
  31. package/src/batch/integrate-worktree.mjs +20 -27
  32. package/src/batch/journal.mjs +5 -3
  33. package/src/batch/metrics-rollup.mjs +98 -4
  34. package/src/batch/metrics.mjs +134 -9
  35. package/src/batch/provider-quota.mjs +156 -7
  36. package/src/batch/quota-fallback.mjs +87 -6
  37. package/src/batch/reconcile-diagnosis.mjs +24 -77
  38. package/src/batch/resume-lane-reviews.mjs +11 -10
  39. package/src/batch/retry-profile.mjs +77 -0
  40. package/src/batch/retry.mjs +32 -1
  41. package/src/batch/review-artifacts.mjs +3 -2
  42. package/src/batch/review-level-effective.mjs +19 -0
  43. package/src/batch/review-spawn.mjs +12 -1
  44. package/src/batch/review-step-run.mjs +18 -2
  45. package/src/batch/review-step.mjs +1 -0
  46. package/src/batch/reviewer-provider-error.mjs +153 -0
  47. package/src/batch/worker-heartbeat.mjs +10 -2
  48. package/src/batch/worker-host.mjs +1 -1
  49. package/src/batch/worker-prompt.mjs +9 -7
  50. package/src/cli/deps.mjs +3 -2
  51. package/src/config/agent-model-resolve.mjs +144 -8
  52. package/src/config/cursor-rules/discover.mjs +38 -1
  53. package/src/config/model-family.mjs +60 -0
  54. package/src/config/preflight/discovery.mjs +1 -0
  55. package/src/config/settings-fields.mjs +11 -0
  56. package/src/config/spine-config-schema.mjs +87 -0
  57. package/src/doctor/agent-model-inherit.mjs +78 -1
  58. package/src/doctor/pi-extension-hooks.mjs +322 -0
  59. package/src/doctor/run-doctor-checks.mjs +18 -2
  60. package/src/metrics/quota-cli.mjs +16 -0
  61. package/src/metrics/quota-probes.mjs +228 -31
  62. package/src/metrics/quota-snapshot.mjs +21 -2
  63. package/src/planner/graph.mjs +7 -5
  64. package/src/planner/pending.mjs +2 -2
  65. package/src/planner/scope.mjs +3 -3
  66. package/src/tasks/packet/parse-prompt.mjs +47 -0
  67. package/src/tasks/packet/validate-prompt.mjs +167 -2
  68. package/src/tasks/validate-contract-warn.mjs +16 -0
  69. package/templates/agents/reviewer.md +3 -1
  70. package/templates/agents/worker.md +15 -19
  71. package/templates/spine-config.json +1 -1
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Merge-deletion materialization for the post-merge base sync (SP-830, #346).
3
+ * Opt-in per call via `applyDeletions` on syncPlumbingMergePathsToWorktree;
4
+ * the human `spine sync-base` flow does not opt in and keeps the skip (SP-784).
5
+ * Deliberately does not import from integrate-worktree.mjs (no import cycle).
6
+ */
7
+
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { execFileSync } from "node:child_process";
11
+ import { resolveGitCommitEnv } from "./git-commit-env.mjs";
12
+
13
+ /**
14
+ * Timeout detection for execFileSync `timeout` kills; shared with the sync loop.
15
+ * @param {unknown} err
16
+ * @returns {boolean}
17
+ */
18
+ export function isTimeoutError(err) {
19
+ if (!err || typeof err !== "object") return false;
20
+ return /** @type {any} */ (err).killed === true || /** @type {any} */ (err).code === "ETIMEDOUT";
21
+ }
22
+
23
+ /**
24
+ * Remove from the checkout a path the merged tree deleted (SP-830). Untracks it
25
+ * with `git rm --cached`. Regular files are only removed when their worktree
26
+ * content matches the index (`git diff --quiet`): an unmodified stale entry is
27
+ * the ref-move artifact integrate leaves behind, while a modified or deleted
28
+ * file is operator work and is left alone. A `160000` gitlink directory is
29
+ * always kept on disk — it may host a live nested worktree. Paths never present
30
+ * at baseSha return `{ removed: false }` (caller keeps today's skip). Git
31
+ * failures return `{ removed: false }`; timeouts are rethrown so the caller
32
+ * reports `timedOut` like its other git calls.
33
+ *
34
+ * @param {string} projectRoot
35
+ * @param {string} baseSha
36
+ * @param {string} filePath
37
+ * @param {{ timeoutMs?: number }} [options]
38
+ * @returns {{ removed: boolean, gitlink?: boolean }}
39
+ */
40
+ export function removeMergeDeletedPath(projectRoot, baseSha, filePath, { timeoutMs } = {}) {
41
+ let entry = "";
42
+ try {
43
+ entry = execFileSync("git", ["ls-tree", baseSha, "--", filePath], {
44
+ cwd: projectRoot,
45
+ encoding: "utf-8",
46
+ stdio: ["ignore", "pipe", "pipe"],
47
+ timeout: timeoutMs,
48
+ env: { ...process.env, ...resolveGitCommitEnv(projectRoot) },
49
+ });
50
+ } catch (err) {
51
+ if (isTimeoutError(err)) throw err;
52
+ return { removed: false };
53
+ }
54
+ if (!entry.trim()) return { removed: false };
55
+ const gitlink = entry.startsWith("160000");
56
+ if (!gitlink) {
57
+ try {
58
+ execFileSync("git", ["diff", "--quiet", "--", filePath], {
59
+ cwd: projectRoot,
60
+ encoding: "utf-8",
61
+ stdio: ["ignore", "pipe", "pipe"],
62
+ timeout: timeoutMs,
63
+ env: { ...process.env, ...resolveGitCommitEnv(projectRoot) },
64
+ });
65
+ } catch (err) {
66
+ if (isTimeoutError(err)) throw err;
67
+ // exit 1: worktree differs from index — operator edit or local deletion.
68
+ return { removed: false };
69
+ }
70
+ }
71
+ try {
72
+ execFileSync("git", ["rm", "-q", "--cached", "--ignore-unmatch", "--", filePath], {
73
+ cwd: projectRoot,
74
+ encoding: "utf-8",
75
+ stdio: ["ignore", "pipe", "pipe"],
76
+ timeout: timeoutMs,
77
+ env: { ...process.env, ...resolveGitCommitEnv(projectRoot) },
78
+ });
79
+ } catch (err) {
80
+ if (isTimeoutError(err)) throw err;
81
+ return { removed: false };
82
+ }
83
+ if (!gitlink) fs.rmSync(path.join(projectRoot, filePath), { force: true });
84
+ return { removed: true, gitlink };
85
+ }
@@ -9,9 +9,10 @@ import path from "node:path";
9
9
  import { execFileSync } from "node:child_process";
10
10
  import { gitExec } from "./git-exec.mjs";
11
11
  import { resolveGitCommitEnv } from "./git-commit-env.mjs";
12
- import { tryAutoResolveRulesManifestMergeConflict } from "./engine-lanes/merge.mjs";
12
+ import { tryAutoResolveMergeConflicts } from "./engine-lanes/merge.mjs";
13
13
  import { appendJournalEvent } from "./journal.mjs";
14
14
  import { listIntegrateDirtyPaths } from "./rules-manifest-drift.mjs";
15
+ import { isTimeoutError, removeMergeDeletedPath } from "./integrate-path-delete.mjs";
15
16
 
16
17
  export const DEFAULT_SYNC_TIMEOUT_MS = 60_000;
17
18
 
@@ -215,13 +216,9 @@ export function plumbingMergeOrchIntoBase({ projectRoot, baseBranch, orchBranch,
215
216
  return { ok: true, mergeCommit, mode: "plumbing" };
216
217
  }
217
218
 
218
- /**
219
- * @param {unknown} err
220
- * @returns {boolean}
221
- */
222
- function isTimeoutError(err) {
223
- if (!err || typeof err !== "object") return false;
224
- return /** @type {any} */ (err).killed === true || /** @type {any} */ (err).code === "ETIMEDOUT";
219
+ /** Shared timed-out result for the sync loop's git calls. */
220
+ function timeoutSyncResult(error, processedCount, totalPaths) {
221
+ return { ok: false, timedOut: true, error, processedPaths: processedCount, totalPaths: totalPaths };
225
222
  }
226
223
 
227
224
  /**
@@ -289,10 +286,10 @@ function pathExistsInTree(cwd, treeRef, filePath, { timeoutMs } = {}) {
289
286
  * @param {string} projectRoot
290
287
  * @param {string} baseSha
291
288
  * @param {string} mergeCommit
292
- * @param {{ timeoutMs?: number, dirtyPaths?: string[] }} [options]
289
+ * @param {{ timeoutMs?: number, dirtyPaths?: string[], applyDeletions?: boolean }} [options]
293
290
  * @returns {{ ok: boolean, timedOut?: boolean, error?: string, processedPaths?: number, totalPaths?: number, skippedDirtyPaths?: string[] }}
294
291
  */
295
- export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeCommit, { timeoutMs = DEFAULT_SYNC_TIMEOUT_MS, dirtyPaths } = {}) {
292
+ export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeCommit, { timeoutMs = DEFAULT_SYNC_TIMEOUT_MS, dirtyPaths, applyDeletions } = {}) {
296
293
  const envTimeoutMs = process.env.SPINE_SYNC_TIMEOUT_MS
297
294
  ? Number(process.env.SPINE_SYNC_TIMEOUT_MS)
298
295
  : null;
@@ -329,18 +326,20 @@ export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeComm
329
326
  pathExistsInTree(projectRoot, baseSha, filePath, { timeoutMs: effectiveTimeout });
330
327
  } catch (err) {
331
328
  if (isTimeoutError(err)) {
332
- return {
333
- ok: false,
334
- timedOut: true,
335
- error: `git cat-file timed out for ${filePath} after ${effectiveTimeout}ms`,
336
- processedPaths: processedCount,
337
- totalPaths: paths.length,
338
- };
329
+ return timeoutSyncResult(`git cat-file timed out for ${filePath} after ${effectiveTimeout}ms`, processedCount, paths.length);
339
330
  }
340
331
  existsInMerge = false;
341
332
  }
342
333
 
343
334
  if (!existsInMerge) {
335
+ if (applyDeletions) {
336
+ try {
337
+ if (removeMergeDeletedPath(projectRoot, baseSha, filePath, { timeoutMs: effectiveTimeout }).removed) processedCount++;
338
+ else if (dirtyPathSet.has(filePath) && operatorTouched) skippedDirtyPaths.push(filePath);
339
+ } catch (err) {
340
+ if (isTimeoutError(err)) return timeoutSyncResult(`git rm timed out for ${filePath} after ${effectiveTimeout}ms`, processedCount, paths.length);
341
+ }
342
+ }
344
343
  debugSyncLog(
345
344
  `syncPlumbingMergePathsToWorktree: skip ${filePath} — not present in merge commit ${mergeCommit}`,
346
345
  );
@@ -360,13 +359,7 @@ export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeComm
360
359
  );
361
360
  } catch (err) {
362
361
  if (isTimeoutError(err)) {
363
- return {
364
- ok: false,
365
- timedOut: true,
366
- error: `git restore timed out for ${filePath} after ${effectiveTimeout}ms`,
367
- processedPaths: processedCount,
368
- totalPaths: paths.length,
369
- };
362
+ return timeoutSyncResult(`git restore timed out for ${filePath} after ${effectiveTimeout}ms`, processedCount, paths.length);
370
363
  }
371
364
  if (isPathspecMismatchError(err)) {
372
365
  debugSyncLog(
@@ -404,11 +397,11 @@ export function syncMergePathsToCheckedOutBase(projectRoot, baseBranch, baseSha,
404
397
  export function syncMergeResultToCheckedOutBase(projectRoot, baseBranch, mergeResult, options) {
405
398
  const { mode, mergeCommit } = mergeResult;
406
399
  if (mode === "fast-forward") {
407
- return syncMergePathsToCheckedOutBase(projectRoot, baseBranch, mergeResult.baseShaBefore, mergeCommit, options);
400
+ return syncMergePathsToCheckedOutBase(projectRoot, baseBranch, mergeResult.baseShaBefore, mergeCommit, { ...options, applyDeletions: true });
408
401
  }
409
402
  if (mode === "plumbing") {
410
403
  const baseSha = git(projectRoot, ["rev-parse", `${mergeCommit}^1`]);
411
- return syncMergePathsToCheckedOutBase(projectRoot, baseBranch, baseSha, mergeCommit, options);
404
+ return syncMergePathsToCheckedOutBase(projectRoot, baseBranch, baseSha, mergeCommit, { ...options, applyDeletions: true });
412
405
  }
413
406
  return null;
414
407
  }
@@ -429,7 +422,7 @@ function mergeInIntegrateWorktree({ projectRoot, worktreePath, baseBranch, orchB
429
422
  try {
430
423
  git(worktreePath, ["merge", "--no-ff", orchBranch, "-m", mergeMessage]);
431
424
  } catch {
432
- const autoResolved = tryAutoResolveRulesManifestMergeConflict(worktreePath);
425
+ const autoResolved = tryAutoResolveMergeConflicts(worktreePath, {});
433
426
  if (!autoResolved.ok) {
434
427
  try {
435
428
  execFileSync("git", ["merge", "--abort"], {
@@ -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
@@ -6,6 +6,7 @@
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { execFileSync } from "node:child_process";
9
+ import { resolveReviewerModelPin, resolveReviewerThinkingPin } from "../config/agent-model-resolve.mjs";
9
10
  import { METRICS_DEFAULTS } from "../config/defaults.mjs";
10
11
  import { redactSecretsDeep } from "../util/secret-redact.mjs";
11
12
  import { readReviewLevel } from "./review.mjs";
@@ -13,6 +14,7 @@ import { readReviewLevel } from "./review.mjs";
13
14
  // Metrics additionally redacts prompt text (worker prompts may embed
14
15
  // secrets) while preserving usage counters for cost rollup.
15
16
  const METRICS_REDACT_KEY_PATTERN = /key|token|secret|password|prompt/i;
17
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
16
18
  const USAGE_KEYS = new Set(["tokensIn", "tokensOut", "estimatedUsd"]);
17
19
 
18
20
  /**
@@ -141,18 +143,16 @@ export function buildTaskMetricRecord({ batchId, task, config = {}, taskFolder,
141
143
  : typeof worker.model === "string"
142
144
  ? worker.model
143
145
  : "inherit",
144
- thinking:
145
- worker.thinking === "off" ||
146
- worker.thinking === "low" ||
147
- worker.thinking === "medium" ||
148
- worker.thinking === "high"
149
- ? worker.thinking
150
- : "high",
146
+ // SP-835 (#340): prefer the per-attempt pin (`**Thinking:**` / profile) over batch-start config.
147
+ thinking: [task.workerThinking, worker.thinking].find((level) => THINKING_LEVELS.includes(level)) ?? "high",
151
148
  startedAt: new Date(startedMs).toISOString(),
152
149
  endedAt: new Date(endedMs).toISOString(),
153
150
  outcome: resolveTaskMetricOutcome(task),
154
151
  };
155
152
 
153
+ if (typeof task.workerProfile === "string" && task.workerProfile !== "") {
154
+ record.profile = task.workerProfile;
155
+ }
156
156
  if (Number.isFinite(resolvedLaneNumber) && resolvedLaneNumber > 0) {
157
157
  record.laneNumber = resolvedLaneNumber;
158
158
  }
@@ -216,6 +216,126 @@ export function recordTaskTerminalMetric({
216
216
  return appendTaskMetric(projectRoot, record, config);
217
217
  }
218
218
 
219
+ /** Reviewer row outcomes: a recorded verdict, or why no verdict was produced. */
220
+ export const REVIEW_METRIC_OUTCOMES = Object.freeze([
221
+ "verdict",
222
+ "spawn_failed",
223
+ "timeout",
224
+ "provider_error",
225
+ "blocked",
226
+ ]);
227
+
228
+ /**
229
+ * Effective reviewer pins for a review type on the config the review ran with
230
+ * (`"inherit"` when the pin resolves to null).
231
+ *
232
+ * @param {object} config
233
+ * @param {"plan"|"code"|"final"} reviewType
234
+ * @returns {{ model: string, thinking: string }}
235
+ */
236
+ export function resolveReviewMetricPins(config, reviewType) {
237
+ return {
238
+ model: resolveReviewerModelPin(config, reviewType) ?? "inherit",
239
+ thinking: resolveReviewerThinkingPin(config, reviewType) ?? "inherit",
240
+ };
241
+ }
242
+
243
+ /**
244
+ * One `recordType: "review"` row per reviewer verdict or reviewer failure (SP-837 / #325).
245
+ *
246
+ * @param {object} params
247
+ * @param {string} params.batchId
248
+ * @param {string} params.taskId
249
+ * @param {number} [params.laneNumber]
250
+ * @param {"plan"|"code"|"final"} params.reviewType
251
+ * @param {number} [params.stepNumber] Plan/code review step (code/plan reviews are per task today).
252
+ * @param {string} [params.model]
253
+ * @param {string} [params.thinking]
254
+ * @param {string} [params.profile]
255
+ * @param {string} [params.verdict] Recorded verdict (APPROVE/PASS/REVISE/REPLAN) for `outcome: "verdict"`.
256
+ * @param {number} [params.attempt] 1-based review attempt index.
257
+ * @param {number} [params.durationMs]
258
+ * @param {"verdict"|"spawn_failed"|"timeout"|"provider_error"|"blocked"} [params.outcome]
259
+ * @param {string} [params.failureReason]
260
+ * @param {number} [params.endedAtMs]
261
+ */
262
+ export function buildReviewMetricRecord({
263
+ batchId,
264
+ taskId,
265
+ laneNumber,
266
+ reviewType,
267
+ stepNumber,
268
+ model,
269
+ thinking,
270
+ profile,
271
+ verdict,
272
+ attempt,
273
+ durationMs,
274
+ outcome = "verdict",
275
+ failureReason,
276
+ endedAtMs = Date.now(),
277
+ }) {
278
+ /** @type {Record<string, unknown>} */
279
+ const record = {
280
+ recordType: "review",
281
+ schemaVersion: 1,
282
+ batchId,
283
+ taskId,
284
+ agentRole: "reviewer",
285
+ role: "reviewer",
286
+ reviewType,
287
+ model: typeof model === "string" && model !== "" ? model : "inherit",
288
+ thinking: THINKING_LEVELS.includes(/** @type {string} */ (thinking)) ? thinking : "inherit",
289
+ endedAt: new Date(endedAtMs).toISOString(),
290
+ outcome: REVIEW_METRIC_OUTCOMES.includes(outcome) ? outcome : "verdict",
291
+ };
292
+
293
+ if (Number.isFinite(laneNumber) && /** @type {number} */ (laneNumber) > 0) record.laneNumber = laneNumber;
294
+ if (Number.isFinite(stepNumber)) record.stepNumber = stepNumber;
295
+ if (typeof profile === "string" && profile !== "") record.profile = profile;
296
+ if (typeof verdict === "string" && verdict !== "") record.verdict = verdict;
297
+ if (Number.isFinite(attempt)) record.attempt = attempt;
298
+ if (Number.isFinite(durationMs)) record.durationMs = Math.max(0, /** @type {number} */ (durationMs));
299
+ if (typeof failureReason === "string" && failureReason !== "") record.failureReason = failureReason;
300
+
301
+ return sanitizeMetricRecord(record);
302
+ }
303
+
304
+ /**
305
+ * @param {string} projectRoot
306
+ * @param {object} record
307
+ * @param {object} [config]
308
+ */
309
+ export function appendReviewMetric(projectRoot, record, config = {}) {
310
+ return appendTaskMetric(projectRoot, record, config);
311
+ }
312
+
313
+ /**
314
+ * Build and append a reviewer row, resolving model/thinking from the pins on
315
+ * the config the review ran with. No-op when `metrics.enabled` is false.
316
+ *
317
+ * @param {object} params
318
+ * @param {string} params.projectRoot
319
+ * @param {object} [params.config] Per-task review config (effective reviewer pins).
320
+ * @param {"plan"|"code"|"final"} params.reviewType
321
+ * @param {string} params.batchId
322
+ * @param {string} params.taskId
323
+ * @param {number} [params.laneNumber]
324
+ * @param {number} [params.stepNumber]
325
+ * @param {string} [params.model] Overrides the config-resolved model.
326
+ * @param {string} [params.verdict]
327
+ * @param {number} [params.attempt]
328
+ * @param {number} [params.durationMs]
329
+ * @param {"verdict"|"spawn_failed"|"timeout"|"provider_error"|"blocked"} [params.outcome]
330
+ * @param {string} [params.failureReason]
331
+ */
332
+ export function recordReviewMetric({ projectRoot, config = {}, model, ...rest }) {
333
+ if (!isMetricsEnabled(config)) return null;
334
+ const pins = resolveReviewMetricPins(config, rest.reviewType);
335
+ const record = buildReviewMetricRecord({ ...rest, model: model ?? pins.model, thinking: pins.thinking });
336
+ return appendReviewMetric(projectRoot, record, config);
337
+ }
338
+
219
339
  /**
220
340
  * @param {object} params
221
341
  * @param {string} params.batchId
@@ -322,10 +442,15 @@ export function formatMetricsTable(lines) {
322
442
 
323
443
  const header = ["Type", "Batch", "Task", "Outcome", "Diagnosis", "Ended"];
324
444
  const rows = lines.map((line) => [
325
- line.recordType ?? "—",
445
+ line.recordType === "review" && typeof line.reviewType === "string"
446
+ ? `review:${line.reviewType}`
447
+ : (line.recordType ?? "—"),
326
448
  line.batchId ?? "—",
327
449
  line.taskId ?? "—",
328
- line.outcome ?? line.diagnosis ?? "—",
450
+ (line.recordType === "review" && line.outcome === "verdict" ? line.verdict : null) ??
451
+ line.outcome ??
452
+ line.diagnosis ??
453
+ "—",
329
454
  line.diagnosis ?? "—",
330
455
  line.endedAt ?? "—",
331
456
  ]);