pi-spine 2.1.0 → 2.3.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 (49) hide show
  1. package/bin/spine-batch.mjs +74 -5
  2. package/bin/spine-cli/verify.mjs +2 -18
  3. package/package.json +1 -1
  4. package/src/batch/attached-runner-promote.mjs +370 -0
  5. package/src/batch/attached-runner-reconcile.mjs +291 -0
  6. package/src/batch/attached-runner.mjs +24 -634
  7. package/src/batch/batch-guards.mjs +69 -0
  8. package/src/batch/contract-exec.mjs +483 -0
  9. package/src/batch/contract-parse.mjs +243 -0
  10. package/src/batch/contract-verify.mjs +32 -707
  11. package/src/batch/detached-diagnostics.mjs +255 -0
  12. package/src/batch/detached-run.mjs +326 -0
  13. package/src/batch/detached-start.mjs +18 -894
  14. package/src/batch/detached-wait.mjs +346 -0
  15. package/src/batch/engine-lanes/merge.mjs +25 -0
  16. package/src/batch/engine.mjs +8 -67
  17. package/src/batch/integrate-git.mjs +21 -0
  18. package/src/batch/integrate.mjs +5 -15
  19. package/src/batch/journal-rebuild-structural.mjs +352 -0
  20. package/src/batch/journal-rebuild.mjs +94 -347
  21. package/src/batch/lane-dirty-check-commit.mjs +361 -0
  22. package/src/batch/lane-dirty-check-git.mjs +298 -0
  23. package/src/batch/lane-dirty-check.mjs +31 -297
  24. package/src/batch/reconcile-batch.mjs +483 -0
  25. package/src/batch/reconcile-classify.mjs +433 -0
  26. package/src/batch/reconcile-diagnosis.mjs +459 -0
  27. package/src/batch/reconcile-light-cache.mjs +61 -0
  28. package/src/batch/reconcile-orphan.mjs +198 -0
  29. package/src/batch/reconcile.mjs +19 -1693
  30. package/src/batch/resume-multi-lanes.mjs +44 -149
  31. package/src/batch/resume-multi-queue.mjs +159 -0
  32. package/src/batch/resume-single-validate.mjs +25 -0
  33. package/src/batch/resume.mjs +3 -20
  34. package/src/batch/review-artifacts.mjs +419 -0
  35. package/src/batch/review-step-run.mjs +383 -0
  36. package/src/batch/review-step.mjs +451 -0
  37. package/src/batch/review.mjs +32 -1199
  38. package/src/batch/salvage-batch-list.mjs +291 -0
  39. package/src/batch/salvage-batch.mjs +417 -0
  40. package/src/batch/sequence-plan.mjs +234 -0
  41. package/src/batch/sequence-run.mjs +418 -0
  42. package/src/batch/sequence-wait.mjs +167 -0
  43. package/src/batch/sequence.mjs +22 -783
  44. package/src/batch/state-guards.mjs +284 -0
  45. package/src/batch/state-io.mjs +135 -0
  46. package/src/batch/state.mjs +27 -396
  47. package/src/batch/worker-heartbeat.mjs +375 -0
  48. package/src/batch/worker-host.mjs +50 -541
  49. package/src/batch/worker-spawn.mjs +315 -0
