pi-spine 2.27.1 → 2.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/bin/spine-batch.mjs +46 -4
  2. package/bin/spine-cli/cli-args.mjs +117 -0
  3. package/bin/spine-gate.mjs +28 -21
  4. package/bin/spine-integrate.mjs +28 -7
  5. package/bin/spine-issue.mjs +2 -1
  6. package/bin/spine-settings.mjs +7 -9
  7. package/bin/spine-tasks.mjs +1 -0
  8. package/bin/spine-worker-runner.mjs +21 -8
  9. package/bin/spine.mjs +10 -3
  10. package/package.json +1 -1
  11. package/skills/create-spine-tasks/references/prompt-template.md +5 -0
  12. package/skills/spine-release-operator/SKILL.md +14 -2
  13. package/src/batch/contract-exec.mjs +2 -3
  14. package/src/batch/contract-task-start.mjs +23 -1
  15. package/src/batch/diagnosis-handoff-packet.mjs +18 -0
  16. package/src/batch/diagnosis-primary-failure.mjs +35 -0
  17. package/src/batch/engine-lanes/matrix-run.mjs +2 -0
  18. package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
  19. package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
  20. package/src/batch/engine-lanes/review-code.mjs +20 -0
  21. package/src/batch/engine-lanes/review-final.mjs +10 -2
  22. package/src/batch/engine-lanes/review-poll.mjs +33 -0
  23. package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
  24. package/src/batch/engine-lanes.mjs +18 -17
  25. package/src/batch/evidence-command.mjs +18 -21
  26. package/src/batch/evidence-exec.mjs +79 -0
  27. package/src/batch/journal.mjs +5 -3
  28. package/src/batch/metrics-rollup.mjs +98 -4
  29. package/src/batch/metrics.mjs +134 -9
  30. package/src/batch/provider-quota.mjs +174 -6
  31. package/src/batch/quota-fallback.mjs +87 -6
  32. package/src/batch/reconcile-classify.mjs +28 -1
  33. package/src/batch/reconcile-diagnosis-context.mjs +2 -0
  34. package/src/batch/resume-lane-reviews.mjs +11 -10
  35. package/src/batch/retry-profile.mjs +77 -0
  36. package/src/batch/retry.mjs +32 -1
  37. package/src/batch/review-step-run.mjs +4 -0
  38. package/src/batch/review-step.mjs +1 -0
  39. package/src/batch/sequence-wait.mjs +7 -5
  40. package/src/batch/state-io.mjs +29 -3
  41. package/src/batch/worker-heartbeat.mjs +10 -2
  42. package/src/batch/worker-host.mjs +1 -1
  43. package/src/batch/worker-prompt.mjs +4 -5
  44. package/src/cli/deps.mjs +3 -2
  45. package/src/config/agent-model-resolve.mjs +144 -8
  46. package/src/config/contract.mjs +20 -0
  47. package/src/config/model-family.mjs +60 -0
  48. package/src/config/preflight/discovery.mjs +1 -0
  49. package/src/config/settings-fields.mjs +15 -0
  50. package/src/config/spine-config-schema.mjs +49 -0
  51. package/src/doctor/agent-model-inherit.mjs +78 -1
  52. package/src/doctor/agent-template-drift.mjs +65 -0
  53. package/src/doctor/run-doctor-checks.mjs +8 -1
  54. package/src/doctor/stet-capacity.mjs +171 -0
  55. package/src/metrics/quota-cli.mjs +16 -0
  56. package/src/metrics/quota-probes.mjs +228 -31
  57. package/src/metrics/quota-snapshot.mjs +21 -2
  58. package/src/planner/graph.mjs +7 -5
  59. package/src/planner/pending.mjs +2 -2
  60. package/src/planner/scope.mjs +3 -3
  61. package/src/tasks/packet/parse-prompt.mjs +47 -0
  62. package/src/tasks/packet/validate-prompt.mjs +156 -1
  63. package/templates/agents/reviewer.md +3 -1
  64. package/templates/agents/worker.md +15 -19
