pi-spine 2.16.0 → 2.18.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 (47) hide show
  1. package/bin/spine-gate.mjs +8 -2
  2. package/package.json +1 -1
  3. package/skills/create-spine-tasks/SKILL.md +3 -1
  4. package/skills/create-spine-tasks/references/contract-template.md +12 -12
  5. package/skills/create-spine-tasks/references/prompt-template.md +8 -6
  6. package/skills/spine-autonomous-operator/SKILL.md +2 -0
  7. package/skills/spine-autonomous-operator/references/agent-shell-batch-policy.md +1 -1
  8. package/skills/spine-orchestrate-waves/SKILL.md +6 -4
  9. package/skills/spine-orchestrate-waves/references/outer-loop.md +16 -1
  10. package/skills/spine-release-operator/SKILL.md +3 -0
  11. package/skills/spine-release-operator/references/pi-async-orchestration.md +2 -1
  12. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +14 -0
  13. package/src/batch/batch-guards.mjs +14 -0
  14. package/src/batch/batch-meta-reconstruct.mjs +5 -2
  15. package/src/batch/diagnosis-worker-done-missing.mjs +12 -1
  16. package/src/batch/engine-lanes/matrix-run.mjs +122 -26
  17. package/src/batch/engine-lanes/merge.mjs +16 -11
  18. package/src/batch/engine-lanes/phase.mjs +45 -0
  19. package/src/batch/engine-lanes/queue.mjs +1 -1
  20. package/src/batch/engine-lanes.mjs +9 -37
  21. package/src/batch/engine.mjs +8 -16
  22. package/src/batch/gate.mjs +153 -6
  23. package/src/batch/heartbeat.mjs +18 -0
  24. package/src/batch/post-merge-finalize.mjs +128 -0
  25. package/src/batch/post-merge-limbo.mjs +14 -85
  26. package/src/batch/readers/spine-state.mjs +22 -1
  27. package/src/batch/readers/taskplane-state.mjs +22 -1
  28. package/src/batch/reconcile-batch.mjs +1 -1
  29. package/src/batch/resume-common.mjs +1 -1
  30. package/src/batch/resume-gate-reopen.mjs +50 -0
  31. package/src/batch/resume-multi-validate.mjs +43 -0
  32. package/src/batch/resume-multi.mjs +6 -2
  33. package/src/batch/resume-prompt-parse-fail.mjs +75 -0
  34. package/src/batch/resume.mjs +21 -40
  35. package/src/batch/review-spawn.mjs +4 -3
  36. package/src/batch/salvage-batch-integrate-gate.mjs +180 -0
  37. package/src/batch/salvage-batch-integrate.mjs +66 -4
  38. package/src/batch/worker-heartbeat.mjs +31 -6
  39. package/src/batch/worker-host.mjs +27 -1
  40. package/src/batch/worker-output.mjs +56 -0
  41. package/src/cli/journal-follow.mjs +3 -1
  42. package/src/cli/lane-logs.mjs +3 -1
  43. package/src/cli/settings-slash.mjs +2 -1
  44. package/src/config/worker-context.mjs +2 -1
  45. package/src/planner/matrix.mjs +24 -0
  46. package/src/tasks/analyze/index.mjs +2 -1
  47. package/src/tasks/validate-contract-warn.mjs +45 -0
@@ -1,6 +1,27 @@
1
1
  // @ts-nocheck
2
2
  /**
3
3
  * Parse Taskplane `.pi/batch-state.json` for dogfood reconciliation.
4
+ *
5
+ * The normalized shape is declared locally so this reader stays a leaf in the batch import
6
+ * graph: a JSDoc type-import pointing at reconcile.mjs makes the arch cycle detector see a
7
+ * readers -> reconcile edge even though no runtime import exists (SP-735 / #267).
8
+ *
9
+ * @typedef {object} NormalizedBatchState
10
+ * @property {string} source
11
+ * @property {string} batchId
12
+ * @property {string} phase
13
+ * @property {string} baseBranch
14
+ * @property {string|null} orchBranch
15
+ * @property {unknown} startedAt
16
+ * @property {unknown} endedAt
17
+ * @property {number} failedTasks
18
+ * @property {number} succeededTasks
19
+ * @property {number} totalTasks
20
+ * @property {unknown[]} mergeResults
21
+ * @property {Array<object>} tasks
22
+ * @property {Array<object>} segments
23
+ * @property {Array<object>} lanes
24
+ * @property {Record<string, unknown>} raw
4
25
  */