@@ -0,0 +1,284 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Batch-state write guards, engine PID tracking, and schema validation (SP-587 / FR-SHIP-02).
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { isProcessAlive } from "../process/liveness.mjs";
9
+
10
+ /** @type {ReadonlySet<string>} */
11
+ export const ACTIVE_PHASES = new Set(["planning", "running", "paused"]);
12
+
13
+ /** @type {ReadonlySet<string>} */
14
+ export const TERMINAL_BATCH_PHASES = new Set([
15
+ "completed",
16
+ "failed",
17
+ "aborted",
18
+ "merge_blocked",
19
+ ]);
20
+
21
+ const SPINE_BATCH_STATE_REL = path.join(".spine", "batch-state.json");
22
+
23
+ /**
24
+ * @param {string} projectRoot
25
+ */
26
+ function spineBatchStatePath(projectRoot) {
27
+ return path.join(projectRoot, SPINE_BATCH_STATE_REL);
28
+ }
29
+
30
+ /**
31
+ * @param {string} projectRoot
32
+ * @param {string} batchId
33
+ */
34
+ function archivedBatchStatePath(projectRoot, batchId) {
35
+ return path.join(projectRoot, ".spine", "runtime", batchId, "archive", "batch-state.json");
36
+ }
37
+
38
+ /**
39
+ * Reject cache writes from non-owner engines or post-archive resurrection (SP-254).
40
+ *
41
+ * @param {string} projectRoot
42
+ * @param {object} state
43
+ * @returns {{ allowed: boolean, reason?: string }}
44
+ */
45
+ export function evaluateBatchStateWriteGuard(projectRoot, state) {
46
+ const filePath = spineBatchStatePath(projectRoot);
47
+ const batchId = String(state.batchId ?? "");
48
+ const incomingPhase = String(state.phase ?? "");
49
+
50
+ if (fs.existsSync(filePath)) {
51
+ try {
52
+ const onDisk = JSON.parse(fs.readFileSync(filePath, "utf-8"));
53
+ const onDiskBatchId = String(onDisk.batchId ?? "");
54
+ const incomingBatchId = String(state.batchId ?? "");
55
+ const onDiskPhase = String(onDisk.phase ?? "");
56
+ const ownerPid = readBatchEnginePid(onDisk);
57
+ if (
58
+ incomingBatchId &&
59
+ onDiskBatchId &&
60
+ incomingBatchId !== onDiskBatchId &&
61
+ TERMINAL_BATCH_PHASES.has(onDiskPhase) &&
62
+ (!ownerPid || !isProcessAlive(ownerPid))
63
+ ) {
64
+ return { allowed: true };
65
+ }
66
+ if (ownerPid && ownerPid !== process.pid && isProcessAlive(ownerPid)) {
67
+ return { allowed: false, reason: "stale_engine_pid" };
68
+ }
69
+ } catch {
70
+ /* corrupt on-disk state — allow overwrite */
71
+ }
72
+ } else if (batchId && ACTIVE_PHASES.has(incomingPhase)) {
73
+ if (fs.existsSync(archivedBatchStatePath(projectRoot, batchId))) {
74
+ return { allowed: false, reason: "archived_batch_resurrection" };
75
+ }
76
+ }
77
+
78
+ return { allowed: true };
79
+ }
80
+
81
+ /**
82
+ * @param {unknown} raw
83
+ * @returns {number|null}
84
+ */
85
+ export function readBatchEnginePid(raw) {
86
+ if (!raw || typeof raw !== "object") return null;
87
+ /** @type {Record<string, unknown>} */
88
+ const state = /** @type {Record<string, unknown>} */ (raw);
89
+ const resilience =
90
+ state.resilience && typeof state.resilience === "object"
91
+ ? /** @type {Record<string, unknown>} */ (state.resilience)
92
+ : null;
93
+ const fromResilience = Number(resilience?.enginePid);
94
+ if (Number.isFinite(fromResilience) && fromResilience > 0) return fromResilience;
95
+ const topLevel = Number(state.enginePid);
96
+ if (Number.isFinite(topLevel) && topLevel > 0) return topLevel;
97
+ return null;
98
+ }
99
+
100
+ /**
101
+ * @param {object} state
102
+ * @param {number} enginePid
103
+ */
104
+ export function recordBatchEnginePid(state, enginePid) {
105
+ const pid = Number(enginePid);
106
+ if (!Number.isFinite(pid) || pid <= 0) return;
107
+ state.resilience = state.resilience ?? {};
108
+ state.resilience.enginePid = pid;
109
+ state.resilience.engineStartedAt = Date.now();
110
+ }
111
+
112
+ /**
113
+ * @param {object} state
114
+ */
115
+ export function clearBatchEnginePid(state) {
116
+ if (!state?.resilience || typeof state.resilience !== "object") return;
117
+ delete state.resilience.enginePid;
118
+ delete state.resilience.engineStartedAt;
119
+ }
120
+
121
+ /**
122
+ * @param {unknown} state
123
+ * @returns {{ ok: true } | { ok: false, errors: string[], suggestedCommand: string }}
124
+ */
125
+ export function validateBatchState(state) {
126
+ /** @type {string[]} */
127
+ const errors = [];
128
+
129
+ if (!state || typeof state !== "object" || Array.isArray(state)) {
130
+ return {
131
+ ok: false,
132
+ errors: ["batch state must be a JSON object"],
133
+ suggestedCommand: "spine state validate --diagnose",
134
+ };
135
+ }
136
+
137
+ /** @type {Record<string, unknown>} */
138
+ const raw = /** @type {Record<string, unknown>} */ (state);
139
+
140
+ if (raw.schemaVersion !== 1) {
141
+ errors.push(`schemaVersion must be 1 (found ${String(raw.schemaVersion)})`);
142
+ }
143
+
144
+ const batchId = String(raw.batchId ?? "").trim();
145
+ if (!batchId) errors.push("batchId is required");
146
+
147
+ const phase = String(raw.phase ?? "").trim();
148
+ const validPhases = new Set([
149
+ "planning",
150
+ "running",
151
+ "paused",
152
+ "merging",
153
+ "completed",
154
+ "failed",
155
+ "aborted",
156
+ "merge_blocked",
157
+ ]);
158
+ if (!validPhases.has(phase)) {
159
+ errors.push(`phase must be one of ${[...validPhases].join(", ")} (found ${phase || "missing"})`);
160
+ }
161
+
162
+ for (const field of ["baseBranch", "orchBranch", "startedAt", "updatedAt", "totalTasks"]) {
163
+ if (raw[field] == null || raw[field] === "") {
164
+ errors.push(`${field} is required`);
165
+ }
166
+ }
167
+
168
+ if (!Array.isArray(raw.wavePlan)) errors.push("wavePlan must be an array");
169
+ if (!Array.isArray(raw.tasks)) errors.push("tasks must be an array");
170
+ if (!Array.isArray(raw.lanes)) errors.push("lanes must be an array");
171
+ if (!Array.isArray(raw.mergeResults)) errors.push("mergeResults must be an array");
172
+ if (!Array.isArray(raw.segments)) errors.push("segments must be an array");
173
+
174
+ const totalTasks = Number(raw.totalTasks ?? 0);
175
+ const succeededTasks = Number(raw.succeededTasks ?? 0);
176
+ const failedTasks = Number(raw.failedTasks ?? 0);
177
+ const skippedTasks = Number(raw.skippedTasks ?? 0);
178
+ const blockedTasks = Number(raw.blockedTasks ?? 0);
179
+ const taskCount = Array.isArray(raw.tasks) ? raw.tasks.length : 0;
180
+
181
+ if (taskCount !== totalTasks) {
182
+ errors.push(`tasks.length (${taskCount}) must match totalTasks (${totalTasks})`);
183
+ }
184
+
185
+ const terminalSum = succeededTasks + failedTasks + skippedTasks + blockedTasks;
186
+ if (terminalSum > totalTasks) {
187
+ errors.push(
188
+ `succeeded+failed+skipped+blocked (${terminalSum}) exceeds totalTasks (${totalTasks})`,
189
+ );
190
+ }
191
+
192
+ const lanes = Array.isArray(raw.lanes) ? raw.lanes : [];
193
+ const laneNumbers = new Set(
194
+ lanes.map((lane) =>
195
+ lane && typeof lane === "object" ? Number(/** @type {{ laneNumber?: number }} */ (lane).laneNumber) : NaN,
196
+ ),
197
+ );
198
+
199
+ for (const task of Array.isArray(raw.tasks) ? raw.tasks : []) {
200
+ if (!task || typeof task !== "object") continue;
201
+ const taskId = String(/** @type {{ taskId?: string }} */ (task).taskId ?? "").trim();
202
+ if (!taskId) errors.push("each task must have taskId");
203
+
204
+ const laneNumber = Number(/** @type {{ laneNumber?: number }} */ (task).laneNumber);
205
+ if (!Number.isNaN(laneNumber) && laneNumbers.size > 0 && !laneNumbers.has(laneNumber)) {
206
+ errors.push(`task ${taskId} references missing lane ${laneNumber}`);
207
+ }
208
+ }
209
+
210
+ for (const lane of lanes) {
211
+ if (!lane || typeof lane !== "object") continue;
212
+ const laneNumber = Number(/** @type {{ laneNumber?: number }} */ (lane).laneNumber);
213
+ const taskIds = Array.isArray(/** @type {{ taskIds?: string[] }} */ (lane).taskIds)
214
+ ? /** @type {{ taskIds?: string[] }} */ (lane).taskIds
215
+ : [];
216
+ for (const taskId of taskIds) {
217
+ const found = (raw.tasks ?? []).some(
218
+ (task) =>
219
+ task &&
220
+ typeof task === "object" &&
221
+ String(/** @type {{ taskId?: string }} */ (task).taskId) === taskId &&
222
+ Number(/** @type {{ laneNumber?: number }} */ (task).laneNumber) === laneNumber,
223
+ );
224
+ if (!found) {
225
+ errors.push(`lane ${laneNumber} lists task ${taskId} not assigned to that lane`);
226
+ }
227
+ }
228
+ }
229
+
230
+ const segments = Array.isArray(raw.segments) ? raw.segments : [];
231
+ const taskIds = new Set(
232
+ (Array.isArray(raw.tasks) ? raw.tasks : [])
233
+ .map((task) =>
234
+ task && typeof task === "object"
235
+ ? String(/** @type {{ taskId?: string }} */ (task).taskId ?? "").trim()
236
+ : "",
237
+ )
238
+ .filter(Boolean),
239
+ );
240
+ const segmentIds = new Set();
241
+
242
+ for (const segment of segments) {
243
+ if (!segment || typeof segment !== "object") {
244
+ errors.push("each segment must be an object");
245
+ continue;
246
+ }
247
+ const segmentId = String(/** @type {{ segmentId?: string }} */ (segment).segmentId ?? "").trim();
248
+ const taskId = String(/** @type {{ taskId?: string }} */ (segment).taskId ?? "").trim();
249
+ const status = String(/** @type {{ status?: string }} */ (segment).status ?? "").trim();
250
+
251
+ if (!segmentId) errors.push("each segment must have segmentId");
252
+ if (!taskId) errors.push("each segment must have taskId");
253
+ if (!status) errors.push(`segment ${segmentId || "(missing)"} must have status`);
254
+ if (segmentId && segmentIds.has(segmentId)) {
255
+ errors.push(`duplicate segmentId ${segmentId}`);
256
+ }
257
+ if (segmentId) segmentIds.add(segmentId);
258
+ if (taskId && !taskIds.has(taskId)) {
259
+ errors.push(`segment ${segmentId || taskId} references unknown task ${taskId}`);
260
+ }
261
+ }
262
+
263
+ for (const taskId of taskIds) {
264
+ const hasSegment = segments.some(
265
+ (segment) =>
266
+ segment &&
267
+ typeof segment === "object" &&
268
+ String(/** @type {{ taskId?: string }} */ (segment).taskId) === taskId,
269
+ );
270
+ if (!hasSegment) {
271
+ errors.push(`task ${taskId} has no matching segment record`);
272
+ }
273
+ }
274
+
275
+ if (errors.length > 0) {
276
+ return {
277
+ ok: false,
278
+ errors,
279
+ suggestedCommand: "spine state validate --diagnose",
280
+ };
281
+ }
282
+
283
+ return { ok: true };
284
+ }
@@ -0,0 +1,135 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Batch-state read/write/archive I/O (SP-587 / FR-SHIP-02).
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { writeJsonAtomic } from "../fs/atomic-write.mjs";
9
+ import {
10
+ clearBatchEnginePid,
11
+ evaluateBatchStateWriteGuard,
12
+ TERMINAL_BATCH_PHASES,
13
+ } from "./state-guards.mjs";
14
+
15
+ export const SPINE_BATCH_STATE_REL = path.join(".spine", "batch-state.json");
16
+
17
+ export const BATCH_HISTORY_REL = path.join(".spine", "batch-history.json");
18
+
19
+ /**
20
+ * @param {string} projectRoot
21
+ */
22
+ export function spineBatchStatePath(projectRoot) {
23
+ return path.join(projectRoot, SPINE_BATCH_STATE_REL);
24
+ }
25
+
26
+ /**
27
+ * @param {string} projectRoot
28
+ */
29
+ export function loadSpineBatchState(projectRoot) {
30
+ const filePath = spineBatchStatePath(projectRoot);
31
+ if (!fs.existsSync(filePath)) {
32
+ return { path: null, raw: null, parseError: null };
33
+ }
34
+ try {
35
+ const raw = JSON.parse(fs.readFileSync(filePath, "utf-8"));
36
+ return { path: filePath, raw, parseError: null };
37
+ } catch (err) {
38
+ return {
39
+ path: filePath,
40
+ raw: null,
41
+ parseError: err instanceof Error ? err.message : String(err),
42
+ };
43
+ }
44
+ }
45
+
46
+ /**
47
+ * @param {string} projectRoot
48
+ * @param {string} batchId
49
+ */
50
+ function archivedBatchStatePath(projectRoot, batchId) {
51
+ return path.join(projectRoot, ".spine", "runtime", batchId, "archive", "batch-state.json");
52
+ }
53
+
54
+ /**
55
+ * @param {string} projectRoot
56
+ * @param {object} state
57
+ * @param {{ bypassWriteGuard?: boolean }} [options]
58
+ */
59
+ export function saveSpineBatchState(projectRoot, state, options = {}) {
60
+ const guard = options.bypassWriteGuard
61
+ ? { allowed: true }
62
+ : evaluateBatchStateWriteGuard(projectRoot, state);
63
+ if (!guard.allowed) {
64
+ const loaded = loadSpineBatchState(projectRoot);
65
+ return loaded.raw ?? state;
66
+ }
67
+
68
+ const filePath = spineBatchStatePath(projectRoot);
69
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
70
+ if (TERMINAL_BATCH_PHASES.has(String(state.phase ?? ""))) {
71
+ clearBatchEnginePid(state);
72
+ }
73
+ const next = { ...state, updatedAt: Date.now() };
74
+ writeJsonAtomic(filePath, next);
75
+ return next;
76
+ }
77
+
78
+ /**
79
+ * @param {string} projectRoot
80
+ */
81
+ export function batchHistoryPath(projectRoot) {
82
+ return path.join(projectRoot, BATCH_HISTORY_REL);
83
+ }
84
+
85
+ /**
86
+ * @param {string} projectRoot
87
+ * @param {string|null} [batchId]
88
+ */
89
+ export function resolveBatchStateFileForValidation(projectRoot, batchId = null) {
90
+ if (batchId) {
91
+ const archived = archivedBatchStatePath(projectRoot, batchId);
92
+ if (fs.existsSync(archived)) {
93
+ return { path: archived, source: "archive" };
94
+ }
95
+ }
96
+
97
+ const active = spineBatchStatePath(projectRoot);
98
+ if (fs.existsSync(active)) {
99
+ const loaded = loadSpineBatchState(projectRoot);
100
+ if (batchId && loaded.raw && String(loaded.raw.batchId) !== batchId) {
101
+ return { path: null, source: null, error: `Active batch is ${loaded.raw.batchId}, not ${batchId}` };
102
+ }
103
+ return { path: active, source: "active" };
104
+ }
105
+
106
+ if (batchId) {
107
+ return { path: null, source: null, error: `No batch-state found for batch ${batchId}` };
108
+ }
109
+
110
+ return { path: null, source: null, error: "No active batch-state.json" };
111
+ }
112
+
113
+ /**
114
+ * @param {string} projectRoot
115
+ * @param {object} entry
116
+ */
117
+ export function appendBatchHistoryEntry(projectRoot, entry) {
118
+ const filePath = batchHistoryPath(projectRoot);
119
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
120
+
121
+ /** @type {object[]} */
122
+ let history = [];
123
+ if (fs.existsSync(filePath)) {
124
+ try {
125
+ const parsed = JSON.parse(fs.readFileSync(filePath, "utf-8"));
126
+ if (Array.isArray(parsed)) history = parsed;
127
+ } catch {
128
+ history = [];
129
+ }
130
+ }
131
+
132
+ history.push(entry);
133
+ fs.writeFileSync(filePath, `${JSON.stringify(history, null, 2)}\n`, "utf-8");
134
+ return filePath;
135
+ }