pi-spine 2.2.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 (47) hide show
  1. package/bin/spine-cli/verify.mjs +2 -19
  2. package/package.json +1 -1
  3. package/src/batch/attached-runner-promote.mjs +370 -0
  4. package/src/batch/attached-runner-reconcile.mjs +291 -0
  5. package/src/batch/attached-runner.mjs +24 -645
  6. package/src/batch/batch-guards.mjs +69 -0
  7. package/src/batch/contract-exec.mjs +483 -0
  8. package/src/batch/contract-parse.mjs +243 -0
  9. package/src/batch/contract-verify.mjs +32 -707
  10. package/src/batch/detached-diagnostics.mjs +255 -0
  11. package/src/batch/detached-run.mjs +326 -0
  12. package/src/batch/detached-start.mjs +18 -894
  13. package/src/batch/detached-wait.mjs +346 -0
  14. package/src/batch/engine.mjs +8 -67
  15. package/src/batch/integrate-git.mjs +21 -0
  16. package/src/batch/integrate.mjs +5 -15
  17. package/src/batch/journal-rebuild-structural.mjs +352 -0
  18. package/src/batch/journal-rebuild.mjs +16 -348
  19. package/src/batch/lane-dirty-check-commit.mjs +361 -0
  20. package/src/batch/lane-dirty-check-git.mjs +298 -0
  21. package/src/batch/lane-dirty-check.mjs +31 -297
  22. package/src/batch/reconcile-batch.mjs +483 -0
  23. package/src/batch/reconcile-classify.mjs +433 -0
  24. package/src/batch/reconcile-diagnosis.mjs +459 -0
  25. package/src/batch/reconcile-light-cache.mjs +61 -0
  26. package/src/batch/reconcile-orphan.mjs +198 -0
  27. package/src/batch/reconcile.mjs +19 -1693
  28. package/src/batch/resume-multi-lanes.mjs +6 -148
  29. package/src/batch/resume-multi-queue.mjs +159 -0
  30. package/src/batch/resume-single-validate.mjs +25 -0
  31. package/src/batch/resume.mjs +3 -20
  32. package/src/batch/review-artifacts.mjs +419 -0
  33. package/src/batch/review-step-run.mjs +383 -0
  34. package/src/batch/review-step.mjs +451 -0
  35. package/src/batch/review.mjs +32 -1199
  36. package/src/batch/salvage-batch-list.mjs +291 -0
  37. package/src/batch/salvage-batch.mjs +10 -284
  38. package/src/batch/sequence-plan.mjs +234 -0
  39. package/src/batch/sequence-run.mjs +418 -0
  40. package/src/batch/sequence-wait.mjs +167 -0
  41. package/src/batch/sequence.mjs +22 -783
  42. package/src/batch/state-guards.mjs +284 -0
  43. package/src/batch/state-io.mjs +135 -0
  44. package/src/batch/state.mjs +27 -396
  45. package/src/batch/worker-heartbeat.mjs +375 -0
  46. package/src/batch/worker-host.mjs +50 -541
  47. package/src/batch/worker-spawn.mjs +315 -0
@@ -1,30 +1,39 @@
1
1
  // @ts-nocheck
2
2
  /**
3
- * pi-spine batch-state.json read/write (schema v1, PRD §10.1).
3
+ * pi-spine batch-state.json orchestration (schema v1, PRD §10.1).
4
+ * Re-export shim — I/O in state-io.mjs, guards in state-guards.mjs (SP-587).
4
5
  */
5
6
 
6
- import fs from "node:fs";
7
- import path from "node:path";
8
- import { writeJsonAtomic } from "../fs/atomic-write.mjs";
9
7
  import { appendJournalEvent } from "./journal.mjs";
10
8
  import {
11
9
  clearStaleTerminalBatchStateForStart,
12
10
  loadBatchStateFile,
13
11
  } from "./batch-state-io.mjs";
