pi-spine 2.3.1 → 2.4.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.
@@ -38,7 +38,8 @@ const BATCH_FLAG_VALUE_TAKERS = new Set([
38
38
  */
39
39
  export function printBatchHelp() {
40
40
  return (
41
- "Usage: spine batch start <scope>|pause|resume|retry <taskId>|skip <taskId>|force-merge [--wave N]|salvage|abort|dismiss|complete [--batch ID] [--lane N] [--integrate] [--yes] [--reason TEXT] [--hard] [--force] [--force-superseded] [--attached] [--dry-run] [--wave N] [--through-wave N] [--skip-preflight] [--detect-manual-merge] [--json]\n"
41
+ "Usage: spine batch start <scope>|pause|resume|retry <taskId>|skip <taskId>|force-merge [--wave N]|salvage|abort|dismiss|complete [--batch ID] [--lane N] [--integrate] [--yes] [--reason TEXT] [--hard] [--force] [--force-superseded] [--attached] [--dry-run] [--wave N] [--through-wave N] [--skip-preflight] [--detect-manual-merge] [--json]\n" +
42
+ " abort --dry-run Preview abort (reason/archive target); does not archive, journal, or clear live batch\n"
42
43
  );
43
44
  }
44
45
 
@@ -113,8 +114,14 @@ export function formatLifecycleHuman(result, json = false) {
113
114
  if (result.diagnosis) {
114
115
  lines.push(` Diagnosis: ${result.diagnosis}`);
115
116
  }
117
+ if (result.dryRun) {
118
+ lines.push(` Dry-run: true (no mutation)`);
119
+ }
116
120
  if (result.archivePath) {
117
- lines.push(` Archive: ${result.archivePath}`);
121
+ lines.push(result.dryRun ? ` Would archive: ${result.archivePath}` : ` Archive: ${result.archivePath}`);
122
+ }
123
+ if (result.reason) {
124
+ lines.push(` Reason: ${result.reason}`);
118
125
  }
119
126
 
120
127
  lines.push("", ` → ${result.suggestedCommand}`);
@@ -300,6 +307,7 @@ export async function runSpineBatch(options) {
300
307
  batchId: parsed.batchId,
301
308
  reason: parsed.reason,
302
309
  hard: parsed.hard,
310
+ dryRun: parsed.dryRun,
303
311
  });
304
312
  return {
305
313
  exitCode: result.exitCode ?? (result.ok ? 0 : 1),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.3.1",
3
+ "version": "2.4.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -191,6 +191,7 @@ Run **after Step A.5 — Clarify** and **before Step B — Slice**. Authoring-on
191
191
  | **Step numbering** | Number steps sequentially starting at 0 with **no duplicates** (`### Step N:`). `spine tasks validate` rejects duplicate step numbers (see issue #148 / SP-435). |
192
192
  | **Two-deliverable test** | If your Steps can be grouped into two clusters with no data dependency between them, split into separate tasks even if the step count is ≤4. The #1 sizing mistake is bundling two independent deliverables in one M task. |
193
193
  | **Parallel waves** | Prefer **≤4** M-sized tasks per wave; 8-task mega-waves stall pi workers (see Phase 15 / SP-086–088). |
194
+ | **False deps** | Edge only for **real data deps** (B needs A's output on disk). Preference-order or "nice to finish first" is **not** a dep — it forces size-1 waves and empty parallel lanes. Independent deliverables → same wave + disjoint File Scope. |
194
195
  | **Scope** | One deliverable per task; disjoint **File Scope** when tasks can run in parallel. |
195
196
  | **IDs** | Use `Next Task ID` from CONTEXT.md; increment after each new task. Greenfield spine projects typically use `SP-###`; Taskplane migrants may keep `TP-###`. |
196
197
  | **Waves** | Order via `## Dependencies` and `{tasksRoot}/dependencies.json`. |
@@ -246,7 +247,7 @@ After creating packets:
246
247
  2. **`{tasksRoot}/dependencies.json`** — add edges for every dependency (machine-parseable)
247
248
  3. Report launch commands: `spine tasks validate pending` (fix contract/PROMPT errors first), `spine tasks analyze pending` (structural checks — wave sizing, deps drift, explore refs), `spine plan pending`, then `spine batch start <id>`
248
249
 
249
- **Example decomposition** (feature brief → three tasks):
250
+ **Example — serial when data deps are real** (handlers import schema; tests call handlers):
250
251
 
251
252
  | Task | Mission | Deps |
252
253
  |------|---------|------|
@@ -254,6 +255,17 @@ After creating packets:
254
255
  | `SP-011-api-handlers` | Implement routes using schema | SP-010 |
255
256
  | `SP-012-api-tests` | Integration tests + docs | SP-011 |
256
257
 
258
+ `spine plan` correctly shows one lane per wave here — serial is required.
259
+
260
+ **Counter-example — parallel when deliverables are independent** (no shared output; disjoint File Scope):
261
+
262
+ | Task | Mission | Deps | File Scope |
263
+ |------|---------|------|------------|
264
+ | `SP-020-skill-dor` | Tighten skill DoR checklist | None | `skills/create-spine-tasks/SKILL.md` |
265
+ | `SP-021-runbook-note` | Add operator recovery note | None | `docs/adoption/operator-runbook.md` |
266
+
267
+ Same wave, no edges → `spine plan` should report **`2 lanes in parallel`**. If it collapses to `1 lane`, check overlapping scopes or accidental deps — do not "fix" with preference-order edges.
268
+
257
269
  ---
258
270
 
259
271
  ## Single-Task Creation Workflow
@@ -461,6 +473,8 @@ Task IDs in JSON use the **folder slug** (full `SP-011-api-handlers`) or bare ID
461
473
 
462
474
  When decomposing a PRD, assign non-overlapping file scopes to tasks that should run in parallel.
463
475
 
476
+ **Shared docs / hot files collapse lanes:** Shared `CONTEXT.md`, `README.md`, area docs, or hot modules (e.g. `bin/spine.mjs`, `src/batch/engine.mjs`) in multiple same-wave File Scopes pack those tasks onto one virtual lane. Keep shared-doc edits **serial** (dependency edge or separate wave) or **out of** parallel mates' scopes — do not list the same shared path on two intended-parallel tasks.
477
+
464
478
  **`fileScopeMustNotChange` (parallel lanes only):** When a packet includes `fileScopeMustNotChange` in `## Contract`, use it only to guard **product paths that concurrent tasks on different lanes** must not edit in the same wave — not to isolate paths touched by **prior serialized tasks** on the same lane. When `spine plan` reports `File scope overlaps (tasks serialized to the same lane)`, those tasks run sequentially on one lane; use disjoint `fileScopeMustChange` paths instead of relying on must-not-change. Full semantics and examples: [references/contract-template.md](references/contract-template.md#filescopemustnotchange-semantics).
465
479
 
466
480
  **Never ban `spine-tasks/**`:** Do **not** list `spine-tasks/**` or the **current task folder** in `fileScopeMustNotChange`. Workers must update `STATUS.md`, create `.DONE`, and may write `.reviews/` — banning those paths causes `contract.verified` failures even when implementation is correct.
@@ -544,6 +558,8 @@ Before reporting launch commands:
544
558
  - [ ] S/M patch Contract uses scoped `node --test` — not `npm test` or `npm test -- path` ([#141](https://github.com/beettlle/pi-spine/issues/141), SP-522)
545
559
  - [ ] Shared-module behavior change: `rg` old strings in `tests/`; all hit files in `testCommand` or documented for post-integrate `release:check` ([post-integrate-regression-gate.md](../spine-release-operator/references/post-integrate-regression-gate.md))
546
560
  - [ ] Plan waves ≤8 tasks when possible — `spine plan` warns when exceeded ([#143](https://github.com/beettlle/pi-spine/issues/143), SP-524)
561
+ - [ ] When parallelism is intended: `spine plan` shows `N lanes in parallel` for that wave — or document why overlapping scopes / real deps forced serial collapse ([#193](https://github.com/beettlle/pi-spine/issues/193))
562
+ - [ ] No false deps: edges only for real data dependencies; preference-order edges that force size-1 waves are rejected ([#193](https://github.com/beettlle/pi-spine/issues/193))
547
563
  - [ ] `### Step N: Testing & Verification` present inside `## Steps` before `## Completion Criteria` (required even for docs-only Review Level 0)
548
564
  - [ ] STATUS.md with matching steps (hydration markers where needed)
549
565
  - [ ] `dependencies.json` updated when task has deps
@@ -575,6 +591,7 @@ Hydration commits (STATUS.md expansions) may happen mid-step for crash recovery.
575
591
  - **Testing step required (never omit)** — every task packet needs `### Step N: Testing & Verification` inside `## Steps`, before `## Completion Criteria`. **Do not skip this for docs-only or Review Level 0 tasks** — the worker rejects packets without a Testing step. Use `testing.test` from spine config; for **code deliverables**, also include `testing.testWithCoverage` and a **≥77% line coverage** checkbox (see prompt template). Docs-only tasks may omit the coverage checkbox.
576
592
  - **Documentation in every task** — "Must Update" / "Check If Affected" prevent doc drift.
577
593
  - **Concrete deliverables** — name files to create/modify; avoid shortcuttable vague steps.
594
+ - **False deps defeat parallelism** — edge only when B needs A's output; independent work gets disjoint File Scope and no edge. Verify intended parallel waves with `spine plan` (`N lanes in parallel`) before handoff ([#193](https://github.com/beettlle/pi-spine/issues/193)).
578
595
  - **Local install** — skill ships with pi-spine; `pi install /path/to/pi-spine -l` loads `./skills`.
579
596
 
580
597
  ---
@@ -84,7 +84,9 @@ For each pending `spine-tasks/{SP-###-slug}/PROMPT.md`:
84
84
 
85
85
  - [ ] `dependencies.json` matches PROMPT `## Dependencies`
86
86
  - [ ] Same-wave tasks have **disjoint** `fileScopeMustChange`
87
- - [ ] Hot shared files are serial (e.g. `src/batch/heartbeat.mjs`, `bin/spine.mjs`)
87
+ - [ ] Hot shared files / shared docs are serial (e.g. `src/batch/heartbeat.mjs`, `bin/spine.mjs`, `CONTEXT.md`) — overlapping shared paths collapse lanes
88
+ - [ ] No false (preference-order) deps that force size-1 waves when deliverables are independent
89
+ - [ ] When parallelism is intended: `spine plan` shows `N lanes in parallel` for that wave — or explain why scopes/deps forced serial collapse
88
90
  - [ ] No directory paths with trailing `/` in contracts — use explicit files
89
91
  - [ ] No parenthetical comments in contract paths (e.g. `file.ts (Step 2 only)`)
90
92
  - [ ] Pre-landed code on `main` → point `fileScopeMustChange` at `spine-tasks/{task}/STATUS.md` + `## Amendments`
@@ -131,12 +131,13 @@ function buildAbortedSnapshot(raw, reason) {
131
131
  * @param {object} ctx
132
132
  * @param {string} ctx.projectRoot
133
133
  * @param {boolean} [ctx.hard]
134
+ * @param {boolean} [ctx.dryRun]
134
135
  * @param {string|null} [ctx.reason]
135
136
  * @param {string|null} [ctx.batchId]
136
137
  * @param {string|null} [ctx.batchStatePath]
137
138
  */
138
139
  export function abortBatch(ctx) {
139
- const { projectRoot, hard = false, reason = null } = ctx;
140
+ const { projectRoot, hard = false, reason = null, dryRun = false } = ctx;
140
141
  const loaded = loadBatchStateFile(projectRoot, ctx.batchStatePath ?? null);
141
142
 
142
143
  if (!loaded.path || !loaded.raw) {
@@ -147,6 +148,7 @@ export function abortBatch(ctx) {
147
148
  suggestedCommand: "spine preflight",
148
149
  alternatives: ["spine status --diagnose"],
149
150
  batchId: null,
151
+ dryRun,
150
152
  };
151
153
  }
152
154
 
@@ -158,6 +160,7 @@ export function abortBatch(ctx) {
158
160
  headline: `Cannot parse batch state: ${loaded.parseError}`,
159
161
  suggestedCommand: "spine status --diagnose",
160
162
  batchId: null,
163
+ dryRun,
161
164
  };
162
165
  }
163
166
 
@@ -170,6 +173,7 @@ export function abortBatch(ctx) {
170
173
  headline: "Active batch state has no batchId",
171
174
  suggestedCommand: "spine status --diagnose",
172
175
  batchId: null,
176
+ dryRun,
173
177
  };
174
178
  }
175
179
 
@@ -181,6 +185,29 @@ export function abortBatch(ctx) {
181
185
  headline: `Batch ID mismatch — active batch is ${batchId}`,
182
186
  suggestedCommand: "spine status --diagnose",
183
187
  batchId,
188
+ dryRun,
189
+ };
190
+ }
191
+
192
+ const previewArchivePath = archiveBatchStatePath(projectRoot, batchId);
193
+
194
+ // Dry-run previews abort without writing archive, journal, signal, or clearing live state.
195
+ if (dryRun) {
196
+ const abortCmd = hard ? "spine batch abort --hard" : "spine batch abort";
197
+ return {
198
+ ok: true,
199
+ exitCode: 0,
200
+ dryRun: true,
201
+ batchId,
202
+ hard,
203
+ reason: reason ?? null,
204
+ diagnosis: "abort_preview",
205
+ archivePath: previewArchivePath,
206
+ headline: hard
207
+ ? `Would hard-abort and archive batch ${batchId}`
208
+ : `Would abort and archive batch ${batchId}`,
209
+ suggestedCommand: abortCmd,
210
+ alternatives: ["spine status --diagnose"],
184
211
  };
185
212
  }
186
213
 
@@ -0,0 +1,400 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Reconstruct batch-state from batch-meta + runtime artifacts (SP-620 / FR-REL240-04 / #126).
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { BATCH_META_FILENAME, batchMetaPath } from "./batch-meta.mjs";
9
+ import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
10
+ import { rebuildBatchStateFromJournal } from "./journal-rebuild.mjs";
11
+ import { computePendingTasks, findResumableWave } from "./resume-validation.mjs";
12
+ import { createInitialBatchState, clearBatchEnginePid, saveSpineBatchState } from "./state.mjs";
13
+ import { loadSpineBatchState } from "./state-io.mjs";
14
+ import { laneTaskBranch, laneWorktreePath } from "./worktree.mjs";
15
+
16
+ /**
17
+ * @param {string} projectRoot
18
+ */
19
+ function runtimeRoot(projectRoot) {
20
+ return path.join(projectRoot, ".spine", "runtime");
21
+ }
22
+
23
+ /**
24
+ * @param {string} projectRoot
25
+ * @param {string} batchId
26
+ */
27
+ function archiveBatchStatePath(projectRoot, batchId) {
28
+ return path.join(runtimeRoot(projectRoot), String(batchId), "archive", "batch-state.json");
29
+ }
30
+
31
+ /**
32
+ * @param {unknown} value
33
+ * @returns {string[][]}
34
+ */
35
+ function normalizeWavePlan(value) {
36
+ if (!Array.isArray(value)) return [];
37
+ return value.map((wave) => (Array.isArray(wave) ? wave.map((id) => String(id)) : []));
38
+ }
39
+
40
+ /**
41
+ * Fail-closed when journal-derived waves disagree with persisted meta topology.
42
+ *
43
+ * @param {string[][]} metaPlan
44
+ * @param {string[][]} journalPlan
45
+ */
46
+ export function wavePlansConflict(metaPlan, journalPlan) {
47
+ const meta = normalizeWavePlan(metaPlan).filter((wave) => wave.length > 0);
48
+ const journal = normalizeWavePlan(journalPlan).filter((wave) => wave.length > 0);
49
+ if (meta.length === 0 || journal.length === 0) return false;
50
+ if (meta.length !== journal.length) return true;
51
+ for (let i = 0; i < meta.length; i++) {
52
+ const a = [...meta[i]].sort();
53
+ const b = [...journal[i]].sort();
54
+ if (a.length !== b.length) return true;
55
+ for (let j = 0; j < a.length; j++) {
56
+ if (a[j] !== b[j]) return true;
57
+ }
58
+ }
59
+ return false;
60
+ }
61
+
62
+ /**
63
+ * @param {string} projectRoot
64
+ * @returns {{ batchId: string, path: string }[]}
65
+ */
66
+ export function listBatchMetaArtifacts(projectRoot) {
67
+ const root = runtimeRoot(projectRoot);
68
+ if (!fs.existsSync(root)) return [];
69
+ /** @type {{ batchId: string, path: string }[]} */
70
+ const found = [];
71
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
72
+ if (!entry.isDirectory()) continue;
73
+ const filePath = path.join(root, entry.name, BATCH_META_FILENAME);
74
+ if (fs.existsSync(filePath)) {
75
+ found.push({ batchId: entry.name, path: filePath });
76
+ }
77
+ }
78
+ return found.sort((a, b) => a.batchId.localeCompare(b.batchId));
79
+ }
80
+
81
+ /**
82
+ * @param {string} projectRoot
83
+ * @param {string} batchId
84
+ * @returns {{ ok: true, meta: object, path: string } | { ok: false, error: string, output: string }}
85
+ */
86
+ export function loadBatchMetaRuntimeArtifact(projectRoot, batchId) {
87
+ const resolvedBatchId = String(batchId ?? "").trim();
88
+ if (!resolvedBatchId) {
89
+ return {
90
+ ok: false,
91
+ error: "batch_meta_missing",
92
+ output:
93
+ "Cannot reconstruct batch state: batchId is required to load batch-meta.json.\n" +
94
+ " → Inspect .spine/runtime/*/batch-meta.json then spine batch resume --force\n",
95
+ };
96
+ }
97
+
98
+ const filePath = batchMetaPath(projectRoot, resolvedBatchId);
99
+ if (!fs.existsSync(filePath)) {
100
+ return {
101
+ ok: false,
102
+ error: "batch_meta_missing",
103
+ output:
104
+ `Cannot reconstruct batch state: missing ${path.relative(projectRoot, filePath)}.\n` +
105
+ " → Force-resume requires surviving batch-meta from batch start (SP-619).\n",
106
+ };
107
+ }
108
+
109
+ try {
110
+ const meta = JSON.parse(fs.readFileSync(filePath, "utf-8"));
111
+ if (!meta || typeof meta !== "object") {
112
+ return {
113
+ ok: false,
114
+ error: "batch_meta_corrupt",
115
+ output: `Cannot reconstruct batch state: corrupt batch-meta at ${filePath}\n`,
116
+ };
117
+ }
118
+ const wavePlan = normalizeWavePlan(meta.wavePlan);
119
+ if (wavePlan.length < 1 || wavePlan.every((wave) => wave.length < 1)) {
120
+ return {
121
+ ok: false,
122
+ error: "batch_meta_ambiguous",
123
+ output:
124
+ `Cannot reconstruct batch state: batch-meta for ${resolvedBatchId} has empty wavePlan.\n` +
125
+ " → Prefer a clear error over guessing the wave topology.\n",
126
+ };
127
+ }
128
+ return {
129
+ ok: true,
130
+ meta: { ...meta, batchId: String(meta.batchId ?? resolvedBatchId), wavePlan },
131
+ path: filePath,
132
+ };
133
+ } catch (err) {
134
+ const message = err instanceof Error ? err.message : String(err);
135
+ return {
136
+ ok: false,
137
+ error: "batch_meta_corrupt",
138
+ output: `Cannot reconstruct batch state: failed to parse batch-meta (${message})\n`,
139
+ };
140
+ }
141
+ }
142
+
143
+ /**
144
+ * @param {string} projectRoot
145
+ * @param {object} meta
146
+ */
147
+ function seedStateFromBatchMeta(projectRoot, meta) {
148
+ const batchId = String(meta.batchId);
149
+ const wavePlan = normalizeWavePlan(meta.wavePlan);
150
+ const taskIds = [...new Set(wavePlan.flat())];
151
+ const tasks = taskIds.map((taskId) => ({
152
+ taskId,
153
+ laneNumber: 1,
154
+ status: "pending",
155
+ taskFolder: null,
156
+ startedAt: null,
157
+ endedAt: null,
158
+ doneFileFound: false,
159
+ exitReason: null,
160
+ }));
161
+ const lanes = [
162
+ {
163
+ laneNumber: 1,
164
+ laneId: "lane-1",
165
+ worktreePath: laneWorktreePath(projectRoot, batchId, 1),
166
+ branch: laneTaskBranch(batchId, 1),
167
+ taskIds: [...taskIds],
168
+ lastHeartbeatAt: null,
169
+ },
170
+ ];
171
+ const state = createInitialBatchState({
172
+ batchId,
173
+ baseBranch: String(meta.baseBranch ?? "main") || "main",
174
+ orchBranch: String(meta.orchBranch ?? "") || `orch/spine-${batchId}`,
175
+ wavePlan,
176
+ tasks,
177
+ lanes,
178
+ });
179
+ state.phase = "failed";
180
+ state.totalWaves = Number(meta.totalWaves ?? wavePlan.length) || wavePlan.length;
181
+ return state;
182
+ }
183
+
184
+ /**
185
+ * @param {string} projectRoot
186
+ * @param {string} batchId
187
+ */
188
+ function loadArchiveSeed(projectRoot, batchId) {
189
+ const archivePath = archiveBatchStatePath(projectRoot, batchId);
190
+ if (!fs.existsSync(archivePath)) return null;
191
+ try {
192
+ const raw = JSON.parse(fs.readFileSync(archivePath, "utf-8"));
193
+ return raw && typeof raw === "object" ? raw : null;
194
+ } catch {
195
+ return null;
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Rebuild usable batch-state from batch-meta + journal/archive artifacts (FR-REL240-04).
201
+ *
202
+ * @param {string} projectRoot
203
+ * @param {{ batchId?: string }} [options]
204
+ */
205
+ export function reconstructBatchStateFromRuntime(projectRoot, options = {}) {
206
+ const requestedBatchId = String(options.batchId ?? "").trim();
207
+ let batchId = requestedBatchId;
208
+
209
+ if (!batchId) {
210
+ const candidates = listBatchMetaArtifacts(projectRoot);
211
+ if (candidates.length < 1) {
212
+ return {
213
+ ok: false,
214
+ exitCode: 1,
215
+ error: "batch_meta_missing",
216
+ output:
217
+ "Cannot reconstruct batch state: no .spine/runtime/*/batch-meta.json found.\n" +
218
+ " → Live batch-state is missing/corrupt and survival meta is absent.\n",
219
+ };
220
+ }
221
+ if (candidates.length > 1) {
222
+ const ids = candidates.map((entry) => entry.batchId).join(", ");
223
+ return {
224
+ ok: false,
225
+ exitCode: 1,
226
+ error: "batch_meta_ambiguous",
227
+ output:
228
+ `Cannot reconstruct batch state: multiple batch-meta artifacts (${ids}).\n` +
229
+ " → Refuse to guess which wave/batch to resume; remove stale runtime dirs or specify the batch.\n",
230
+ };
231
+ }
232
+ batchId = candidates[0].batchId;
233
+ }
234
+
235
+ const loadedMeta = loadBatchMetaRuntimeArtifact(projectRoot, batchId);
236
+ if (!loadedMeta.ok) {
237
+ return { ...loadedMeta, exitCode: 1 };
238
+ }
239
+
240
+ const meta = loadedMeta.meta;
241
+ const archiveSeed = loadArchiveSeed(projectRoot, batchId);
242
+ const metaSeed = seedStateFromBatchMeta(projectRoot, meta);
243
+ const seed =
244
+ archiveSeed && normalizeWavePlan(archiveSeed.wavePlan).length > 0
245
+ ? {
246
+ ...metaSeed,
247
+ ...archiveSeed,
248
+ batchId,
249
+ baseBranch: String(archiveSeed.baseBranch ?? metaSeed.baseBranch),
250
+ orchBranch: String(archiveSeed.orchBranch ?? metaSeed.orchBranch),
251
+ wavePlan:
252
+ normalizeWavePlan(archiveSeed.wavePlan).length > 0
253
+ ? normalizeWavePlan(archiveSeed.wavePlan)
254
+ : metaSeed.wavePlan,
255
+ }
256
+ : metaSeed;
257
+
258
+ if (wavePlansConflict(meta.wavePlan, seed.wavePlan)) {
259
+ return {
260
+ ok: false,
261
+ exitCode: 1,
262
+ error: "batch_meta_wave_conflict",
263
+ output:
264
+ `Cannot reconstruct batch state: archive wavePlan conflicts with batch-meta for ${batchId}.\n` +
265
+ " → Prefer a clear error over silently resuming the wrong wave.\n",
266
+ };
267
+ }
268
+
269
+ const events = readJournalEvents(projectRoot, batchId);
270
+ const rebuilt = rebuildBatchStateFromJournal(seed, events);
271
+
272
+ if (wavePlansConflict(meta.wavePlan, rebuilt.wavePlan)) {
273
+ return {
274
+ ok: false,
275
+ exitCode: 1,
276
+ error: "batch_meta_wave_conflict",
277
+ output:
278
+ `Cannot reconstruct batch state: journal topology conflicts with batch-meta for ${batchId}.\n` +
279
+ " → Prefer a clear error over silently resuming the wrong wave.\n",
280
+ };
281
+ }
282
+
283
+ // Meta is the survival source of truth for wave topology.
284
+ rebuilt.wavePlan = normalizeWavePlan(meta.wavePlan);
285
+ rebuilt.totalWaves = Number(meta.totalWaves ?? rebuilt.wavePlan.length) || rebuilt.wavePlan.length;
286
+ rebuilt.batchId = batchId;
287
+ rebuilt.baseBranch = String(meta.baseBranch || rebuilt.baseBranch || "main");
288
+ rebuilt.orchBranch = String(meta.orchBranch || rebuilt.orchBranch || `orch/spine-${batchId}`);
289
+
290
+ const phase = String(rebuilt.phase ?? "");
291
+ if (phase === "completed") {
292
+ return {
293
+ ok: false,
294
+ exitCode: 1,
295
+ error: "batch_already_completed",
296
+ output:
297
+ `Cannot reconstruct batch ${batchId} for resume: journal indicates completed.\n` +
298
+ " → Use spine batch dismiss / integrate / salvage as appropriate.\n",
299
+ };
300
+ }
301
+ // Force-resume reconstruct must land in a force-resumable phase. Journal rebuild
302
+ // often yields "running" without a live engine; remap so --force can continue.
303
+ if (phase === "aborted" || phase === "planning" || phase === "running") {
304
+ rebuilt.phase = "failed";
305
+ rebuilt.endedAt = null;
306
+ }
307
+
308
+ clearBatchEnginePid(rebuilt);
309
+ const priorResilience =
310
+ rebuilt.resilience && typeof rebuilt.resilience === "object" ? rebuilt.resilience : {};
311
+ rebuilt.resilience = {
312
+ resumeForced: true,
313
+ retryCountByScope: priorResilience.retryCountByScope ?? {},
314
+ lastFailureClass: priorResilience.lastFailureClass ?? null,
315
+ repairHistory: Array.isArray(priorResilience.repairHistory)
316
+ ? priorResilience.repairHistory
317
+ : [],
318
+ ...(priorResilience.forceMergedWaves
319
+ ? { forceMergedWaves: priorResilience.forceMergedWaves }
320
+ : {}),
321
+ };
322
+ rebuilt.currentWaveIndex = findResumableWave(rebuilt, computePendingTasks(rebuilt));
323
+ rebuilt.updatedAt = Date.now();
324
+
325
+ return {
326
+ ok: true,
327
+ exitCode: 0,
328
+ batchId,
329
+ state: rebuilt,
330
+ meta,
331
+ metaPath: loadedMeta.path,
332
+ reconstructedFrom: events.length > 0 ? "batch-meta+journal" : "batch-meta",
333
+ };
334
+ }
335
+
336
+ /**
337
+ * When force-resume sees missing/corrupt live state, reconstruct and persist it.
338
+ *
339
+ * @param {string} projectRoot
340
+ * @param {{ force?: boolean, batchId?: string }} [options]
341
+ */
342
+ export function ensureForceResumeBatchState(projectRoot, options = {}) {
343
+ const force = Boolean(options.force);
344
+ const loaded = loadSpineBatchState(projectRoot);
345
+ if (loaded.raw) {
346
+ return { ok: true, attempted: false, state: loaded.raw, path: loaded.path };
347
+ }
348
+
349
+ if (!force) {
350
+ return {
351
+ ok: false,
352
+ attempted: false,
353
+ exitCode: 1,
354
+ error: "no_active_batch",
355
+ output: "No active pi-spine batch.\n",
356
+ };
357
+ }
358
+
359
+ const reason = loaded.parseError ? "corrupt" : "missing";
360
+ const reconstructed = reconstructBatchStateFromRuntime(projectRoot, {
361
+ batchId: options.batchId,
362
+ });
363
+ if (!reconstructed.ok) {
364
+ return {
365
+ ...reconstructed,
366
+ attempted: true,
367
+ reason,
368
+ };
369
+ }
370
+
371
+ if (!reconstructed.state) {
372
+ return {
373
+ ok: false,
374
+ attempted: true,
375
+ exitCode: 1,
376
+ error: "batch_meta_reconstruct_failed",
377
+ reason,
378
+ output: "Failed to reconstruct batch state from batch-meta.\n",
379
+ };
380
+ }
381
+
382
+ const saved = saveSpineBatchState(projectRoot, reconstructed.state, { bypassWriteGuard: true });
383
+ appendJournalEvent(projectRoot, reconstructed.batchId, "batch.state_reconstructed", {
384
+ reason,
385
+ source: reconstructed.reconstructedFrom ?? "batch-meta",
386
+ resumeForced: true,
387
+ });
388
+ return {
389
+ ok: true,
390
+ attempted: true,
391
+ reason,
392
+ batchId: reconstructed.batchId,
393
+ state: saved,
394
+ path: loadSpineBatchState(projectRoot).path,
395
+ reconstructedFrom: reconstructed.reconstructedFrom,
396
+ output:
397
+ `Reconstructed batch-state for ${reconstructed.batchId} from ${reconstructed.reconstructedFrom} ` +
398
+ `(live state was ${reason}).\n`,
399
+ };
400
+ }