pi-spine 2.27.0 → 2.27.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 (38) hide show
  1. package/bin/spine-worker-runner.mjs +1 -0
  2. package/package.json +1 -1
  3. package/skills/create-spine-tasks/SKILL.md +60 -33
  4. package/skills/create-spine-tasks/references/authoring-evidence.md +58 -0
  5. package/skills/create-spine-tasks/references/contract-template.md +52 -7
  6. package/skills/create-spine-tasks/references/prompt-template.md +72 -8
  7. package/skills/spine-release-operator/SKILL.md +30 -51
  8. package/skills/spine-release-operator/references/issue-intake-checklist.md +3 -1
  9. package/skills/spine-release-operator/references/pi-async-orchestration.md +13 -9
  10. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +8 -1
  11. package/skills/spine-release-operator/references/publish-recovery.md +62 -0
  12. package/src/batch/diagnosis-alternatives.mjs +16 -1
  13. package/src/batch/diagnosis-pending-lane.mjs +18 -0
  14. package/src/batch/diagnosis-review-infra.mjs +144 -0
  15. package/src/batch/diagnosis-suggested-command.mjs +9 -0
  16. package/src/batch/diagnosis.mjs +19 -20
  17. package/src/batch/engine-lanes/merge.mjs +0 -8
  18. package/src/batch/engine-lanes/review-poll.mjs +4 -1
  19. package/src/batch/engine-lanes.mjs +0 -1
  20. package/src/batch/gate-posture-approve.mjs +154 -15
  21. package/src/batch/integrate-path-delete.mjs +85 -0
  22. package/src/batch/integrate-worktree.mjs +20 -27
  23. package/src/batch/provider-quota.mjs +1 -1
  24. package/src/batch/reconcile-diagnosis.mjs +24 -77
  25. package/src/batch/review-artifacts.mjs +3 -2
  26. package/src/batch/review-level-effective.mjs +19 -0
  27. package/src/batch/review-spawn.mjs +12 -1
  28. package/src/batch/review-step-run.mjs +14 -2
  29. package/src/batch/reviewer-provider-error.mjs +153 -0
  30. package/src/batch/worker-prompt.mjs +5 -2
  31. package/src/config/cursor-rules/discover.mjs +38 -1
  32. package/src/config/settings-fields.mjs +5 -0
  33. package/src/config/spine-config-schema.mjs +38 -0
  34. package/src/doctor/pi-extension-hooks.mjs +322 -0
  35. package/src/doctor/run-doctor-checks.mjs +14 -1
  36. package/src/tasks/packet/validate-prompt.mjs +11 -1
  37. package/src/tasks/validate-contract-warn.mjs +16 -0
  38. package/templates/spine-config.json +1 -1
@@ -57,7 +57,6 @@ export {
57
57
  mergeWaveLanesToOrch,
58
58
  resolveRulesManifestIntegrateDrift,
59
59
  tryAutoResolveMergeConflicts,
60
- tryAutoResolveRulesManifestMergeConflict,
61
60
  } from "./engine-lanes/merge.mjs";
62
61
 
63
62
  export { syncLaneWorktreeFromOrch } from "./worktree.mjs";