14
- import { isProcessAlive } from "../process/liveness.mjs";
15
-
16
- export const SPINE_BATCH_STATE_REL = path.join(".spine", "batch-state.json");
17
-
18
- /** @type {ReadonlySet<string>} */
19
- export const ACTIVE_PHASES = new Set(["planning", "running", "paused"]);
20
-
21
- /** @type {ReadonlySet<string>} */
22
- export const TERMINAL_BATCH_PHASES = new Set([
23
- "completed",
24
- "failed",
25
- "aborted",
26
- "merge_blocked",
27
- ]);
12
+ import {
13
+ loadSpineBatchState,
14
+ saveSpineBatchState,
15
+ } from "./state-io.mjs";
16
+ import { ACTIVE_PHASES } from "./state-guards.mjs";
17
+
18
+ export {
19
+ SPINE_BATCH_STATE_REL,
20
+ BATCH_HISTORY_REL,
21
+ spineBatchStatePath,
22
+ loadSpineBatchState,
23
+ saveSpineBatchState,
24
+ batchHistoryPath,
25
+ resolveBatchStateFileForValidation,
26
+ appendBatchHistoryEntry,
27
+ } from "./state-io.mjs";
28
+ export {
29
+ ACTIVE_PHASES,
30
+ TERMINAL_BATCH_PHASES,
31
+ evaluateBatchStateWriteGuard,
32
+ readBatchEnginePid,
33
+ recordBatchEnginePid,
34
+ clearBatchEnginePid,
35
+ validateBatchState,
36
+ } from "./state-guards.mjs";
28
37
 
