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,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,
@@ -57,14 +50,10 @@ export {
57
50
  mergeWaveLanesToOrch,
58
51
  resolveRulesManifestIntegrateDrift,
59
52
  tryAutoResolveMergeConflicts,
60
- tryAutoResolveRulesManifestMergeConflict,
61
53
  } from "./engine-lanes/merge.mjs";
62
54
 
63
55
  export { syncLaneWorktreeFromOrch } from "./worktree.mjs";
64
- export {
65
- collectSharedScopeSatisfiedDeps,
66
- ensureLaneSyncedForSharedScopeDeps,
67
- } from "./engine-lanes/orch-sync.mjs";
56
+ export { collectSharedScopeSatisfiedDeps, ensureLaneSyncedForSharedScopeDeps } from "./engine-lanes/orch-sync.mjs";
68
57
 
69
58
  export {
70
59
  acquireLaneSlot,
@@ -276,11 +265,14 @@ async function runNonMatrixTaskOnLane({
276
265
  if (!task.startedAt) task.startedAt = Date.now();
277
266
  updateSegmentForTask(state, taskId, "running");
278
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 });
279
270
  appendJournalEvent(projectRoot, batchId, "task.started", {
280
271
  taskId,
281
272
  laneNumber,
282
273
  laneId: lane.laneId,
283
274
  correlationId: laneCorrelationId,
275
+ ...attempt.startedPayload,
284
276
  });
285
277
 
286
278
  const workerResult = /** @type {any} */ (await runWorker({
@@ -294,6 +286,7 @@ async function runNonMatrixTaskOnLane({
294
286
  laneCorrelationId,
295
287
  fileScopePaths,
296
288
  config,
289
+ extraEnv: attempt.extraEnv,
297
290
  // Fire-and-forget saves (SP-797 / #302): the host never awaits these callbacks.
298
291
  // Safe — the save serializes live state at lock-acquire time, never a stale snapshot.
299
292
  onHeartbeat: async (timestamp) => {
@@ -389,11 +382,18 @@ async function runNonMatrixTaskOnLane({
389
382
  correlationId: laneCorrelationId,
390
383
  });
391
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
+
392
392
  const planReview = await runPlanReviewPhase({
393
393
  projectRoot,
394
394
  state,
395
395
  batchId,
396
- config,
396
+ config: reviewConfig,
397
397
  task,
398
398
  lane,
399
399
  taskFolderInWorktree,
@@ -410,7 +410,7 @@ async function runNonMatrixTaskOnLane({
410
410
  projectRoot,
411
411
  state,
412
412
  batchId,
413
- config,
413
+ config: reviewConfig,
414
414
  task,
415
415
  lane,
416
416
  taskFolderInWorktree,
@@ -427,7 +427,7 @@ async function runNonMatrixTaskOnLane({
427
427
  projectRoot,
428
428
  state,
429
429
  batchId,
430
- config,
430
+ config: reviewConfig,
431
431
  task,
432
432
  lane,
433
433
  taskFolderInWorktree,
@@ -4,6 +4,8 @@
4
4
  * Kept separate from gate.mjs so the open/check facade stays ≤500 LOC.
5
5
  */
6
6
 
7
+ import fs from "node:fs";
8
+ import path from "node:path";
7
9
  import { resolveGatePostureConfig } from "../config/gate-posture-config.mjs";
8
10
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
11
  import { writeJsonAtomic } from "../fs/atomic-write.mjs";
@@ -11,6 +13,7 @@ import { makeBlocker } from "./blocker-codes.mjs";
11
13
  import { GATE_CATEGORIES, POSTURES } from "./gate-posture-defaults.mjs";
12
14
  import { evaluateGatePosture } from "./gate-posture-evaluate.mjs";
13
15
  import {
16
+ gatePostureStreakPath,
14
17
  getCategoryStreak,
15
18
  incrementCategoryStreak,
16
19
  incrementKindStreak,
@@ -28,6 +31,92 @@ const INTEGRATE_DEFAULT_CATEGORY = /** @type {GateCategory} */ ("execute");
28
31
 
29
32
  const CATEGORY_SET = new Set(/** @type {string[]} */ ([...GATE_CATEGORIES]));
30
33
 
34
+ /** Real streak I/O (SP-824). Tests may override any subset via `ctx.streakIo`. */
35
+ const DEFAULT_STREAK_IO = Object.freeze({
36
+ incrementCategoryStreak,
37
+ incrementKindStreak,
38
+ resetCategoryStreak,
39
+ resetKindStreak,
40
+ removeStreakFile(projectRoot) {
41
+ fs.rmSync(gatePostureStreakPath(projectRoot), { force: true });
42
+ },
43
+ });
44
+
45
+ /**
46
+ * @param {unknown} streakIo Optional partial override of streak I/O operations.
47
+ * @returns {typeof DEFAULT_STREAK_IO}
48
+ */
49
+ function resolveStreakIo(streakIo) {
50
+ if (!streakIo || typeof streakIo !== "object" || Array.isArray(streakIo)) {
51
+ return DEFAULT_STREAK_IO;
52
+ }
53
+ return { ...DEFAULT_STREAK_IO, ...streakIo };
54
+ }
55
+
56
+ /**
57
+ * Best-effort journal record of a streak I/O failure (SP-824 / #314).
58
+ * @param {string} projectRoot
59
+ * @param {string|null|undefined} batchId
60
+ * @param {Record<string, unknown>} payload
61
+ */
62
+ function journalStreakIoFailure(projectRoot, batchId, payload) {
63
+ if (typeof batchId !== "string" || batchId.trim() === "") return;
64
+ try {
65
+ appendJournalEvent(projectRoot, batchId, "gate.streak_io_failed", payload);
66
+ } catch {
67
+ // Journaling is best-effort — never throw out of a persisted gate decision.
68
+ }
69
+ }
70
+
71
+ /** @param {unknown} error @returns {string} */
72
+ function errorMessage(error) {
73
+ return error instanceof Error ? error.message : String(error);
74
+ }
75
+
76
+ /**
77
+ * SP-824 / #314 — does ANY batch journal record a streak reset whose fail-closed
78
+ * recovery (streak file removal) also failed? Streak state is project-wide while
79
+ * journals are per-batch, so scan `.spine/runtime/<batchId>/journal/events.jsonl`
80
+ * (substring pre-filter keeps JSON parsing to matching lines only).
81
+ * @param {string} projectRoot
82
+ * @returns {boolean}
83
+ */
84
+ function journalHasUnrecoveredStreakReset(projectRoot) {
85
+ const runtimeDir = path.join(projectRoot, ".spine", "runtime");
86
+ /** @type {string[]} */
87
+ let batchDirNames;
88
+ try {
89
+ batchDirNames = fs
90
+ .readdirSync(runtimeDir, { withFileTypes: true })
91
+ .filter((entry) => entry.isDirectory())
92
+ .map((entry) => entry.name);
93
+ } catch {
94
+ return false; // no runtime dir → no journals → no recorded unrecovered reset
95
+ }
96
+ return batchDirNames.some((batchId) => {
97
+ /** @type {string} */
98
+ let content;
99
+ try {
100
+ content = fs.readFileSync(path.join(runtimeDir, batchId, "journal", "events.jsonl"), "utf-8");
101
+ } catch {
102
+ return false; // unreadable journal — keep scanning the others
103
+ }
104
+ return content.split("\n").some((line) => {
105
+ if (!line.includes("gate.streak_io_failed")) return false;
106
+ try {
107
+ const { type, payload } = JSON.parse(line);
108
+ return (
109
+ type === "gate.streak_io_failed" &&
110
+ payload?.op === "reset" &&
111
+ payload?.recovered === false
112
+ );
113
+ } catch {
114
+ return false; // skip malformed journal line
115
+ }
116
+ });
117
+ });
118
+ }
119
+
31
120
  /**
32
121
  * @param {string} projectRoot
33
122
  * @param {object} gate
@@ -82,38 +171,69 @@ function resolveGateCategory(gate) {
82
171
 
83
172
  /**
84
173
  * Persist consecutive-approval streak after a successful approve.
85
- * Failures must not undo the gate FSM decision.
86
- *
174
+ * Failures must not undo the gate FSM decision; they are journaled instead
175
+ * (SP-824 / #314). A failed increment only delays auto-approval — the safe
176
+ * direction — so no recovery is attempted.
87
177
  * @param {string} projectRoot
88
178
  * @param {object} gate
179
+ * @param {string} batchId
180
+ * @param {typeof DEFAULT_STREAK_IO} streakIo
89
181
  */
90
- function recordApprovalStreak(projectRoot, gate) {
182
+ function recordApprovalStreak(projectRoot, gate, batchId, streakIo) {
91
183
  const category = resolveGateCategory(gate);
184
+ const kind = typeof gate.kind === "string" && gate.kind.trim() !== "" ? gate.kind : null;
92
185
  try {
93
- incrementCategoryStreak(projectRoot, category);
94
- if (typeof gate.kind === "string" && gate.kind.trim() !== "") {
95
- incrementKindStreak(projectRoot, gate.kind);
186
+ streakIo.incrementCategoryStreak(projectRoot, category);
187
+ if (kind !== null) {
188
+ streakIo.incrementKindStreak(projectRoot, kind);
96
189
  }
97
- } catch {
190
+ } catch (error) {
98
191
  // Streak I/O must not reverse an already-persisted approval.
192
+ journalStreakIoFailure(projectRoot, batchId, {
193
+ op: "increment",
194
+ category,
195
+ kind,
196
+ error: errorMessage(error),
197
+ });
99
198
  }
100
199
  }
101
200
 
102
201
  /**
103
202
  * Reset streak counters after a reject (breaks consecutive-approval chain).
104
- *
203
+ * A failed reset would leave a stale consecutive-approval count that could
204
+ * unlock a later auto-approve despite the rejection, so this fails closed:
205
+ * best-effort removal of the whole streak store (missing file → zero counts).
105
206
  * @param {string} projectRoot
106
207
  * @param {object} gate
208
+ * @param {string} batchId
209
+ * @param {typeof DEFAULT_STREAK_IO} streakIo
107
210
  */
108
- function recordRejectStreakReset(projectRoot, gate) {
211
+ function recordRejectStreakReset(projectRoot, gate, batchId, streakIo) {
109
212
  const category = resolveGateCategory(gate);
213
+ const kind = typeof gate.kind === "string" && gate.kind.trim() !== "" ? gate.kind : null;
110
214
  try {
111
- resetCategoryStreak(projectRoot, category);
112
- if (typeof gate.kind === "string" && gate.kind.trim() !== "") {
113
- resetKindStreak(projectRoot, gate.kind);
215
+ streakIo.resetCategoryStreak(projectRoot, category);
216
+ if (kind !== null) {
217
+ streakIo.resetKindStreak(projectRoot, kind);
114
218
  }
115
- } catch {
219
+ } catch (error) {
116
220
  // Streak reset failure must not reverse a persisted rejection.
221
+ let recovered = true;
222
+ let recoveryError;
223
+ try {
224
+ streakIo.removeStreakFile(projectRoot);
225
+ } catch (rmError) {
226
+ recovered = false;
227
+ recoveryError = errorMessage(rmError);
228
+ }
229
+ journalStreakIoFailure(projectRoot, batchId, {
230
+ op: "reset",
231
+ category,
232
+ kind,
233
+ error: errorMessage(error),
234
+ recovered,
235
+ ...(recovered ? {} : { recoveryError }),
236
+ });
117
237
  }
118
238
  }
119
239
 
@@ -127,6 +247,7 @@ function recordRejectStreakReset(projectRoot, gate) {
127
247
  */
128
248
  export function approveIntegrateGate(ctx) {
129
249
  const { projectRoot, batchId, decidedBy = "human", postureEvaluation = null, synthesis } = ctx;
250
+ const streakIo = resolveStreakIo(ctx.streakIo);
130
251
  const gate = loadGateRecord(projectRoot, batchId);
131
252
 
132
253
  if (!gate) {
@@ -168,7 +289,7 @@ export function approveIntegrateGate(ctx) {
168
289
  const synthesisNote = typeof synthesis === "string" && synthesis.trim() !== "" ? synthesis : null;
169
290
  if (synthesisNote) gate.synthesis = synthesisNote;
170
291
  saveGateRecord(projectRoot, gate);
171
- recordApprovalStreak(projectRoot, gate);
292
+ recordApprovalStreak(projectRoot, gate, batchId, streakIo);
172
293
 
173
294
  /** @type {Record<string, unknown>} */
174
295
  const journalPayload = {
@@ -213,6 +334,7 @@ export function approveIntegrateGate(ctx) {
213
334
  */
214
335
  export function maybeAutoApproveIntegrateGate(ctx) {
215
336
  const { projectRoot, batchId, tags = [] } = ctx;
337
+ const streakIo = resolveStreakIo(ctx.streakIo);
216
338
  const config = ctx.config ?? loadSpineConfig(projectRoot).config ?? null;
217
339
  const gate = loadGateRecord(projectRoot, batchId);
218
340
 
@@ -236,6 +358,21 @@ export function maybeAutoApproveIntegrateGate(ctx) {
236
358
  ? postureConfig.categories[category]
237
359
  : { posture: POSTURES.LOCKED, autoApproveAfterN: null };
238
360
 
361
+ // SP-824 / #314 fail-closed: a journal-recorded unrecovered streak reset makes
362
+ // the project-wide streak state untrustworthy — checked before reading it.
363
+ if (journalHasUnrecoveredStreakReset(projectRoot)) {
364
+ return {
365
+ ok: true,
366
+ approved: false,
367
+ evaluation: { decision: "require-manual", reason: "streak_unreliable", tier: null },
368
+ optedIn,
369
+ category,
370
+ consecutiveApprovals: null,
371
+ reason: "streak_unreliable",
372
+ gate,
373
+ };
374
+ }
375
+
239
376
  const consecutiveApprovals = getCategoryStreak(projectRoot, category);
240
377
  /** @type {string[]} */
241
378
  const mergedTags = [];
@@ -275,6 +412,7 @@ export function maybeAutoApproveIntegrateGate(ctx) {
275
412
  batchId,
276
413
  decidedBy: "auto",
277
414
  postureEvaluation: evaluation,
415
+ streakIo,
278
416
  });
279
417
 
280
418
  return {
@@ -336,7 +474,8 @@ export function rejectIntegrateGate(ctx) {
336
474
  const synthesisNote = typeof synthesis === "string" && synthesis.trim() !== "" ? synthesis : null;
337
475
  if (synthesisNote) gate.synthesis = synthesisNote;
338
476
  saveGateRecord(projectRoot, gate);
339
- recordRejectStreakReset(projectRoot, gate);
477
+ const streakIo = resolveStreakIo(ctx.streakIo);
478
+ recordRejectStreakReset(projectRoot, gate, batchId, streakIo);
340
479
 
341
480
  appendJournalEvent(projectRoot, batchId, "gate.rejected", {
342
481
  gateId: gate.gateId,