pi-spine 2.2.0 → 2.3.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 (56) hide show
  1. package/bin/spine-cli/verify.mjs +15 -46
  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/diagnosis.mjs +35 -4
  15. package/src/batch/engine-lanes/orch-sync.mjs +126 -0
  16. package/src/batch/engine-lanes.mjs +69 -0
  17. package/src/batch/engine.mjs +8 -67
  18. package/src/batch/integrate-git.mjs +21 -0
  19. package/src/batch/integrate.mjs +5 -15
  20. package/src/batch/journal-rebuild-structural.mjs +352 -0
  21. package/src/batch/journal-rebuild.mjs +16 -348
  22. package/src/batch/lane-dirty-check-commit.mjs +361 -0
  23. package/src/batch/lane-dirty-check-git.mjs +298 -0
  24. package/src/batch/lane-dirty-check.mjs +31 -297
  25. package/src/batch/reconcile-batch.mjs +495 -0
  26. package/src/batch/reconcile-classify.mjs +433 -0
  27. package/src/batch/reconcile-diagnosis.mjs +459 -0
  28. package/src/batch/reconcile-light-cache.mjs +61 -0
  29. package/src/batch/reconcile-orphan.mjs +198 -0
  30. package/src/batch/reconcile.mjs +19 -1693
  31. package/src/batch/resume-multi-lanes.mjs +6 -148
  32. package/src/batch/resume-multi-queue.mjs +159 -0
  33. package/src/batch/resume-single-validate.mjs +25 -0
  34. package/src/batch/resume.mjs +3 -20
  35. package/src/batch/review-artifacts.mjs +419 -0
  36. package/src/batch/review-step-run.mjs +383 -0
  37. package/src/batch/review-step.mjs +451 -0
  38. package/src/batch/review.mjs +32 -1199
  39. package/src/batch/salvage-batch-list.mjs +291 -0
  40. package/src/batch/salvage-batch.mjs +10 -284
  41. package/src/batch/sequence-plan.mjs +234 -0
  42. package/src/batch/sequence-run.mjs +418 -0
  43. package/src/batch/sequence-wait.mjs +167 -0
  44. package/src/batch/sequence.mjs +22 -783
  45. package/src/batch/state-guards.mjs +284 -0
  46. package/src/batch/state-io.mjs +135 -0
  47. package/src/batch/state.mjs +27 -396
  48. package/src/batch/worker-heartbeat.mjs +382 -0
  49. package/src/batch/worker-host.mjs +56 -548
  50. package/src/batch/worker-spawn.mjs +326 -0
  51. package/src/batch/worktree.mjs +68 -0
  52. package/src/config/preflight/integrate-plan.mjs +6 -1
  53. package/src/config/preflight/loc-capstone.mjs +274 -0
  54. package/src/config/spine-preflight-lib.mjs +14 -0
  55. package/src/planner/index.mjs +14 -3
  56. package/src/process/terminate-tree.mjs +154 -0
@@ -8,49 +8,20 @@ import { spawnSync } from "node:child_process";
8
8
  import { fileURLToPath } from "node:url";
9
9
 
10
10
  import { c, FAIL, OK } from "./shared.mjs";
11
+ import {
12
+ BATCH_MODULE_LOC_LIMIT,
13
+ evaluateBatchLocPolicy,
14
+ listBatchModuleLineCounts,
15
+ } from "../../src/config/preflight/loc-capstone.mjs";
11
16
 
12
17
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
13
18
 
14
- /** Modules >500 LOC grandfathered until v2.3 split (FR-SHIP-02 partial — engine-lanes split done). */
15
- export const PHASE23_GRANDFATHERED_OVER_500 = [
16
- "src/batch/engine.mjs",
17
- "src/batch/integrate.mjs",
18
- "src/batch/state.mjs",
19
- "src/batch/worker-host.mjs",
20
- "src/batch/reconcile.mjs",
21
- "src/batch/detached-start.mjs",
22
- "src/batch/review.mjs",
23
- "src/batch/resume-multi-lanes.mjs",
24
- "src/batch/resume.mjs",
25
- "src/batch/sequence.mjs",
26
- "src/batch/contract-verify.mjs",
27
- "src/batch/journal-rebuild.mjs",
28
- "src/batch/lane-dirty-check.mjs",
29
- "src/batch/attached-runner.mjs",
30
- "src/batch/lifecycle.mjs",
31
- "src/batch/salvage-batch.mjs",
32
- ];
19
+ /** Modules >500 LOC grandfathered until v2.3 split — emptied after SP-578–592 (issue #117). */
20
+ export const PHASE23_GRANDFATHERED_OVER_500 = [];
33
21
 