5
26
 
6
27
  const TERMINAL_SUCCESS = new Set(["completed", "succeeded", "skipped", "done"]);
@@ -9,7 +30,7 @@ const ACTIVE = new Set(["pending", "running", "executing"]);
9
30
 
10
31
  /**
11
32
  * @param {unknown} raw
12
- * @returns {import("../reconcile.mjs").NormalizedBatchState | null}
33
+ * @returns {NormalizedBatchState | null}
13
34
  */
14
35
  export function parseTaskplaneBatchState(raw) {
15
36
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
@@ -22,7 +22,7 @@ import { inferWorkerDoneMissingFailure } from "./diagnosis-worker-done-missing.m
22
22
  import { inferEngineOrphanCause } from "./diagnosis-parent-exit.mjs";
23
23
  import { findStubMarkedSucceededTask } from "./diagnosis-stub.mjs";
24
24
  import { detectOrphanRunning, journalEventsSinceResume } from "./orphan-detect.mjs";
25
- import { computePendingTasks } from "./resume-multi.mjs";
25
+ import { computePendingTasks } from "./resume-validation.mjs";
26
26
  import { computeStatusProgress } from "./status-json.mjs";
27
27
  import {
28
28
  detectBatchStateDrift,
@@ -8,7 +8,7 @@ import path from "node:path";
8
8
  import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
9
9
  import { appendJournalEvent } from "./journal.mjs";
10
10
  import { recomputeTaskCounters } from "./state.mjs";
11
- import { loadTaskFileScopePaths } from "./engine-lanes.mjs";
11
+ import { loadTaskFileScopePaths } from "./engine-lanes/queue.mjs";
12
12
  import { laneWorktreePath } from "./worktree.mjs";
13
13
 
14
14
  /**
@@ -0,0 +1,50 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Force-resume gate reopen for completed batches (SP-740 / #275).
4
+ * Extracted from resume.mjs to keep that module under the 500 LOC cap.
5
+ */
6
+
7
+ import { reopenIntegrateGateForCompletedBatch } from "./gate.mjs";
8
+ import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
9
+
10
+ /**
11
+ * When `resumeCheck.gateReopen` is set, re-open the integrate gate and return
12
+ * a resumeBatch-shaped result. Caller must release the resume lock via the
13
+ * returned path (this helper releases it).
14
+ *
15
+ * @param {{
16
+ * projectRoot: string,
17
+ * resumeCheck: { batchId: string, gateReopen?: boolean },
18
+ * releaseResumeLock?: (() => void) | null,
19
+ * }} params
20
+ * @returns {object | null} resumeBatch result when handled; null when not a reopen path
21
+ */
22
+ export function tryResumeCompletedGateReopen({ projectRoot, resumeCheck, releaseResumeLock }) {
23
+ if (!resumeCheck?.gateReopen) {
24
+ return null;
25
+ }
26
+
27
+ const reopenState = loadSpineBatchState(projectRoot).raw;
28
+ const reopenResult = reopenIntegrateGateForCompletedBatch({
29
+ projectRoot,
30
+ batchId: resumeCheck.batchId,
31
+ batchState: reopenState,
32
+ });
33
+ if (reopenState) {
34
+ saveSpineBatchState(projectRoot, reopenState, { bypassWriteGuard: true });
35
+ }
36
+ releaseResumeLock?.();
37
+ const output = reopenResult.reopened
38
+ ? `Batch ${resumeCheck.batchId} gate re-opened: evidence re-collected, targetRevision re-pinned.\n → spine gate approve\n → spine integrate\n`
39
+ : `${reopenResult.headline}\n → ${reopenResult.suggestedCommand}\n`;
40
+ return {
41
+ ok: reopenResult.ok,
42
+ exitCode: reopenResult.exitCode,
43
+ batchId: resumeCheck.batchId,
44
+ reopened: reopenResult.reopened,
45
+ reopenReason: reopenResult.reason,
46
+ gate: reopenResult.gate,
47
+ error: reopenResult.error,
48
+ output,
49
+ };
50
+ }
@@ -194,6 +194,49 @@ export function validateMultiTaskResume({ projectRoot, force = false }) {
194
194
  const failedTasksCount = Number(state.failedTasks ?? 0);
195
195
  const failedPhaseRetryLimbo =
196
196
  phase === "failed" && failedTasksCount === 0 && pendingTasksForResume.length > 0;
197
+
198
+ // SP-740 / #275: completed batches are never worker-resumable, but after a
199
+ // `stale_revision` blocker or a removed gate record they still need a working
200
+ // re-open + re-approve path. Force resume on a completed batch routes through
201
+ // the gate re-open (no worker re-run) instead of dead-ending on cannot_resume.
202
+ if (phase === "completed") {
203
+ if (!force) {
204
+ return {
205
+ ok: false,
206
+ exitCode: 1,
207
+ error: "cannot_resume",
208
+ output: `Batch ${state.batchId} completed. Use spine gate reopen (or spine batch resume --force) to re-open the integrate gate.\n`,
209
+ batchId: state.batchId,
210
+ phase,
211
+ };
212
+ }
213
+ if (pendingTasksForResume.length > 0) {
214
+ return {
215
+ ok: false,
216
+ exitCode: 1,
217
+ error: "cannot_resume",
218
+ output: `Batch ${state.batchId} is completed but has pending tasks — use spine batch retry <taskId> instead.\n`,
219
+ batchId: state.batchId,
220
+ phase,
221
+ };
222
+ }
223
+ // Lane worktrees may already be cleaned up after completion; skip worker-oriented
224
+ // validation. The caller must route this through reopenIntegrateGateForCompletedBatch.
225
+ return {
226
+ ok: true,
227
+ batchId: state.batchId,
228
+ phase,
229
+ updatedAt: Number(state.updatedAt ?? 0),
230
+ pendingTasks: [],
231
+ lanes: [],
232
+ resumableWave: null,
233
+ postMergeLimbo: false,
234
+ orphanResume: false,
235
+ engineConfirmedDead: false,
236
+ gateReopen: true,
237
+ };
238
+ }
239
+
197
240
  const postMergeLimbo = detectPostMergeLimboForResume({ projectRoot, state });
198
241
  const orphanEligibility =
199
242
  phase === "running"
@@ -7,10 +7,13 @@ import { loadSpineConfig } from "../config/spine-config-load.mjs";
7
7
  import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
8
8
  import { resolveTasksRoot } from "../config/spine-preflight-lib.mjs";
9
9
  import { assessWaveMergeEligibility } from "./engine-scope.mjs";
10
- import { mergeWaveLanesToOrch } from "./engine-lanes.mjs";
10
+ import { mergeWaveLanesToOrch } from "./engine-lanes/merge.mjs";
11
11
  import { recordResumePhaseTransition } from "./resume-common.mjs";
12
12
  import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
13
- import { finalizeResumedBatchForIntegrate } from "./post-merge-limbo.mjs";
13
+ import {
14
+ finalizeResumedBatchForIntegrate,
15
+ maybeFinalizeAfterWaveMerge,
16
+ } from "./post-merge-limbo.mjs";
14
17
  import {
15
18
  succeededWaveMergeIndices,
16
19
  waveTasksAllTerminal,
@@ -211,6 +214,7 @@ export async function resumeMultiTaskBatch({ projectRoot, force = false, resumeC
211
214
  orchBranch,
212
215
  waveIndex,
213
216
  resumed: true,
217
+ finalizeAfterWaveMerge: maybeFinalizeAfterWaveMerge,
214
218
  });
215
219
  if (!mergeResult.ok) {
216
220
  return {
@@ -0,0 +1,75 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Single-lane resume prompt-parse failure path.
4
+ * Extracted from resume.mjs to keep that module under the 500 LOC cap.
5
+ */
6
+
7
+ import { appendJournalEvent } from "./journal.mjs";
8
+ import { saveSpineBatchState, updateSegmentForTask } from "./state.mjs";
9
+
10
+ /**
11
+ * Persist prompt-parse failure for a resumed single-lane task and return the
12
+ * resumeBatch-shaped error result.
13
+ *
14
+ * @param {{
15
+ * projectRoot: string,
16
+ * state: object,
17
+ * batchId: string,
18
+ * task: object,
19
+ * taskId: string,
20
+ * scopeResult: { error?: string, errors?: unknown, promptPath?: string },
21
+ * releaseResumeLock?: (() => void) | null,
22
+ * laneCorrelationId: string,
23
+ * }} params
24
+ */
25
+ export function failResumePromptParse({
26
+ projectRoot,
27
+ state,
28
+ batchId,
29
+ task,
30
+ taskId,
31
+ scopeResult,
32
+ releaseResumeLock,
33
+ laneCorrelationId,
34
+ }) {
35
+ task.status = "failed";
36
+ task.endedAt = Date.now();
37
+ task.exitReason = "prompt_parse_failed";
38
+ if (!task.startedAt) task.startedAt = Date.now();
39
+ updateSegmentForTask(state, taskId, "failed");
40
+ state.failedTasks = 1;
41
+ state.succeededTasks = 0;
42
+ state.endedAt = Date.now();
43
+ state.lastError = scopeResult.error?.slice(0, 500) ?? "prompt parse failed";
44
+ state.phase = "failed";
45
+ saveSpineBatchState(projectRoot, state);
46
+ appendJournalEvent(projectRoot, batchId, "task.prompt_parse_failed", {
47
+ taskId,
48
+ laneNumber: 1,
49
+ laneId: "lane-1",
50
+ correlationId: laneCorrelationId,
51
+ error: scopeResult.error,
52
+ errors: scopeResult.errors,
53
+ promptPath: scopeResult.promptPath,
54
+ resumed: true,
55
+ });
56
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
57
+ taskId,
58
+ laneNumber: 1,
59
+ laneId: "lane-1",
60
+ correlationId: laneCorrelationId,
61
+ classification: "prompt_parse_failed",
62
+ exitCode: 1,
63
+ output: scopeResult.error,
64
+ resumed: true,
65
+ });
66
+ releaseResumeLock?.();
67
+ return {
68
+ ok: false,
69
+ exitCode: 1,
70
+ batchId,
71
+ taskId,
72
+ error: "prompt_parse_failed",
73
+ output: scopeResult.error,
74
+ };
75
+ }
@@ -16,7 +16,7 @@ import { finalizeResumedBatchForIntegrate, isPostMergeLimbo } from "./post-merge
16
16
  import { prepareOrphanResumeHandoff } from "./resume-engine.mjs";
17
17
  import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
18
18
  import { commitLaneWorktree, filterPorcelain, gitPorcelain } from "./lane-commit.mjs";
19
- import { mergeLaneToOrch } from "./engine-lanes.mjs";
19
+ import { mergeLaneToOrch } from "./engine-lanes/merge.mjs";
20
20
  import {
21
21
  loadResumeFileScopePaths,
22
22
  recordResumePhaseTransition,
@@ -24,6 +24,8 @@ import {
24
24
  resolveTaskFolderRel,
25
25
  taskAlreadyComplete,
26
26
  } from "./resume-common.mjs";
27
+ import { tryResumeCompletedGateReopen } from "./resume-gate-reopen.mjs";
28
+ import { failResumePromptParse } from "./resume-prompt-parse-fail.mjs";
27
29
  import {
28
30
  countPendingSegments,
29
31
  loadSpineBatchState,
@@ -66,6 +68,16 @@ export async function resumeBatch({ projectRoot, force = false }) {
66
68
  return resumeCheck;
67
69
  }
68
70
 
71
+ // SP-740 / #275: completed + force re-opens the integrate gate (no worker re-run).
72
+ const gateReopenResult = tryResumeCompletedGateReopen({
73
+ projectRoot,
74
+ resumeCheck,
75
+ releaseResumeLock,
76
+ });
77
+ if (gateReopenResult) {
78
+ return gateReopenResult;
79
+ }
80
+
69
81
  installAttachedEngineShutdownHandlers({ projectRoot });
70
82
 
71
83
  const loaded = loadSpineBatchState(projectRoot);
@@ -102,47 +114,16 @@ export async function resumeBatch({ projectRoot, force = false }) {
102
114
  const taskFolderOnHost = resolveTaskFolderOnHost(projectRoot, taskFolderRel, tasksRootRel, taskId);
103
115
  const scopeResult = loadResumeFileScopePaths(taskFolderOnHost);
104
116
  if (!scopeResult.ok) {
105
- const laneCorrelationId = crypto.randomUUID();
106
- task.status = "failed";
107
- task.endedAt = Date.now();
108
- task.exitReason = "prompt_parse_failed";
109
- if (!task.startedAt) task.startedAt = Date.now();
110
- updateSegmentForTask(state, taskId, "failed");
111
- state.failedTasks = 1;
112
- state.succeededTasks = 0;
113
- state.endedAt = Date.now();
114
- state.lastError = scopeResult.error?.slice(0, 500) ?? "prompt parse failed";
115
- state.phase = "failed";
116
- saveSpineBatchState(projectRoot, state);
117
- appendJournalEvent(projectRoot, batchId, "task.prompt_parse_failed", {
118
- taskId,
119
- laneNumber: 1,
120
- laneId: "lane-1",
121
- correlationId: laneCorrelationId,
122
- error: scopeResult.error,
123
- errors: scopeResult.errors,
124
- promptPath: scopeResult.promptPath,
125
- resumed: true,
126
- });
127
- appendJournalEvent(projectRoot, batchId, "task.failed", {
128
- taskId,
129
- laneNumber: 1,
130
- laneId: "lane-1",
131
- correlationId: laneCorrelationId,
132
- classification: "prompt_parse_failed",
133
- exitCode: 1,
134
- output: scopeResult.error,
135
- resumed: true,
136
- });
137
- releaseResumeLock?.();
138
- return {
139
- ok: false,
140
- exitCode: 1,
117
+ return failResumePromptParse({
118
+ projectRoot,
119
+ state,
141
120
  batchId,
121
+ task,
142
122
  taskId,
143
- error: "prompt_parse_failed",
144
- output: scopeResult.error,
145
- };
123
+ scopeResult,
124
+ releaseResumeLock,
125
+ laneCorrelationId: crypto.randomUUID(),
126
+ });
146
127
  }
147
128
  const fileScopePaths = scopeResult.fileScopePaths;
148
129
 
@@ -181,8 +181,9 @@ export function isEarlyArtifactHonorAllowed(reviewType, contractVerifyResult) {
181
181
 
182
182
  /**
183
183
  * @param {object} params
184
+ * @returns {Promise<object>} Resolves with the reviewer spawn result (real async child-process wait).
184
185
  */
185
- export async function spawnReviewerPi({
186
+ export function spawnReviewerPi({
186
187
  worktreePath,
187
188
  taskFolder,
188
189
  reviewPrompt,
@@ -194,11 +195,11 @@ export async function spawnReviewerPi({
194
195
  contractVerifyResult = null,
195
196
  }) {
196
197
  if (!reviewerPiCommandExists("pi")) {
197
- return {
198
+ return Promise.resolve({
198
199
  spawnFailed: true,
199
200
  exitCode: 127,
200
201
  error: "pi not available for reviewer spawn",
201
- };
202
+ });
202
203
  }
203
204
 
204
205
  const piArgs = buildReviewerPiArgs({
@@ -0,0 +1,180 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Salvage --integrate gate open path (#274).
4
+ * Extracted from salvage-batch-integrate.mjs to keep that module under the 500 LOC cap.
5
+ */
6
+
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { writeJsonAtomic } from "../fs/atomic-write.mjs";
10
+ import {
11
+ evidenceDir,
12
+ loadGateRecord,
13
+ maybeAutoApproveIntegrateGate,
14
+ openIntegrateGate,
15
+ } from "./gate.mjs";
16
+ import { gitExec } from "./git-exec.mjs";
17
+ import { archiveBatchStatePath } from "./lifecycle.mjs";
18
+ import { appendJournalEvent } from "./journal.mjs";
19
+ import { loadBatchStateFile } from "./reconcile.mjs";
20
+
21
+ /**
22
+ * Load archived seed state (or matching live state) for a finished batch.
23
+ * Mirrors the seed resolution used by salvage-batch-list.mjs.
24
+ *
25
+ * @param {string} projectRoot
26
+ * @param {string} batchId
27
+ * @returns {object|null}
28
+ */
29
+ function loadSalvageBatchSeed(projectRoot, batchId) {
30
+ const archivePath = archiveBatchStatePath(projectRoot, batchId);
31
+ if (fs.existsSync(archivePath)) {
32
+ try {
33
+ return JSON.parse(fs.readFileSync(archivePath, "utf-8"));
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ const loaded = loadBatchStateFile(projectRoot);
40
+ if (loaded.raw && String(loaded.raw.batchId ?? loaded.raw.id ?? "") === batchId) {
41
+ return loaded.raw;
42
+ }
43
+
44
+ return null;
45
+ }
46
+
47
+ /**
48
+ * True only when the gate check failed solely on a missing gate record (#274).
49
+ * Pending / rejected / stale-revision gates keep their existing blocked paths.
50
+ *
51
+ * @param {{ ok?: boolean, gate?: object|null, blockers?: Array<{ code?: string }> }} gateCheck
52
+ */
53
+ export function gateBlockedOnMissingGate(gateCheck) {
54
+ return (
55
+ gateCheck.gate == null &&
56
+ Array.isArray(gateCheck.blockers) &&
57
+ gateCheck.blockers.some((blocker) => blocker?.code === "missing_gate")
58
+ );
59
+ }
60
+
61
+ /**
62
+ * Best-effort rev-parse of a branch tip SHA for salvage evidence.
63
+ *
64
+ * @param {string} projectRoot
65
+ * @param {string} ref
66
+ * @returns {string|null}
67
+ */
68
+ function resolveTipSha(projectRoot, ref) {
69
+ try {
70
+ return gitExec(projectRoot, ["rev-parse", "--verify", `${ref}^{commit}`], { projectRoot }) || null;
71
+ } catch {
72
+ return null;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Write salvage inspection evidence into the gate evidence dir.
78
+ * `collectCoreEvidenceBundle` picks up `salvage-*.json` files as gate evidence refs.
79
+ *
80
+ * @param {string} projectRoot
81
+ * @param {string} batchId
82
+ * @param {object} snapshot
83
+ * @returns {string} evidence ref
84
+ */
85
+ function writeSalvageGateEvidence(projectRoot, batchId, snapshot) {
86
+ const dir = evidenceDir(projectRoot, batchId);
87
+ fs.mkdirSync(dir, { recursive: true });
88
+ writeJsonAtomic(path.join(dir, "salvage-inspect.json"), {
89
+ ...snapshot,
90
+ inspectedAt: new Date().toISOString(),
91
+ source: "batch salvage --integrate",
92
+ });
93
+ return "evidence/salvage-inspect.json";
94
+ }
95
+
96
+ /**
97
+ * Open a fresh integrate gate from salvage inspection evidence (#274).
98
+ *
99
+ * A batch that failed before the merge phase never journaled `gate.opened`, so
100
+ * salvage --integrate used to dead-end on "no gate record". When the lane is
101
+ * verified salvageable (terminal-success tasks, commits ahead — established by
102
+ * `listSalvageableLanes` before this runs), open the gate here with salvage
103
+ * evidence plus the current orch tip pin. Approval posture still applies: the
104
+ * fresh gate stays pending unless config explicitly opts in to auto-approve.
105
+ *
106
+ * @param {string} projectRoot
107
+ * @param {string} batchId
108
+ * @param {object} ctx
109
+ * @param {object} ctx.lane
110
+ * @param {string} ctx.baseBranch
111
+ * @param {string} ctx.taskBranch
112
+ * @param {number} ctx.commitsAhead
113
+ * @param {object|null} ctx.config
114
+ * @returns {{ ok: true, opened: boolean, gate: object, evidenceRefs: string[] } | { ok: false, error: string }}
115
+ */
116
+ export function openGateFromSalvageEvidence(projectRoot, batchId, ctx) {
117
+ const { lane, baseBranch, taskBranch, commitsAhead, config } = ctx;
118
+
119
+ // Fail closed when salvage evidence is insufficient to justify a gate.
120
+ if (!lane || !Array.isArray(lane.salvageableTasks) || lane.salvageableTasks.length === 0) {
121
+ return { ok: false, error: "salvage_evidence_insufficient" };
122
+ }
123
+ if (!Number.isFinite(commitsAhead) || commitsAhead <= 0) {
124
+ return { ok: false, error: "salvage_commits_ahead_required" };
125
+ }
126
+
127
+ /** @type {string[]} */
128
+ const salvageEvidenceRefs = [];
129
+ try {
130
+ salvageEvidenceRefs.push(
131
+ writeSalvageGateEvidence(projectRoot, batchId, {
132
+ batchId,
133
+ laneNumber: lane.laneNumber,
134
+ taskBranch,
135
+ baseBranch,
136
+ commitsAhead,
137
+ salvageableTasks: lane.salvageableTasks,
138
+ excludedTasks: lane.excludedTasks ?? [],
139
+ diffStat: lane.diffStat ?? null,
140
+ baseTip: resolveTipSha(projectRoot, baseBranch),
141
+ laneTip: resolveTipSha(projectRoot, taskBranch),
142
+ }),
143
+ );
144
+ } catch (err) {
145
+ const message = err instanceof Error ? err.message : String(err);
146
+ return { ok: false, error: `salvage_evidence_write_failed: ${message}` };
147
+ }
148
+
149
+ const batchState = loadSalvageBatchSeed(projectRoot, batchId);
150
+ try {
151
+ const opened = openIntegrateGate({ projectRoot, batchId, batchState, config });
152
+ const gate = loadGateRecord(projectRoot, batchId);
153
+ if (!gate || !Array.isArray(gate.evidenceRefs) || gate.evidenceRefs.length === 0) {
154
+ return { ok: false, error: "gate_open_verification_failed" };
155
+ }
156
+
157
+ // Respect approval posture — auto-approves only when config opts in.
158
+ maybeAutoApproveIntegrateGate({ projectRoot, batchId, config });
159
+
160
+ appendJournalEvent(projectRoot, batchId, "batch.salvage_gate_opened", {
161
+ laneNumber: lane.laneNumber,
162
+ taskBranch,
163
+ baseBranch,
164
+ commitsAhead,
165
+ gateId: gate.gateId,
166
+ gateAlreadyOpen: opened.opened !== true,
167
+ salvageEvidenceRefs,
168
+ });
169
+
170
+ return {
171
+ ok: true,
172
+ opened: opened.opened === true,
173
+ gate: loadGateRecord(projectRoot, batchId) ?? gate,
174
+ evidenceRefs: gate.evidenceRefs,
175
+ };
176
+ } catch (err) {
177
+ const message = err instanceof Error ? err.message : String(err);
178
+ return { ok: false, error: `gate_open_failed: ${message}` };
179
+ }
180
+ }
@@ -12,6 +12,10 @@ import { gitExec } from "./git-exec.mjs";
12
12
  import { mergeOrchIntoBaseIsolated, syncPlumbingMergePathsToWorktree } from "./integrate-worktree.mjs";
13
13
  import { appendJournalEvent } from "./journal.mjs";
14
14
  import { resolveRulesManifestIntegrateDrift } from "./rules-manifest-drift.mjs";
15
+ import {
16
+ gateBlockedOnMissingGate,
17
+ openGateFromSalvageEvidence,
18
+ } from "./salvage-batch-integrate-gate.mjs";
15
19
  import { laneTaskBranch } from "./worktree.mjs";
16
20
  import { listSalvageableLanes } from "./salvage-batch-list.mjs";
17
21
 
@@ -153,13 +157,54 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
153
157
  }
154
158
 
155
159
  const configResult = loadSpineConfig(projectRoot);
156
- const gateCheck = checkIntegrateGate({
160
+ const config = configResult.config ?? null;
161
+ let gateCheck = checkIntegrateGate({
157
162
  projectRoot,
158
163
  batchId: resolvedBatchId,
159
- config: configResult.config ?? null,
164
+ config,
160
165
  forceIntegrate,
161
166
  });
162
167
 
168
+ // #274 — a batch that failed before merge never opened the integrate gate,
169
+ // so the old path dead-ended on "no gate record". When the lane is salvageable,
170
+ // open a fresh gate from salvage evidence instead of failing.
171
+ let gateOpenedBySalvage = false;
172
+ if (!gateCheck.ok && gateBlockedOnMissingGate(gateCheck)) {
173
+ const openResult = openGateFromSalvageEvidence(projectRoot, resolvedBatchId, {
174
+ lane,
175
+ baseBranch,
176
+ taskBranch,
177
+ commitsAhead,
178
+ config,
179
+ });
180
+
181
+ if (!openResult.ok) {
182
+ appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
183
+ laneNumber: laneNum,
184
+ taskBranch,
185
+ baseBranch,
186
+ gateBlocked: true,
187
+ gateStatus: "missing",
188
+ error: openResult.error,
189
+ });
190
+
191
+ return {
192
+ ok: false,
193
+ exitCode: 2,
194
+ failureClass: "GateBlocked",
195
+ error: openResult.error,
196
+ headline: "Salvage integrate blocked — could not open integrate gate from salvage evidence",
197
+ suggestedCommand: "spine status --diagnose",
198
+ alternatives: ["spine gate status"],
199
+ batchId: resolvedBatchId,
200
+ laneNumber: laneNum,
201
+ };
202
+ }
203
+
204
+ gateOpenedBySalvage = true;
205
+ gateCheck = checkIntegrateGate({ projectRoot, batchId: resolvedBatchId, config, forceIntegrate });
206
+ }
207
+
163
208
  if (!gateCheck.ok) {
164
209
  appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
165
210
  laneNumber: laneNum,
@@ -167,6 +212,7 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
167
212
  baseBranch,
168
213
  gateBlocked: true,
169
214
  gateStatus: gateCheck.gate?.status ?? "missing",
215
+ gateOpenedBySalvage,
170
216
  error: gateCheck.error ?? gateCheck.headline,
171
217
  });
172
218
 
@@ -175,12 +221,20 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
175
221
  exitCode: gateCheck.exitCode ?? 2,
176
222
  failureClass: gateCheck.failureClass ?? "GateBlocked",
177
223
  error: gateCheck.error,
178
- headline: gateCheck.headline ?? "Salvage integrate blocked by gate",
224
+ headline: gateOpenedBySalvage
225
+ ? "Salvage opened a fresh integrate gate — approve it, then re-run salvage integrate"
226
+ : gateCheck.headline ?? "Salvage integrate blocked by gate",
179
227
  suggestedCommand: gateCheck.suggestedCommand ?? "spine gate approve",
180
- alternatives: gateCheck.alternatives ?? ["/spine-gate approve"],
228
+ alternatives: gateOpenedBySalvage
229
+ ? [
230
+ "/spine-gate approve",
231
+ `spine batch salvage --batch ${resolvedBatchId} --lane ${laneNum} --integrate --yes`,
232
+ ]
233
+ : gateCheck.alternatives ?? ["/spine-gate approve"],
181
234
  batchId: resolvedBatchId,
182
235
  laneNumber: laneNum,
183
236
  gate: gateCheck.gate ?? null,
237
+ gateOpenedBySalvage,
184
238
  };
185
239
  }
186
240
 
@@ -261,6 +315,7 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
261
315
  excludedTasks: lane.excludedTasks,
262
316
  gateRequired: gateCheck.required ?? false,
263
317
  gateForced: gateCheck.forced ?? false,
318
+ gateOpenedBySalvage,
264
319
  });
265
320
 
266
321
  const mergeResult = mergeOrchIntoBaseIsolated({
@@ -351,6 +406,7 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
351
406
  commitsAhead,
352
407
  salvageableTasks: lane.salvageableTasks,
353
408
  excludedTasks: lane.excludedTasks,
409
+ gateOpenedBySalvage,
354
410
  headline: `Salvaged lane ${laneNum} (${taskBranch}) into ${baseBranch}`,
355
411
  suggestedCommand: "spine status --diagnose",
356
412
  };
@@ -375,6 +431,12 @@ export function formatSalvageIntegrateOutput(result, options = {}) {
375
431
  if (result.error) {
376
432
  lines.push("", ` Error: ${result.error}`);
377
433
  }
434
+ if (result.gateOpenedBySalvage) {
435
+ lines.push(
436
+ "",
437
+ " Gate: opened by salvage from inspection evidence (evidence/salvage-inspect.json)",
438
+ );
439
+ }
378
440
  if (result.batchId) {
379
441
  lines.push("", ` Batch: ${result.batchId}`);
380
442
  }