29
38
  /**
30
39
  * @returns {string} batchId `{YYYYMMDD}T{HHmmss}` UTC
@@ -39,139 +48,6 @@ export function generateBatchId(now = new Date()) {
39
48
  return `${y}${m}${d}T${h}${min}${s}`;
40
49
  }
41
50
 
42
- /**
43
- * @param {string} projectRoot
44
- */
45
- export function spineBatchStatePath(projectRoot) {
46
- return path.join(projectRoot, SPINE_BATCH_STATE_REL);
47
- }
48
-
49
- /**
50
- * @param {string} projectRoot
51
- */
52
- export function loadSpineBatchState(projectRoot) {
53
- const filePath = spineBatchStatePath(projectRoot);
54
- if (!fs.existsSync(filePath)) {
55
- return { path: null, raw: null, parseError: null };
56
- }
57
- try {
58
- const raw = JSON.parse(fs.readFileSync(filePath, "utf-8"));
59
- return { path: filePath, raw, parseError: null };
60
- } catch (err) {
61
- return {
62
- path: filePath,
63
- raw: null,
64
- parseError: err instanceof Error ? err.message : String(err),
65
- };
66
- }
67
- }
68
-
69
- /**
70
- * @param {string} projectRoot
71
- * @param {string} batchId
72
- */
73
- function archivedBatchStatePath(projectRoot, batchId) {
74
- return path.join(projectRoot, ".spine", "runtime", batchId, "archive", "batch-state.json");
75
- }
76
-
77
- /**
78
- * Reject cache writes from non-owner engines or post-archive resurrection (SP-254).
79
- *
80
- * @param {string} projectRoot
81
- * @param {object} state
82
- * @returns {{ allowed: boolean, reason?: string }}
83
- */
84
- export function evaluateBatchStateWriteGuard(projectRoot, state) {
85
- const filePath = spineBatchStatePath(projectRoot);
86
- const batchId = String(state.batchId ?? "");
87
- const incomingPhase = String(state.phase ?? "");
88
-
89
- if (fs.existsSync(filePath)) {
90
- try {
91
- const onDisk = JSON.parse(fs.readFileSync(filePath, "utf-8"));
92
- const onDiskBatchId = String(onDisk.batchId ?? "");
93
- const incomingBatchId = String(state.batchId ?? "");
94
- const onDiskPhase = String(onDisk.phase ?? "");
95
- const ownerPid = readBatchEnginePid(onDisk);
96
- if (
97
- incomingBatchId &&
98
- onDiskBatchId &&
99
- incomingBatchId !== onDiskBatchId &&
100
- TERMINAL_BATCH_PHASES.has(onDiskPhase) &&
101
- (!ownerPid || !isProcessAlive(ownerPid))
102
- ) {
103
- return { allowed: true };
104
- }
105
- if (ownerPid && ownerPid !== process.pid && isProcessAlive(ownerPid)) {
106
- return { allowed: false, reason: "stale_engine_pid" };
107
- }
108
- } catch {
109
- /* corrupt on-disk state — allow overwrite */
110
- }
111
- } else if (batchId && ACTIVE_PHASES.has(incomingPhase)) {
112
- if (fs.existsSync(archivedBatchStatePath(projectRoot, batchId))) {
113
- return { allowed: false, reason: "archived_batch_resurrection" };
114
- }
115
- }
116
-
117
- return { allowed: true };
118
- }
119
-
120
- /**
121
- * @param {string} projectRoot
122
- * @param {object} state
123
- * @param {{ bypassWriteGuard?: boolean }} [options]
124
- */
125
- export function saveSpineBatchState(projectRoot, state, options = {}) {
126
- const guard = options.bypassWriteGuard
127
- ? { allowed: true }
128
- : evaluateBatchStateWriteGuard(projectRoot, state);
129
- if (!guard.allowed) {
130
- const loaded = loadSpineBatchState(projectRoot);
131
- return loaded.raw ?? state;
132
- }
133
-
134
- const filePath = spineBatchStatePath(projectRoot);
135
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
136
- if (TERMINAL_BATCH_PHASES.has(String(state.phase ?? ""))) {
137
- clearBatchEnginePid(state);
138
- }
139
- const next = { ...state, updatedAt: Date.now() };
140
- writeJsonAtomic(filePath, next);
141
- return next;
142
- }
143
-
144
- /**
145
- * @param {unknown} raw
146
- * @returns {number|null}
147
- */
148
- export function readBatchEnginePid(raw) {
149
- if (!raw || typeof raw !== "object") return null;
150
- /** @type {Record<string, unknown>} */
151
- const state = /** @type {Record<string, unknown>} */ (raw);
152
- const resilience =
153
- state.resilience && typeof state.resilience === "object"
154
- ? /** @type {Record<string, unknown>} */ (state.resilience)
155
- : null;
156
- const fromResilience = Number(resilience?.enginePid);
157
- if (Number.isFinite(fromResilience) && fromResilience > 0) return fromResilience;
158
- const topLevel = Number(state.enginePid);
159
- if (Number.isFinite(topLevel) && topLevel > 0) return topLevel;
160
- return null;
161
- }
162
-
163
- /**
164
- * @param {object} state
165
- * @param {number} enginePid
166
- */
167
- export function recordBatchEnginePid(state, enginePid) {
168
- const pid = Number(enginePid);
169
- if (!Number.isFinite(pid) || pid <= 0) return;
170
- state.resilience = state.resilience ?? {};
171
- state.resilience.enginePid = pid;
172
- state.resilience.engineStartedAt = Date.now();
173
- }
174
-
175
51
  /**
176
52
  * Reset lane stall clocks at resume handoff so dashboard does not show pre-resume heartbeats as stale.
177
53
  *
@@ -188,15 +64,6 @@ export function refreshLaneHeartbeatsOnResume(state) {
188
64
  }
189
65
  }
190
66
 
191
- /**
192
- * @param {object} state
193
- */
194
- export function clearBatchEnginePid(state) {
195
- if (!state?.resilience || typeof state.resilience !== "object") return;
196
- delete state.resilience.enginePid;
197
- delete state.resilience.engineStartedAt;
198
- }
199
-
200
67
  /**
201
68
  * Mark running tasks that lost their worker when the engine exits unexpectedly.
202
69
  *
@@ -292,242 +159,6 @@ export function assertNoActiveBatch(projectRoot) {
292
159
  }
293
160
  }
294
161
 
295
- /**
296
- * @param {object} params
297
- */
298
- export const BATCH_HISTORY_REL = path.join(".spine", "batch-history.json");
299
-
300
- /**
301
- * @param {string} projectRoot
302
- */
303
- export function batchHistoryPath(projectRoot) {
304
- return path.join(projectRoot, BATCH_HISTORY_REL);
305
- }
306
-
307
- /**
308
- * @param {unknown} state
309
- * @returns {{ ok: true } | { ok: false, errors: string[], suggestedCommand: string }}
310
- */
311
- export function validateBatchState(state) {
312
- /** @type {string[]} */
313
- const errors = [];
314
-
315
- if (!state || typeof state !== "object" || Array.isArray(state)) {
316
- return {
317
- ok: false,
318
- errors: ["batch state must be a JSON object"],
319
- suggestedCommand: "spine state validate --diagnose",
320
- };
321
- }
322
-
323
- /** @type {Record<string, unknown>} */
324
- const raw = /** @type {Record<string, unknown>} */ (state);
325
-
326
- if (raw.schemaVersion !== 1) {
327
- errors.push(`schemaVersion must be 1 (found ${String(raw.schemaVersion)})`);
328
- }
329
-
330
- const batchId = String(raw.batchId ?? "").trim();
331
- if (!batchId) errors.push("batchId is required");
332
-
333
- const phase = String(raw.phase ?? "").trim();
334
- const validPhases = new Set([
335
- "planning",
336
- "running",
337
- "paused",
338
- "merging",
339
- "completed",
340
- "failed",
341
- "aborted",
342
- "merge_blocked",
343
- ]);
344
- if (!validPhases.has(phase)) {
345
- errors.push(`phase must be one of ${[...validPhases].join(", ")} (found ${phase || "missing"})`);
346
- }
347
-
348
- for (const field of ["baseBranch", "orchBranch", "startedAt", "updatedAt", "totalTasks"]) {
349
- if (raw[field] == null || raw[field] === "") {
350
- errors.push(`${field} is required`);
351
- }
352
- }
353
-
354
- if (!Array.isArray(raw.wavePlan)) errors.push("wavePlan must be an array");
355
- if (!Array.isArray(raw.tasks)) errors.push("tasks must be an array");
356
- if (!Array.isArray(raw.lanes)) errors.push("lanes must be an array");
357
- if (!Array.isArray(raw.mergeResults)) errors.push("mergeResults must be an array");
358
- if (!Array.isArray(raw.segments)) errors.push("segments must be an array");
359
-
360
- const totalTasks = Number(raw.totalTasks ?? 0);
361
- const succeededTasks = Number(raw.succeededTasks ?? 0);
362
- const failedTasks = Number(raw.failedTasks ?? 0);
363
- const skippedTasks = Number(raw.skippedTasks ?? 0);
364
- const blockedTasks = Number(raw.blockedTasks ?? 0);
365
- const taskCount = Array.isArray(raw.tasks) ? raw.tasks.length : 0;
366
-
367
- if (taskCount !== totalTasks) {
368
- errors.push(`tasks.length (${taskCount}) must match totalTasks (${totalTasks})`);
369
- }
370
-
371
- const terminalSum = succeededTasks + failedTasks + skippedTasks + blockedTasks;
372
- if (terminalSum > totalTasks) {
373
- errors.push(
374
- `succeeded+failed+skipped+blocked (${terminalSum}) exceeds totalTasks (${totalTasks})`,
375
- );
376
- }
377
-
378
- const lanes = Array.isArray(raw.lanes) ? raw.lanes : [];
379
- const laneNumbers = new Set(
380
- lanes.map((lane) =>
381
- lane && typeof lane === "object" ? Number(/** @type {{ laneNumber?: number }} */ (lane).laneNumber) : NaN,
382
- ),
383
- );
384
-
385
- for (const task of Array.isArray(raw.tasks) ? raw.tasks : []) {
386
- if (!task || typeof task !== "object") continue;
387
- const taskId = String(/** @type {{ taskId?: string }} */ (task).taskId ?? "").trim();
388
- if (!taskId) errors.push("each task must have taskId");
389
-
390
- const laneNumber = Number(/** @type {{ laneNumber?: number }} */ (task).laneNumber);
391
- if (!Number.isNaN(laneNumber) && laneNumbers.size > 0 && !laneNumbers.has(laneNumber)) {
392
- errors.push(`task ${taskId} references missing lane ${laneNumber}`);
393
- }
394
- }
395
-
396
- for (const lane of lanes) {
397
- if (!lane || typeof lane !== "object") continue;
398
- const laneNumber = Number(/** @type {{ laneNumber?: number }} */ (lane).laneNumber);
399
- const taskIds = Array.isArray(/** @type {{ taskIds?: string[] }} */ (lane).taskIds)
400
- ? /** @type {{ taskIds?: string[] }} */ (lane).taskIds
401
- : [];
402
- for (const taskId of taskIds) {
403
- const found = (raw.tasks ?? []).some(
404
- (task) =>
405
- task &&
406
- typeof task === "object" &&
407
- String(/** @type {{ taskId?: string }} */ (task).taskId) === taskId &&
408
- Number(/** @type {{ laneNumber?: number }} */ (task).laneNumber) === laneNumber,
409
- );
410
- if (!found) {
411
- errors.push(`lane ${laneNumber} lists task ${taskId} not assigned to that lane`);
412
- }
413
- }
414
- }
415
-
416
- const segments = Array.isArray(raw.segments) ? raw.segments : [];
417
- const taskIds = new Set(
418
- (Array.isArray(raw.tasks) ? raw.tasks : [])
419
- .map((task) =>
420
- task && typeof task === "object"
421
- ? String(/** @type {{ taskId?: string }} */ (task).taskId ?? "").trim()
422
- : "",
423
- )
424
- .filter(Boolean),
425
- );
426
- const segmentIds = new Set();
427
-
428
- for (const segment of segments) {
429
- if (!segment || typeof segment !== "object") {
430
- errors.push("each segment must be an object");
431
- continue;
432
- }
433
- const segmentId = String(/** @type {{ segmentId?: string }} */ (segment).segmentId ?? "").trim();
434
- const taskId = String(/** @type {{ taskId?: string }} */ (segment).taskId ?? "").trim();
435
- const status = String(/** @type {{ status?: string }} */ (segment).status ?? "").trim();
436
-
437
- if (!segmentId) errors.push("each segment must have segmentId");
438
- if (!taskId) errors.push("each segment must have taskId");
439
- if (!status) errors.push(`segment ${segmentId || "(missing)"} must have status`);
440
- if (segmentId && segmentIds.has(segmentId)) {
441
- errors.push(`duplicate segmentId ${segmentId}`);
442
- }
443
- if (segmentId) segmentIds.add(segmentId);
444
- if (taskId && !taskIds.has(taskId)) {
445
- errors.push(`segment ${segmentId || taskId} references unknown task ${taskId}`);
446
- }
447
- }
448
-
449
- for (const taskId of taskIds) {
450
- const hasSegment = segments.some(
451
- (segment) =>
452
- segment &&
453
- typeof segment === "object" &&
454
- String(/** @type {{ taskId?: string }} */ (segment).taskId) === taskId,
455
- );
456
- if (!hasSegment) {
457
- errors.push(`task ${taskId} has no matching segment record`);
458
- }
459
- }
460
-
461
- if (errors.length > 0) {
462
- return {
463
- ok: false,
464
- errors,
465
- suggestedCommand: "spine state validate --diagnose",
466
- };
467
- }
468
-
469
- return { ok: true };
470
- }
471
-
472
- /**
473
- * @param {string} projectRoot
474
- * @param {string|null} [batchId]
475
- */
476
- export function resolveBatchStateFileForValidation(projectRoot, batchId = null) {
477
- if (batchId) {
478
- const archived = path.join(
479
- projectRoot,
480
- ".spine",
481
- "runtime",
482
- batchId,
483
- "archive",
484
- "batch-state.json",
485
- );
486
- if (fs.existsSync(archived)) {
487
- return { path: archived, source: "archive" };
488
- }
489
- }
490
-
491
- const active = spineBatchStatePath(projectRoot);
492
- if (fs.existsSync(active)) {
493
- const loaded = loadSpineBatchState(projectRoot);
494
- if (batchId && loaded.raw && String(loaded.raw.batchId) !== batchId) {
495
- return { path: null, source: null, error: `Active batch is ${loaded.raw.batchId}, not ${batchId}` };
496
- }
497
- return { path: active, source: "active" };
498
- }
499
-
500
- if (batchId) {
501
- return { path: null, source: null, error: `No batch-state found for batch ${batchId}` };
502
- }
503
-
504
- return { path: null, source: null, error: "No active batch-state.json" };
505
- }
506
-
507
- /**
508
- * @param {string} projectRoot
509
- * @param {object} entry
510
- */
511
- export function appendBatchHistoryEntry(projectRoot, entry) {
512
- const filePath = batchHistoryPath(projectRoot);
513
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
514
-
515
- /** @type {object[]} */
516
- let history = [];
517
- if (fs.existsSync(filePath)) {
518
- try {
519
- const parsed = JSON.parse(fs.readFileSync(filePath, "utf-8"));
520
- if (Array.isArray(parsed)) history = parsed;
521
- } catch {
522
- history = [];
523
- }
524
- }
525
-
526
- history.push(entry);
527
- fs.writeFileSync(filePath, `${JSON.stringify(history, null, 2)}\n`, "utf-8");
528
- return filePath;
529
- }
530
-
531
162
  /**
532
163
  * @param {string} taskId
533
164
  */