34
22
  const PHASE23_ENGINE_LANES_MAX = 500;
35
23
 
36
- /**
37
- * @param {string} projectRoot
38
- */
39
- function listBatchModuleLineCounts(projectRoot) {
40
- const batchDir = path.join(projectRoot, "src/batch");
41
- if (!fs.existsSync(batchDir)) return [];
42
-
43
- return fs
44
- .readdirSync(batchDir)
45
- .filter((name) => name.endsWith(".mjs"))
46
- .map((name) => {
47
- const relPath = path.posix.join("src/batch", name);
48
- const absPath = path.join(batchDir, name);
49
- const lines = fs.readFileSync(absPath, "utf-8").split(/\r?\n/).length;
50
- return { relPath, lines };
51
- })
52
- .sort((left, right) => left.relPath.localeCompare(right.relPath));
53
- }
24
+ export { listBatchModuleLineCounts, evaluateBatchLocPolicy, BATCH_MODULE_LOC_LIMIT };
54
25
 
55
26
  /**
56
27
  * @param {object} params
@@ -111,17 +82,15 @@ export function runPhase23ExitVerify({ projectRoot, skipTest = false }) {
111
82
  : `engine-lanes.mjs exceeds ${PHASE23_ENGINE_LANES_MAX} LOC (${engineLanes?.lines ?? "missing"})`,
112
83
  });
113
84
 
114
- const over500 = modules.filter((entry) => entry.lines > 500);
115
- const ungrandfathered = over500.filter(
116
- (entry) => !PHASE23_GRANDFATHERED_OVER_500.includes(entry.relPath),
117
- );
118
- const locPolicyOk = ungrandfathered.length === 0;
85
+ const locPolicy = evaluateBatchLocPolicy(projectRoot, {
86
+ grandfathered: PHASE23_GRANDFATHERED_OVER_500,
87
+ });
119
88
  checks.push({
120
89
  id: "batch-loc-policy",
121
- ok: locPolicyOk,
122
- message: locPolicyOk
123
- ? `batch module LOC policy ok (${over500.length} grandfathered >500)`
124
- : `unexpected >500 LOC modules: ${ungrandfathered.map((entry) => `${entry.relPath} (${entry.lines})`).join(", ")}`,
90
+ ok: locPolicy.ok,
91
+ message: locPolicy.ok
92
+ ? `batch module LOC policy ok (${locPolicy.overLimit.length} grandfathered >${BATCH_MODULE_LOC_LIMIT})`
93
+ : `unexpected >${BATCH_MODULE_LOC_LIMIT} LOC modules: ${locPolicy.ungrandfathered.map((entry) => `${entry.relPath} (${entry.lines})`).join(", ")}`,
125
94
  });
126
95
 
127
96
  const realPiWorkflow = path.join(projectRoot, ".github/workflows/real-pi.yml");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.2.0",
3
+ "version": "2.3.1",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -0,0 +1,370 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Attached batch promote/exit paths — milestones, land-loop CLI, post-merge limbo (SP-586).
4
+ * Pause/resume reconcile lives in attached-runner-reconcile.mjs (SP-604).
5
+ */
6
+
7
+ import {
8
+ finalizeAttachedLandLoopBeforeExit,
9
+ finalizeResumedBatchForIntegrate,
10
+ isPostMergeLimbo,
11
+ } from "./post-merge-limbo.mjs";
12
+ import { detectPostMergeLimboForResume } from "./resume-multi-validate.mjs";
13
+ import { terminateStaleDetachedEngine } from "./resume-engine.mjs";
14
+ import { reconcileBatch } from "./reconcile.mjs";
15
+ import { readJournalEventsCached } from "./journal.mjs";
16
+ import { enforceOperatorPauseOnDisk } from "./pause.mjs";
17
+ import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
18
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
19
+ import { resolveAttachedMilestonePollMs } from "../config/spine-config-schema.mjs";
20
+ import { startParentSessionMonitor } from "./parent-session-monitor.mjs";
21
+ import {
22
+ enforceAttachedEngineSingleOwner,
23
+ reconcilePausedResumeDoneInLane,
24
+ } from "./attached-runner-reconcile.mjs";
25
+
26
+ export { DEFAULT_ATTACHED_MILESTONE_POLL_MS } from "../config/spine-config-schema.mjs";
27
+
28
+ /** @type {boolean} */
29
+ let attachedExitHandlersInstalled = false;
30
+
31
+ /** Journal types surfaced on attached stdout during the land loop. */
32
+ export const ATTACHED_LAND_LOOP_MILESTONE_TYPES = new Set([
33
+ "batch.started",
34
+ "task.started",
35
+ "task.completed",
36
+ "task.failed",
37
+ "batch.merge_started",
38
+ "batch.merge_completed",
39
+ "batch.merge_blocked",
40
+ "gate.opened",
41
+ "gate.evidence_collecting",
42
+ "gate.evidence_completed",
43
+ "gate.evidence_failed",
44
+ "batch.land_loop_finalized",
45
+ "batch.completed",
46
+ ]);
47
+
48
+ /**
49
+ * Install journal-aware SIGTERM/SIGINT handlers before attached engine exit (SP-378).
50
+ *
51
+ * @param {object} params
52
+ * @param {string} params.projectRoot
53
+ * @param {string} [params.spineBin]
54
+ */
55
+ export function installAttachedExitFinalizeHandlers({ projectRoot, spineBin }) {
56
+ if (attachedExitHandlersInstalled) return;
57
+ attachedExitHandlersInstalled = true;
58
+
59
+ const onShutdown = (signal) => {
60
+ const handoff = finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal });
61
+ if (handoff.handled) {
62
+ process.exit(0);
63
+ }
64
+ };
65
+
66
+ process.once("SIGTERM", () => onShutdown("SIGTERM"));
67
+ process.once("SIGINT", () => onShutdown("SIGINT"));
68
+ }
69
+
70
+ /**
71
+ * @param {number} ms
72
+ */
73
+ function sleep(ms) {
74
+ return new Promise((resolve) => setTimeout(resolve, ms));
75
+ }
76
+
77
+ /**
78
+ * @param {object} event
79
+ */
80
+ function milestoneEventKey(event) {
81
+ if (typeof event.eventId === "string" && event.eventId) {
82
+ return event.eventId;
83
+ }
84
+ const taskId = typeof event.taskId === "string" ? event.taskId : "";
85
+ const timestamp = typeof event.timestamp === "string" ? event.timestamp : String(event.timestamp ?? "");
86
+ return `${event.type ?? "unknown"}:${timestamp}:${taskId}`;
87
+ }
88
+
89
+ /**
90
+ * @param {object} event
91
+ * @returns {string}
92
+ */
93
+ export function formatAttachedMilestoneLine(event) {
94
+ const type = String(event.type ?? "unknown");
95
+ const taskId = typeof event.taskId === "string" && event.taskId ? ` ${event.taskId}` : "";
96
+ const payload =
97
+ event.payload && typeof event.payload === "object" ? /** @type {Record<string, unknown>} */ (event.payload) : {};
98
+ const waveIndex = payload.waveIndex;
99
+ const waveSuffix =
100
+ typeof waveIndex === "number" &&
101
+ (type === "batch.merge_started" || type === "batch.merge_completed" || type === "batch.merge_blocked")
102
+ ? ` wave=${waveIndex}`
103
+ : "";
104
+ return `[spine] ${type}${taskId}${waveSuffix}\n`;
105
+ }
106
+
107
+ /**
108
+ * @param {object} params
109
+ * @param {string} params.projectRoot
110
+ * @param {(line: string) => void} [params.write]
111
+ * @param {number} [params.pollIntervalMs]
112
+ * @returns {Promise<{ stop: () => Promise<void> }>}
113
+ */
114
+ export async function startAttachedMilestoneReporter({
115
+ projectRoot,
116
+ write = (line) => process.stdout.write(line),
117
+ pollIntervalMs,
118
+ }) {
119
+ const configResult = loadSpineConfig(projectRoot);
120
+ const resolvedPollMs =
121
+ pollIntervalMs ??
122
+ resolveAttachedMilestonePollMs({ config: configResult.config ?? {} });
123
+ /** @type {Set<string>} */
124
+ const printed = new Set();
125
+ let batchId = null;
126
+ let stopped = false;
127
+
128
+ const loop = async () => {
129
+ while (!stopped) {
130
+ enforceOperatorPauseOnDisk(projectRoot);
131
+ if (!batchId) {
132
+ const loaded = loadSpineBatchState(projectRoot);
133
+ batchId = loaded.raw?.batchId ? String(loaded.raw.batchId) : null;
134
+ }
135
+ if (batchId) {
136
+ const events = readJournalEventsCached(projectRoot, batchId);
137
+ for (const event of events) {
138
+ const key = milestoneEventKey(event);
139
+ if (printed.has(key)) continue;
140
+ if (!ATTACHED_LAND_LOOP_MILESTONE_TYPES.has(String(event.type ?? ""))) continue;
141
+ printed.add(key);
142
+ write(formatAttachedMilestoneLine(event));
143
+ }
144
+ }
145
+ await sleep(resolvedPollMs);
146
+ }
147
+ };
148
+
149
+ const loopPromise = loop();
150
+
151
+ return {
152
+ stop: async () => {
153
+ stopped = true;
154
+ await loopPromise;
155
+ if (batchId) {
156
+ const events = readJournalEventsCached(projectRoot, batchId);
157
+ for (const event of events) {
158
+ const key = milestoneEventKey(event);
159
+ if (printed.has(key)) continue;
160
+ if (!ATTACHED_LAND_LOOP_MILESTONE_TYPES.has(String(event.type ?? ""))) continue;
161
+ printed.add(key);
162
+ write(formatAttachedMilestoneLine(event));
163
+ }
164
+ }
165
+ },
166
+ };
167
+ }
168
+
169
+ /**
170
+ * Run an attached foreground engine while streaming land-loop journal milestones to stdout.
171
+ *
172
+ * @param {object} params
173
+ * @param {string} params.projectRoot
174
+ * @param {() => Promise<object>} params.runEngine
175
+ * @param {(line: string) => void} [params.write]
176
+ * @param {boolean} [params.force]
177
+ * @param {"start"|"resume"} [params.operation]
178
+ */
179
+ export async function runAttachedBatchEngine({
180
+ projectRoot,
181
+ runEngine,
182
+ write,
183
+ spineBin,
184
+ _force = false,
185
+ operation = "resume",
186
+ }) {
187
+ if (operation === "start") {
188
+ const lock = enforceAttachedEngineSingleOwner({ projectRoot, force: false, operation: "start" });
189
+ if (!lock.ok) {
190
+ return {
191
+ ok: false,
192
+ exitCode: lock.exitCode ?? 1,
193
+ error: lock.error,
194
+ output: lock.output,
195
+ batchId: lock.batchId,
196
+ };
197
+ }
198
+ }
199
+
200
+ installAttachedExitFinalizeHandlers({ projectRoot, spineBin });
201
+ const reporter = await startAttachedMilestoneReporter({ projectRoot, write });
202
+ /** @type {{ stop: () => Promise<void> }} */
203
+ let parentMonitor = { stop: async () => {} };
204
+ if (process.env.SPINE_ALLOW_ATTACHED_HARNESS !== "1") {
205
+ parentMonitor = await startParentSessionMonitor({
206
+ projectRoot,
207
+ onParentDied: () => {
208
+ process.exit(1);
209
+ },
210
+ });
211
+ }
212
+ try {
213
+ const result = await runEngine();
214
+ const handoff = finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal: "exit" });
215
+ if (handoff.handled && handoff.action === "finalized_in_process" && handoff.result) {
216
+ return handoff.result;
217
+ }
218
+ return result;
219
+ } finally {
220
+ await parentMonitor.stop();
221
+ await reporter.stop();
222
+ }
223
+ }
224
+
225
+ /**
226
+ * @param {object} result
227
+ * @param {import("./reconcile.mjs").ReconciliationResult} reconciliation
228
+ */
229
+ function resolveAttachedBatchExitCode(result, reconciliation) {
230
+ if (reconciliation.phase === "merge_blocked") {
231
+ return result.exitCode ?? 1;
232
+ }
233
+ return result.exitCode ?? (result.ok ? 0 : 1);
234
+ }
235
+
236
+ /**
237
+ * @param {object} params
238
+ * @param {string} params.projectRoot
239
+ * @param {"start"|"resume"} params.operation
240
+ * @param {object} params.result
241
+ * @param {boolean} [params.json]
242
+ */
243
+ export function formatAttachedBatchCliResult({ projectRoot, operation, result, json = false }) {
244
+ const loaded = loadSpineBatchState(projectRoot);
245
+ if (loaded.raw?.batchId) {
246
+ reconcilePausedResumeDoneInLane({
247
+ projectRoot,
248
+ state: loaded.raw,
249
+ batchId: String(loaded.raw.batchId),
250
+ });
251
+ }
252
+ const reconciliation = reconcileBatch({ projectRoot });
253
+ const mergeBlocked = reconciliation.phase === "merge_blocked";
254
+
255
+ if (json) {
256
+ return {
257
+ exitCode: resolveAttachedBatchExitCode(result, reconciliation),
258
+ output: `${JSON.stringify({ ...result, reconciliation }, null, 2)}\n`,
259
+ };
260
+ }
261
+
262
+ const operationLabel = operation === "resume" ? "resumed" : "started";
263
+ const headline = result.ok
264
+ ? `Batch ${operationLabel}`
265
+ : mergeBlocked && reconciliation.headline
266
+ ? reconciliation.headline
267
+ : operation === "resume"
268
+ ? "Batch resume failed"
269
+ : "Batch start failed";
270
+
271
+ /** @type {string[]} */
272
+ const lines = ["", headline, ""];
273
+
274
+ if (result.output) {
275
+ lines.push(result.output.trimEnd());
276
+ } else if (result.error && !mergeBlocked) {
277
+ lines.push(String(result.error));
278
+ }
279
+
280
+ if (reconciliation.headline && reconciliation.headline !== headline) {
281
+ lines.push("", reconciliation.headline);
282
+ }
283
+ if (reconciliation.suggestedCommand) {
284
+ lines.push("", ` → ${reconciliation.suggestedCommand}`);
285
+ }
286
+ if (reconciliation.alternatives?.length) {
287
+ lines.push("", " Alternatives:");
288
+ for (const alt of reconciliation.alternatives) {
289
+ lines.push(` • ${alt}`);
290
+ }
291
+ }
292
+
293
+ if (result.batchId) {
294
+ lines.push("", ` Batch: ${result.batchId}`);
295
+ }
296
+ if (result.taskId) {
297
+ lines.push(` Task: ${result.taskId}`);
298
+ }
299
+
300
+ lines.push("");
301
+ return {
302
+ exitCode: resolveAttachedBatchExitCode(result, reconciliation),
303
+ output: lines.join("\n"),
304
+ };
305
+ }
306
+
307
+ /**
308
+ * Write attached CLI output and exit so the foreground process does not linger after batch.completed.
309
+ *
310
+ * @param {{ exitCode?: number, output?: string }} cli
311
+ * @param {object} [options]
312
+ * @param {boolean} [options.deferExit]
313
+ */
314
+ export function finishAttachedBatchCli(cli, { deferExit = false, projectRoot, spineBin } = {}) {
315
+ const exitCode = cli.exitCode ?? 1;
316
+ if (cli.output) {
317
+ process.stdout.write(cli.output);
318
+ }
319
+ if (deferExit) {
320
+ return;
321
+ }
322
+ if (projectRoot) {
323
+ finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal: "cli_exit" });
324
+ }
325
+ process.exit(exitCode);
326
+ }
327
+
328
+ /**
329
+ * Finalize post-merge limbo during resume without re-running workers.
330
+ *
331
+ * @param {object} params
332
+ * @param {string} params.projectRoot
333
+ * @param {object} params.state
334
+ * @param {string} params.batchId
335
+ * @param {string} params.orchBranch
336
+ * @param {string} [params.fromPhase]
337
+ * @param {boolean} [params.resumeForced]
338
+ * @returns {ReturnType<typeof finalizeResumedBatchForIntegrate>|null}
339
+ */
340
+ export function finalizeResumePostMergeLimbo({
341
+ projectRoot,
342
+ state,
343
+ batchId,
344
+ orchBranch,
345
+ fromPhase = "running",
346
+ resumeForced = false,
347
+ }) {
348
+ if (String(state.phase ?? "") === "completed") {
349
+ return null;
350
+ }
351
+ if (!detectPostMergeLimboForResume({ projectRoot, state }) && !isPostMergeLimbo(state)) {
352
+ return null;
353
+ }
354
+
355
+ terminateStaleDetachedEngine({
356
+ projectRoot,
357
+ state,
358
+ batchId,
359
+ fromPhase,
360
+ });
361
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
362
+
363
+ return finalizeResumedBatchForIntegrate({
364
+ projectRoot,
365
+ state,
366
+ batchId,
367
+ orchBranch,
368
+ resumeForced,
369
+ });
370
+ }