@@ -7,7 +7,9 @@
7
7
  * SP-804 classification, and the worker backend:
8
8
  *
9
9
  * - at most one hop per batch (sticky once applied — a second exhaustion can
10
- * only re-route lanes still pinned to the old pool, never pick a new pool);
10
+ * only re-route lanes still pinned to the old pool, never pick a new pool)
11
+ * until the hop is cleared: it expires once its parsed reset time plus a
12
+ * grace window has passed, or the operator clears it (SP-843, #350);
11
13
  * - one auto-retry per task (`retriedTaskIds`), so no task ping-pongs;
12
14
  * - transient overload, an unset fallback key, and the in-process
13
15
  * `agentSession` backend never fall back;
@@ -38,6 +40,7 @@ import { resolvePoolId } from "../metrics/quota-snapshot.mjs";
38
40
  * @property {string} toModel Worker model after the hop.
39
41
  * @property {string} exhaustedPool Pool whose exhaustion triggered the hop.
40
42
  * @property {string|null} resetAtRaw Raw provider reset text for that pool, when it had one.
43
+ * @property {number|null} [resetAt] Epoch ms the exhausted pool resets (SP-843), or null when `resetAtRaw` is not parsable. Absent on hops persisted before SP-843 (never expires).
41
44
  * @property {string} triggerTaskId Task whose failure triggered the hop.
42
45
  * @property {string} at ISO timestamp of the hop.
43
46
  * @property {string[]} retriedTaskIds Tasks already auto-retried onto the fallback pool.
@@ -96,6 +99,73 @@ import { resolvePoolId } from "../metrics/quota-snapshot.mjs";
96
99
  * @typedef {{ agents?: { activeProfile?: unknown, worker?: { model?: unknown }, profiles?: Record<string, any>, quotaFallbackProfile?: unknown } }} QuotaFallbackConfig
97
100
  */
98
101
 
102
+ /** Grace after the parsed reset time before the hop expires (provider clocks drift). */
103
+ export const QUOTA_FALLBACK_EXPIRY_GRACE_MS = 5 * 60 * 1000;
104
+
105
+ /** z.ai reset text carries no timezone; the provider's local time is assumed UTC+8 (#329). */
106
+ const ZAI_UTC_OFFSET_MS = 8 * 60 * 60 * 1000;
107
+
108
+ const ZAI_RESET_PATTERN = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;
109
+ const RETRY_IN_PATTERN = /^retry in (\d+(?:\.\d+)?)s$/i;
110
+
111
+ /**
112
+ * Parses the raw provider reset text into an epoch-ms reset time. Pure.
113
+ *
114
+ * - z.ai `YYYY-MM-DD HH:MM:SS` → that wall-clock time read as UTC+8;
115
+ * - Google `retry in <N>s` → `at + N*1000` (relative to when the error was seen);
116
+ * - anything else (Kimi `10pm PT`, blank, non-string, impossible dates) → `null`.
117
+ *
118
+ * @param {unknown} resetAtRaw
119
+ * @param {{ at?: Date|number|string|null }} [options] `at`: when the exhaustion was observed (hop time); needed for `retry in <N>s`.
120
+ * @returns {number|null}
121
+ */
122
+ export function parseQuotaResetAt(resetAtRaw, { at = null } = {}) {
123
+ if (typeof resetAtRaw !== "string") return null;
124
+ const text = resetAtRaw.trim();
125
+
126
+ const zai = ZAI_RESET_PATTERN.exec(text);
127
+ if (zai) {
128
+ const [year, month, day, hour, minute, second] = zai.slice(1).map(Number);
129
+ const wall = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
130
+ // Date.UTC rolls impossible values over (month 13, Feb 31); reject them.
131
+ if (
132
+ wall.getUTCFullYear() !== year ||
133
+ wall.getUTCMonth() !== month - 1 ||
134
+ wall.getUTCDate() !== day ||
135
+ wall.getUTCHours() !== hour ||
136
+ wall.getUTCMinutes() !== minute ||
137
+ wall.getUTCSeconds() !== second
138
+ ) {
139
+ return null;
140
+ }
141
+ return wall.getTime() - ZAI_UTC_OFFSET_MS;
142
+ }
143
+
144
+ const relative = RETRY_IN_PATTERN.exec(text);
145
+ if (relative && at !== null && at !== undefined) {
146
+ const base = new Date(at).getTime();
147
+ if (!Number.isFinite(base)) return null;
148
+ return base + Math.round(Number(relative[1]) * 1000);
149
+ }
150
+ return null;
151
+ }
152
+
153
+ /**
154
+ * True when a persisted hop has a parsed reset time and `now` is past it plus
155
+ * {@link QUOTA_FALLBACK_EXPIRY_GRACE_MS}. A hop without a parsable reset
156
+ * (`resetAt` null/absent, including hops persisted before SP-843) never expires.
157
+ *
158
+ * @param {QuotaFallbackState|null|undefined} fallbackState
159
+ * @param {Date|number} now
160
+ * @returns {boolean}
161
+ */
162
+ export function isQuotaFallbackExpired(fallbackState, now) {
163
+ const resetAt = fallbackState?.resetAt;
164
+ if (typeof resetAt !== "number" || !Number.isFinite(resetAt)) return false;
165
+ const nowMs = new Date(now).getTime();
166
+ return Number.isFinite(nowMs) && nowMs >= resetAt + QUOTA_FALLBACK_EXPIRY_GRACE_MS;
167
+ }
168
+
99
169
  /**
100
170
  * Reads `agents.quotaFallbackProfile` from a resolved config. An unset,
101
171
  * non-string, or blank value disables fallback entirely (SP-805 lets `""`
@@ -162,7 +232,9 @@ function buildExhaustedReport(fallbackState, classification) {
162
232
  * ignore child env pins, so fallback cannot reach them.
163
233
  * 4. `stop/profile_missing` — fallback profile absent from `agents.profiles`
164
234
  * (defensive: the schema normally rejects this; fail closed on drift).
165
- * 5. Fallback already applied (sticky, one hop per batch):
235
+ * 5. Fallback already applied (sticky until it expires or is cleared; one
236
+ * hop at a time). A hop that is expired at `now` counts as cleared, so a
237
+ * later exhaustion can hop again (SP-843):
166
238
  * `stop/task_retry_spent` when the task already used its auto-retry;
167
239
  * `retry` when the classification hits the original pool (a lane still
168
240
  * pinned there) — re-route it, no new hop; otherwise
@@ -181,16 +253,21 @@ function buildExhaustedReport(fallbackState, classification) {
181
253
  * @param {string} [params.taskId] Task the classification came from.
182
254
  * @param {string} [params.workerBackend] Resolved worker backend.
183
255
  * @param {string[]} [params.probeExhaustedPools] Pools a live probe reported exhausted.
256
+ * @param {Date|number} [params.now] When set, an expired `fallbackState` is treated as cleared (SP-843). Omitted: no expiry check.
184
257
  * @returns {QuotaFallbackDecision}
185
258
  */
186
259
  export function decideQuotaFallback({
187
260
  config,
188
- fallbackState = null,
261
+ fallbackState: persistedFallbackState = null,
189
262
  classification = null,
190
263
  taskId,
191
264
  workerBackend,
192
265
  probeExhaustedPools,
266
+ now,
193
267
  } = {}) {
268
+ const fallbackState =
269
+ now !== undefined && isQuotaFallbackExpired(persistedFallbackState, now) ? null : persistedFallbackState;
270
+
194
271
  // Row 1 — no fallback target configured.
195
272
  const toProfileName = readFallbackProfileName(config);
196
273
  if (toProfileName === null) {
@@ -224,7 +301,8 @@ export function decideQuotaFallback({
224
301
  return stop("profile_missing");
225
302
  }
226
303
 
227
- // Row 5 — sticky: once the hop happened, no second hop is ever decided.
304
+ // Row 5 — sticky: while the hop is active, no second hop is decided. An
305
+ // expired or cleared hop is `null` here, so the batch may hop again.
228
306
  if (fallbackState) {
229
307
  const retriedTaskIds = Array.isArray(fallbackState.retriedTaskIds) ? fallbackState.retriedTaskIds : [];
230
308
  if (taskId !== undefined && taskId !== null && retriedTaskIds.includes(taskId)) {
@@ -283,15 +361,18 @@ export function decideQuotaFallback({
283
361
  * @returns {QuotaFallbackState}
284
362
  */
285
363
  export function buildQuotaFallbackState(decision, { classification, taskId, now }) {
364
+ const at = new Date(now);
365
+ const resetAtRaw = typeof classification.resetAtRaw === "string" ? classification.resetAtRaw : null;
286
366
  return {
287
367
  fromProfile: decision.fromProfile,
288
368
  toProfile: decision.toProfile,
289
369
  fromModel: decision.fromModel,
290
370
  toModel: decision.toModel,
291
371
  exhaustedPool: decision.exhaustedPool,
292
- resetAtRaw: typeof classification.resetAtRaw === "string" ? classification.resetAtRaw : null,
372
+ resetAtRaw,
373
+ resetAt: parseQuotaResetAt(resetAtRaw, { at }),
293
374
  triggerTaskId: taskId,
294
- at: new Date(now).toISOString(),
375
+ at: at.toISOString(),
295
376
  retriedTaskIds: [],
296
377
  };
297
378
  }
@@ -299,6 +299,30 @@ export function listHumanOnlyPaths(projectRoot, snapshot, humanHead, orchBranch)
299
299
  }
300
300
  }
301
301
 
302
+ /**
303
+ * Paths touched on both sides only overlap when their contents differ: the same
304
+ * template sync landing on main and orch is not a divergence. One `git diff`
305
+ * call covers every candidate; a git failure keeps all candidates (fail closed).
306
+ *
307
+ * @param {string} projectRoot @param {string} humanRef @param {string} orchRef @param {string[]} candidatePaths
308
+ * @returns {string[]}
309
+ */
310
+ function keepPathsWithDifferentContent(projectRoot, humanRef, orchRef, candidatePaths) {
311
+ if (candidatePaths.length === 0 || !orchRef) return candidatePaths;
312
+ try {
313
+ const output = execFileSync("git", ["diff", "--name-only", humanRef, orchRef, "--", ...candidatePaths], {
314
+ cwd: projectRoot,
315
+ encoding: "utf-8",
316
+ stdio: ["ignore", "pipe", "pipe"],
317
+ timeout: 5000,
318
+ });
319
+ const differing = new Set(output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
320
+ return candidatePaths.filter((filePath) => differing.has(filePath));
321
+ } catch {
322
+ return candidatePaths;
323
+ }
324
+ }
325
+
302
326
  /** @param {string} projectRoot @param {string} ref @param {string} filePath */
303
327
  function pathExistsAtRef(projectRoot, ref, filePath) {
304
328
  try {
@@ -382,7 +406,10 @@ export function inspectHumanBaseSync(ctx) {
382
406
  resolvedOrch && gitRefExists(projectRoot, resolvedOrch)
383
407
  ? listGitChangedPaths(projectRoot, snapshot, resolvedOrch)
384
408
  : landPaths;
385
- const overlapPaths = humanPaths.filter((filePath) => orchPaths.includes(filePath));
409
+ const orchPathSet = new Set(orchPaths);
410
+ const touchedByBoth = humanPaths.filter((filePath) => orchPathSet.has(filePath));
411
+ const orchContentRef = resolvedOrch ?? baseTip;
412
+ const overlapPaths = keepPathsWithDifferentContent(projectRoot, humanHead, orchContentRef, touchedByBoth);
386
413
 
387
414
  if (overlapPaths.length > 0) {
388
415
  return {
@@ -1,6 +1,7 @@
1
1
  /** Diagnosis output context after reconcile signal enrichment (#201 / SP-645). */
2
2
 
3
3
  import { findPendingLaneLandTasks } from "./diagnosis-pending-lane.mjs";
4
+ import { isContractTimeoutFailure } from "./diagnosis-primary-failure.mjs";
4
5
 
5
6
  /**
6
7
  * @param {Record<string, any>} params
@@ -73,6 +74,7 @@ export function buildReconcileDiagnosisContext(params) {
73
74
  lastQuotaExhausted,
74
75
  driftTaskStatus,
75
76
  exitReason,
77
+ contractTimedOut: exitReason === "contract_failed" && isContractTimeoutFailure(journalEvents, failedTaskId),
76
78
  launchFailureKind: resolvedLaunchFailureKind,
77
79
  gitMerged: git.orchMergedToBase,
78
80
  pendingTaskCount,
@@ -1,21 +1,22 @@
1
1
  /**
2
2
  * Resume lane review phases — mirror engine-lanes review before lane commit (SP-359).
3
3
  * Engine-owned plan review runs first for RL≥1 (SP-695 / #250).
4
+ * Resumed reviews use the same per-task effective reviewer config as a fresh run (SP-834 / #355).
4
5
  */
5
6
 
6
7
  import { runCodeReviewPhase, runFinalReviewPhase, runPlanReviewPhase } from "./engine-lanes/review.mjs";
8
+ import { applyTaskReviewProfile } from "./engine-lanes/task-agent-profile.mjs";
7
9
 
8
10
  /**
9
- * @param {object} params
11
+ * @param {Record<string, any>} params
10
12
  */
11
13
  export async function runLaneReviewPhasesBeforeCommit(params) {
12
- const planReview = await runPlanReviewPhase(params);
13
- if (!planReview.ok) {
14
- return planReview;
15
- }
16
- const codeReview = await runCodeReviewPhase(params);
17
- if (!codeReview.ok) {
18
- return codeReview;
19
- }
20
- return runFinalReviewPhase(params);
14
+ const reviewProfile = await applyTaskReviewProfile(params);
15
+ if (!reviewProfile.ok) return reviewProfile;
16
+ const reviewParams = { ...params, config: reviewProfile.config };
17
+ const planReview = await runPlanReviewPhase(reviewParams);
18
+ if (!planReview.ok) return planReview;
19
+ const codeReview = await runCodeReviewPhase(reviewParams);
20
+ if (!codeReview.ok) return codeReview;
21
+ return runFinalReviewPhase(reviewParams);
21
22
  }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Retry profile escalation decision (SP-836 / #340).
3
+ */
4
+
5
+ /**
6
+ * Failure classes (`task.exitReason`) that are content/contract failures: a stronger
7
+ * profile can plausibly fix them (SP-836 / #340). Everything else — provider quota/403,
8
+ * overload, launch, stall/orphan, `review_blocked`, reviewer spawn/provider errors — is a
9
+ * provider/infra failure and must never escalate (#248, #329; quota uses
10
+ * `agents.quotaFallbackProfile`).
11
+ */
12
+ export const ESCALATION_ELIGIBLE_CLASSES = Object.freeze(["contract_failed", "review_exhausted"]);
13
+
14
+ /**
15
+ * @param {unknown} value
16
+ * @returns {string}
17
+ */
18
+ function trimmedString(value) {
19
+ return typeof value === "string" ? value.trim() : "";
20
+ }
21
+
22
+ /**
23
+ * Decide the `task.profileOverride` for a retry (SP-836 / #340). Pure: reads the
24
+ * failure class off the (not yet reset) task and the `agents` config.
25
+ *
26
+ * @param {object} params
27
+ * @param {Record<string, any>} params.task Batch-state task row, before `resetTaskForRetry`.
28
+ * @param {Record<string, any>|null} [params.config] Effective config.
29
+ * @param {string|null} [params.profile] Operator `--profile` value.
30
+ * @param {boolean} [params.noEscalate] Operator `--no-escalate`.
31
+ * @returns {{ ok: true, profileOverride: string|null, escalation: "manual"|"auto"|null, apply: boolean }
32
+ * | { ok: false, error: string, output: string }}
33
+ */
34
+ export function resolveRetryProfileOverride({ task, config = null, profile = null, noEscalate = false }) {
35
+ const agents = config?.agents && typeof config.agents === "object" ? config.agents : {};
36
+ const profiles = agents.profiles && typeof agents.profiles === "object" ? agents.profiles : {};
37
+ const failureClass = trimmedString(task?.exitReason) || trimmedString(task?.classification);
38
+ const eligible = ESCALATION_ELIGIBLE_CLASSES.includes(failureClass);
39
+ const currentOverride = trimmedString(task?.profileOverride) || null;
40
+
41
+ const requested = trimmedString(profile);
42
+ if (profile != null) {
43
+ const defined = Object.keys(profiles);
44
+ if (requested === "" || !Object.hasOwn(profiles, requested)) {
45
+ return {
46
+ ok: false,
47
+ error: "unknown_profile",
48
+ output: `Unknown profile "${requested}". Defined profiles: ${defined.length > 0 ? defined.join(", ") : "(none)"}.\n`,
49
+ };
50
+ }
51
+ if (!eligible) {
52
+ const label = failureClass || "unknown";
53
+ return {
54
+ ok: false,
55
+ error: "profile_ineligible",
56
+ output:
57
+ `--profile is for content/contract failures; ${label} is a provider/infra failure — ` +
58
+ "use agents.quotaFallbackProfile or retry without --profile\n",
59
+ };
60
+ }
61
+ return { ok: true, profileOverride: requested, escalation: "manual", apply: true };
62
+ }
63
+
64
+ const policy = agents.escalatePolicy;
65
+ const target = trimmedString(policy?.toProfile);
66
+ if (
67
+ noEscalate ||
68
+ !eligible ||
69
+ policy?.enabled !== true ||
70
+ target === "" ||
71
+ !Object.hasOwn(profiles, target) ||
72
+ currentOverride === target
73
+ ) {
74
+ return { ok: true, profileOverride: currentOverride, escalation: null, apply: false };
75
+ }
76
+ return { ok: true, profileOverride: target, escalation: "auto", apply: true };
77
+ }
@@ -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") {
@@ -58,14 +58,16 @@ export async function waitForSequenceBatchTerminal({
58
58
  stallMs = DEFAULT_SEQUENCE_STALL_MS,
59
59
  enginePid = null,
60
60
  reconcileFn = reconcileBatch,
61
+ now = Date.now,
62
+ sleepFn = sleep,
61
63
  }) {
62
- const startedAt = Date.now();
64
+ const startedAt = now();
63
65
  const deadline = startedAt + timeoutMs;
64
66
  const hardCap = startedAt + maxWaitMs;
65
67
  let lastProgressAt = startedAt;
66
68
  let useLightReconcile = false;
67
- while (Date.now() < deadline || isEngineStillRunning(enginePid, projectRoot)) {
68
- if (Date.now() >= hardCap) {
69
+ while (now() < deadline || isEngineStillRunning(enginePid, projectRoot)) {
70
+ if (now() >= hardCap) {
69
71
  const reconciliation = reconcileFn({ projectRoot });
70
72
  return {
71
73
  ok: false,
@@ -100,7 +102,7 @@ export async function waitForSequenceBatchTerminal({
100
102
  if (progressAt != null && progressAt > lastProgressAt) {
101
103
  lastProgressAt = progressAt;
102
104
  }
103
- if (Date.now() - lastProgressAt >= stallMs) {
105
+ if (now() - lastProgressAt >= stallMs) {
104
106
  return {
105
107
  ok: false,
106
108
  error: "engine_stalled",
@@ -110,7 +112,7 @@ export async function waitForSequenceBatchTerminal({
110
112
  suggestedCommand: "spine status --diagnose",
111
113
  };
112
114
  }
113
- await sleep(pollIntervalMs);
115
+ await sleepFn(pollIntervalMs);
114
116
  }
115
117
  const reconciliation = reconcileFn({ projectRoot });
116
118
  return {
@@ -10,6 +10,7 @@ import { withBatchStateLock } from "./batch-state-lock.mjs";
10
10
  import {
11
11
  clearBatchEnginePid,
12
12
  evaluateBatchStateWriteGuard,
13
+ readBatchEnginePid,
13
14
  TERMINAL_BATCH_PHASES,
14
15
  } from "./state-guards.mjs";
15
16
 
@@ -53,29 +54,54 @@ function archivedBatchStatePath(projectRoot, batchId) {
53
54
  return path.join(projectRoot, ".spine", "runtime", batchId, "archive", "batch-state.json");
54
55
  }
55
56
 
57
+ /**
58
+ * Rejection counts per `projectRoot|batchId|reason|ownerPid`. A non-engine writer
59
+ * can hit the guard dozens of times during one contract/merge (28 in v2.28 Batch B);
60
+ * one report per key, plus a count at each power of ten, keeps the signal without
61
+ * the noise.
62
+ *
63
+ * @type {Map<string, number>}
64
+ */
65
+ const rejectedWriteCounts = new Map();
66
+
67
+ /** @param {number} count */
68
+ function isRejectionReportMilestone(count) {
69
+ return count === 1 || (count >= 10 && Number.isInteger(Math.log10(count)));
70
+ }
71
+
56
72
  /**
57
73
  * Make a rejected batch-state write visible instead of silent (#293 / SP-790):
58
74
  * journal `batch.state_write_rejected` (when the incoming state carries a batchId)
59
75
  * and print one `[spine]` line to stderr so a swallowed late write is diagnosable.
76
+ * Repeats of the same rejection are counted and reported at 10, 100, 1000, …
60
77
  *
61
78
  * @param {string} projectRoot
62
79
  * @param {Record<string, any>} state
63
80
  * @param {string} reason
81
+ * @param {number|null} ownerPid Engine PID recorded on disk when the write was refused.
64
82
  */
65
- function reportRejectedBatchStateWrite(projectRoot, state, reason) {
83
+ function reportRejectedBatchStateWrite(projectRoot, state, reason, ownerPid) {
66
84
  const batchId = String(state?.batchId ?? "");
85
+ const key = `${projectRoot}|${batchId}|${reason}|${ownerPid ?? ""}`;
86
+ const count = (rejectedWriteCounts.get(key) ?? 0) + 1;
87
+ rejectedWriteCounts.set(key, count);
88
+ if (!isRejectionReportMilestone(count)) return;
89
+
67
90
  if (batchId) {
68
91
  try {
69
92
  appendJournalEvent(projectRoot, batchId, "batch.state_write_rejected", {
70
93
  reason,
71
94
  incomingPhase: String(state.phase ?? ""),
95
+ ownerPid,
96
+ rejectedCount: count,
72
97
  });
73
98
  } catch {
74
99
  /* journal failure must not turn a guarded no-op into a crash */
75
100
  }
76
101
  }
102
+ const repeat = count > 1 ? ` (${count} rejections so far)` : "";
77
103
  console.error(
78
- `[spine] refused batch-state write (${reason}) for batch ${batchId || "unknown"} — keeping on-disk state`,
104
+ `[spine] refused batch-state write (${reason}) for batch ${batchId || "unknown"} — keeping on-disk state${repeat}`,
79
105
  );
80
106
  }
81
107
 
@@ -101,8 +127,8 @@ function persistSpineBatchStateGuarded(projectRoot, state, options) {
101
127
  });
102
128
  if (!guard.allowed) {
103
129
  const reason = String(guard.reason ?? "unknown");
104
- reportRejectedBatchStateWrite(projectRoot, state, reason);
105
130
  const loaded = loadSpineBatchState(projectRoot);
131
+ reportRejectedBatchStateWrite(projectRoot, state, reason, loaded.raw ? readBatchEnginePid(loaded.raw) : null);
106
132
  return { ok: false, reason, state: loaded.raw ?? state };
107
133
  }
108
134
 
@@ -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
  /**