@@ -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,
@@ -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"], {
@@ -90,7 +90,7 @@ function extractBalancedObject(text, startIndex) {
90
90
  * @param {string} output
91
91
  * @returns {{httpStatus: number, payload: Record<string, any>}[]}
92
92
  */
93
- function collectStatusPayloads(output) {
93
+ export function collectStatusPayloads(output) {
94
94
  const candidates = [];
95
95
  STATUS_JSON_PATTERN.lastIndex = 0;
96
96
  let match;
@@ -1,6 +1,11 @@
1
1
  /** Diagnosis derivation (SP-596/SP-606 / #192). */
2
2
 
3
3
  import { inferLaunchFailureKind } from "./diagnosis.mjs";
4
+ import {
5
+ REVIEW_INFRASTRUCTURE_EXIT_REASONS,
6
+ resolvePrimaryFailureExitReason,
7
+ resolveTaskPrimaryFailureExitReason,
8
+ } from "./diagnosis-review-infra.mjs";
4
9
  import {
5
10
  findPendingLaneLandTasks,
6
11
  shouldDiagnosePendingLaneLand,
@@ -21,56 +26,6 @@ export {
21
26
  laneTaskBranchForDiagnosis,
22
27
  } from "./reconcile-diagnosis-enrich.mjs";
23
28
 
24
- /**
25
- * @param {unknown} rawTasks
26
- * @param {string|null} failedTaskId
27
- * @returns {string|null}
28
- */
29
- function resolveFailedExitReason(rawTasks, failedTaskId) {
30
- if (!failedTaskId || !Array.isArray(rawTasks)) return null;
31
- const match = rawTasks.find((/** @type {any} */ entry) => {
32
- if (!entry || typeof entry !== "object") return false;
33
- return String(entry.taskId ?? entry.id ?? "") === failedTaskId;
34
- });
35
- if (!match || typeof match !== "object") return null;
36
- const exitReason = /** @type {{ exitReason?: unknown }} */ (match).exitReason;
37
- return typeof exitReason === "string" && exitReason ? exitReason : null;
38
- }
39
-
40
- /**
41
- * @param {string|null} failedTaskId
42
- * @param {Record<string, any>} signals
43
- * @returns {string|null}
44
- */
45
- function resolvePrimaryFailureExitReason(failedTaskId, signals) {
46
- const fromTask = resolveFailedExitReason(signals.raw?.tasks, failedTaskId);
47
- if (fromTask) return fromTask;
48
- if (!failedTaskId) return null;
49
- if (Array.isArray(signals.segments)) {
50
- const segment = signals.segments.find((/** @type {any} */ entry) => entry?.taskId === failedTaskId);
51
- const classification = segment?.classification;
52
- if (
53
- typeof classification === "string" &&
54
- classification &&
55
- classification !== "terminal-failure"
56
- ) {
57
- return classification;
58
- }
59
- }
60
- if (Array.isArray(signals.journalEvents)) {
61
- for (let index = signals.journalEvents.length - 1; index >= 0; index -= 1) {
62
- const event = signals.journalEvents[index];
63
- if (event.type !== "task.failed") continue;
64
- const eventTaskId = event.taskId ?? event.payload?.taskId;
65
- if (eventTaskId !== failedTaskId) continue;
66
- const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
67
- const reason = payload.exitReason ?? payload.classification;
68
- if (typeof reason === "string" && reason) return reason;
69
- }
70
- }
71
- return null;
72
- }
73
-
74
29
  /**
75
30
  * @param {string|null} failedTaskId
76
31
  * @param {string|null} exitReason
@@ -134,33 +89,24 @@ function hasNeedsReplanBlocker(signals) {
134
89
  return tasks.some((/** @type {any} */ task) => task?.exitReason === "needs_replan");
135
90
  }
136
91
 
137
- /**
138
- * Plan-review exit reasons where reviewer infrastructure failed after the
139
- * worker had already completed its lane work (#291 / SP-762). Mirrors the
140
- * SP-718 final-review distinction: spawn failure / timeout mean no verdict
141
- * was produced — the implementation itself is not the failure.
142
- */
143
- const POST_DONE_PLAN_REVIEW_EXIT_REASONS = new Set([
144
- "plan_review_spawn_failed",
145
- "plan_review_timeout",
146
- ]);
147
-
148
92
  /**
149
93
  * Failed task whose lane work already completed (done evidence / `.DONE` in
150
- * the lane worktree) but whose engine plan review failed to spawn or timed
151
- * out. Such tasks are salvageable land-loop candidates — a full worker retry
152
- * would re-run expensive work that is already on disk (#291 / SP-762).
94
+ * the lane worktree) but whose engine review (plan, code, or final) failed to
95
+ * spawn, timed out, or hit a provider error — no verdict was ever produced
96
+ * (SP-821 / #334). Such tasks get re-review guidance, not salvage: the retry
97
+ * command resumes at the review (`runWorker` no-ops on existing `.DONE`),
98
+ * whereas `salvage --integrate` lands code no reviewer saw. This reverses the
99
+ * SP-762 pending_lane_land mapping for the plan-review case (#291) and
100
+ * extends the shared reason set to code/final and provider errors.
153
101
  *
154
102
  * Parsed batch-state tasks drop `exitReason` (normalizeTasks), so the exit
155
103
  * reason is resolved the same way deriveFailureContext resolves it: from the
156
104
  * task entry when present, else raw state / journal `task.failed` events.
157
- * The salvage command itself hard-gates on commits-ahead, so pointing at it
158
- * without lane commits is safe (dry-run reports none salvageable).
159
105
  *
160
106
  * @param {Record<string, any>} signals
161
107
  * @returns {Record<string, any>|null}
162
108
  */
163
- function findPostDonePlanReviewSpawnFailedTask(signals) {
109
+ function findPostDoneReviewInfraFailedTask(signals) {
164
110
  const tasks = Array.isArray(signals.tasks) ? signals.tasks : [];
165
111
  for (const task of tasks) {
166
112
  if (String(task?.status ?? "").toLowerCase() !== "failed") continue;
@@ -170,9 +116,8 @@ function findPostDonePlanReviewSpawnFailedTask(signals) {
170
116
  task?.doneFileFound === true ||
171
117
  String(task?.classification ?? "").toLowerCase() === "terminal-success";
172
118
  if (!hasDoneEvidence) continue;
173
- const taskId = String(task?.taskId ?? "");
174
- const exitReason = task?.exitReason ?? resolvePrimaryFailureExitReason(taskId, signals);
175
- if (!POST_DONE_PLAN_REVIEW_EXIT_REASONS.has(String(exitReason ?? ""))) continue;
119
+ const exitReason = resolveTaskPrimaryFailureExitReason(task, signals);
120
+ if (!REVIEW_INFRASTRUCTURE_EXIT_REASONS.has(String(exitReason ?? ""))) continue;
176
121
  return task;
177
122
  }
178
123
  return null;
@@ -278,14 +223,16 @@ export function deriveDiagnosis(signals) {
278
223
  if (doneMissing) {
279
224
  return withFailureContext("worker_done_missing", failedTaskId, signals);
280
225
  }
281
- // Post-DONE plan-review spawn failure: lane work is complete, so map to
282
- // pending_lane_land (salvage / land-loop guidance) instead of needs_retry,
283
- // whose retry language would force an expensive worker re-run (#291 / SP-762).
284
- const postDonePlanReviewTask = findPostDonePlanReviewSpawnFailedTask(signals);
285
- if (postDonePlanReviewTask) {
226
+ // Post-DONE review-infrastructure failure (plan/code/final spawn failure,
227
+ // timeout, or provider error): lane work is complete but no verdict was
228
+ // produced. Map to needs_retry — `spine batch retry` resumes at the review
229
+ // because runWorker no-ops on the existing lane .DONE. Salvage --integrate
230
+ // would land code no reviewer saw (SP-821 / #334, reversing SP-762).
231
+ const postDoneReviewInfraTask = findPostDoneReviewInfraFailedTask(signals);
232
+ if (postDoneReviewInfraTask) {
286
233
  return withFailureContext(
287
- "pending_lane_land",
288
- postDonePlanReviewTask.taskId ?? failedTaskId,
234
+ "needs_retry",
235
+ postDoneReviewInfraTask.taskId ?? failedTaskId,
289
236
  signals,
290
237
  );
291
238
  }
@@ -4,7 +4,8 @@ import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { detectOrphanedReviewStarted } from "./journal-rebuild.mjs";
6
6
  import { NESTED_REVIEW_SPAWN_REASON } from "./review-spawn.mjs";
7
- import { normalizeVerdict, parseReviewLevel, parseReviewVerdict } from "./review-shared.mjs";
7
+ import { normalizeVerdict, parseReviewVerdict } from "./review-shared.mjs";
8
+ import { effectiveReviewLevel } from "./review-level-effective.mjs";
8
9
  import { shouldUseReviewStub } from "./engine-lanes/review-stub.mjs";
9
10
 
10
11
  /**
@@ -13,7 +14,7 @@ import { shouldUseReviewStub } from "./engine-lanes/review-stub.mjs";
13
14
  export function readReviewLevel(taskFolder) {
14
15
  const promptPath = path.join(taskFolder, "PROMPT.md");
15
16
  if (!fs.existsSync(promptPath)) return 0;
16
- return parseReviewLevel(fs.readFileSync(promptPath, "utf-8"));
17
+ return effectiveReviewLevel(fs.readFileSync(promptPath, "utf-8"));
17
18
  }
18
19
 
19
20
  /**
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Effective review level for a task packet (SP-827 / #336).
3
+ *
4
+ * `**Type:** execute` packets run no reviewers (operator runbook §2.5), so
5
+ * their effective review level is 0 regardless of the declared level. `llm`
6
+ * packets return their declared level unchanged.
7
+ */
8
+
9
+ import { parsePrompt } from "../tasks/packet/parse-prompt.mjs";
10
+ import { parseReviewLevel } from "./review-shared.mjs";
11
+
12
+ /**
13
+ * @param {string} markdown PROMPT.md contents
14
+ * @returns {number}
15
+ */
16
+ export function effectiveReviewLevel(markdown) {
17
+ if (parsePrompt(markdown).type === "execute") return 0;
18
+ return parseReviewLevel(markdown);
19
+ }
@@ -108,6 +108,13 @@ function reviewerPiCommandExists(cmd) {
108
108
  }
109
109
 
110
110
  /**
111
+ * Build the argv for a reviewer `pi` spawn.
112
+ *
113
+ * SP-819 / #334: reviewers pass `-ne` (pi `--no-extensions`) by default so operator-installed
114
+ * pi extensions (e.g. context-rewriting hooks) cannot break review runs. Core tools are not
115
+ * extensions, so reviewers keep read/bash/write. `agents.reviewer.loadUserExtensions: true`
116
+ * opts back into user extensions.
117
+ *
111
118
  * @param {object} params
112
119
  */
113
120
  export function buildReviewerPiArgs({
@@ -122,7 +129,11 @@ export function buildReviewerPiArgs({
122
129
  const reviewerModel = resolveReviewerModelPin(config, reviewType);
123
130
  const reviewerThinking = resolveReviewerThinkingPin(config, reviewType);
124
131
 
125
- const piArgs = ["-p", "--no-session"];
132
+ const piArgs = [];
133
+ if (config?.agents?.reviewer?.loadUserExtensions !== true) {
134
+ piArgs.push("-ne");
135
+ }
136
+ piArgs.push("-p", "--no-session");
126
137
  if (reviewerAgentPath && fs.existsSync(reviewerAgentPath)) {
127
138
  piArgs.push("--append-system-prompt", reviewerAgentPath);
128
139
  }