pi-spine 2.4.0 → 2.6.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 (38) hide show
  1. package/bin/spine.mjs +22 -0
  2. package/package.json +1 -1
  3. package/src/batch/attached-runner-promote.mjs +95 -11
  4. package/src/batch/blocker-codes.mjs +63 -0
  5. package/src/batch/diagnosis-alternatives.mjs +18 -0
  6. package/src/batch/diagnosis-gate-ready.mjs +23 -0
  7. package/src/batch/diagnosis-pending-lane.mjs +63 -0
  8. package/src/batch/diagnosis-retry-command.mjs +23 -0
  9. package/src/batch/diagnosis-tail-state.mjs +68 -0
  10. package/src/batch/diagnosis.mjs +69 -52
  11. package/src/batch/engine-lanes/commit.mjs +2 -0
  12. package/src/batch/engine-lanes.mjs +2 -3
  13. package/src/batch/evidence-command.mjs +125 -4
  14. package/src/batch/gate-posture-approve.mjs +345 -0
  15. package/src/batch/gate-posture-defaults.mjs +64 -0
  16. package/src/batch/gate-posture-evaluate.mjs +133 -0
  17. package/src/batch/gate-posture-streak.mjs +290 -0
  18. package/src/batch/gate-revision.mjs +95 -0
  19. package/src/batch/gate.mjs +89 -117
  20. package/src/batch/integrate.mjs +1 -0
  21. package/src/batch/lane-commit.mjs +77 -8
  22. package/src/batch/lifecycle-archive.mjs +71 -0
  23. package/src/batch/lifecycle.mjs +27 -67
  24. package/src/batch/orphan-detect.mjs +68 -5
  25. package/src/batch/post-merge-limbo.mjs +137 -22
  26. package/src/batch/reconcile-batch.mjs +40 -43
  27. package/src/batch/reconcile-diagnosis-context.mjs +88 -0
  28. package/src/batch/reconcile-diagnosis.mjs +14 -32
  29. package/src/batch/resume-multi-validate.mjs +51 -9
  30. package/src/batch/retry.mjs +18 -2
  31. package/src/batch/sequence-wait.mjs +20 -6
  32. package/src/config/gate-posture-config.mjs +190 -0
  33. package/src/config/pi-spine-root.mjs +22 -0
  34. package/src/config/spine-config-load.mjs +33 -0
  35. package/src/doctor/duplicate-install.mjs +100 -0
  36. package/src/doctor/run-doctor-checks.mjs +10 -1
  37. package/src/doctor/worktree-health.mjs +4 -0
  38. package/templates/spine-config.json +3 -2
package/bin/spine.mjs CHANGED
@@ -38,6 +38,11 @@ import { loadSpineConfig } from "./spine-config.mjs";
38
38
  import { cmdInit } from "./spine-init.mjs";
39
39
  import { cmdMigrateFromTaskplane } from "./spine-migrate-from-taskplane.mjs";
40
40
  import { cmdDoctor } from "./spine-doctor.mjs";
41
+ import { ensureDefaultPiSpineRootEnv } from "../src/config/pi-spine-root.mjs";
42
+ import {
43
+ detectPathSpineVersionSkew,
44
+ formatCheckoutVersionSkewRemediation,
45
+ } from "../src/doctor/duplicate-install.mjs";
41
46
 
42
47
  export { runDoctorChecks } from "./spine-doctor.mjs";
43
48
 
@@ -243,6 +248,20 @@ function cmdVersion() {
243
248
  const piVersion = getVersion("pi");
244
249
  if (piVersion) console.log(` Pi: ${piVersion}`);
245
250
  console.log(` Node: v${process.versions.node}`);
251
+
252
+ const skew = detectPathSpineVersionSkew({
253
+ runningPackageRoot: PACKAGE_ROOT,
254
+ projectRoot,
255
+ });
256
+ if (skew.skewed) {
257
+ console.log(
258
+ `\n ${c.yellow}⚠️ Version skew:${c.reset} running v${skew.cliVersion} ≠ checkout v${skew.checkoutVersion}`,
259
+ );
260
+ console.log(
261
+ ` ${c.dim}→ Use: ${formatCheckoutVersionSkewRemediation()}${c.reset}`,
262
+ );
263
+ }
264
+
246
265
  console.log();
247
266
  }
248
267
 
@@ -355,6 +374,9 @@ ${c.bold}Examples:${c.reset}
355
374
  }
356
375
 
357
376
  if (isCliEntrypoint(import.meta.url)) {
377
+ // Dogfood/checkout: unset PI_SPINE_ROOT + worktreeSetupHook must not fail
378
+ // doctor/preflight solely for a missing env var (SP-643 / #203).
379
+ ensureDefaultPiSpineRootEnv();
358
380
  const [command = "help", ...args] = process.argv.slice(2);
359
381
 
360
382
  const runCli = async () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.4.0",
3
+ "version": "2.6.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import {
8
+ ensureLandLoopFinalizedAfterGateOrIntegrate,
8
9
  finalizeAttachedLandLoopBeforeExit,
9
10
  finalizeResumedBatchForIntegrate,
10
11
  isPostMergeLimbo,
@@ -12,7 +13,7 @@ import {
12
13
  import { detectPostMergeLimboForResume } from "./resume-multi-validate.mjs";
13
14
  import { terminateStaleDetachedEngine } from "./resume-engine.mjs";
14
15
  import { reconcileBatch } from "./reconcile.mjs";
15
- import { readJournalEventsCached } from "./journal.mjs";
16
+ import { readJournalEvents, readJournalEventsCached } from "./journal.mjs";
16
17
  import { enforceOperatorPauseOnDisk } from "./pause.mjs";
17
18
  import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
18
19
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
@@ -25,6 +26,75 @@ import {
25
26
 
26
27
  export { DEFAULT_ATTACHED_MILESTONE_POLL_MS } from "../config/spine-config-schema.mjs";
27
28
 
29
+ /** Journal types that mean the land loop is done and a stuck resume engine should exit (#198). */
30
+ const HOST_LAND_LOOP_EXIT_TYPES = new Set([
31
+ "integrate.completed",
32
+ "gate.approved",
33
+ ]);
34
+
35
+ /** Journal types that mean gate/integrate artifacts exist and finalize should run. */
36
+ const LAND_LOOP_ENSURE_TYPES = new Set([
37
+ "gate.opened",
38
+ "gate.approved",
39
+ "integrate.completed",
40
+ "batch.land_loop_finalized",
41
+ ]);
42
+
43
+ /**
44
+ * When host opens/approves the gate or integrates while this engine is mid-evidence,
45
+ * finalize land-loop artifacts and exit so we are not a zombie PID (#198 / SP-636).
46
+ *
47
+ * @param {object} params
48
+ * @param {string} params.projectRoot
49
+ * @param {object} params.event
50
+ * @param {(code?: number) => void} [params.exitProcess]
51
+ */
52
+ export function maybeFinalizeAttachedEngineAfterHostLandLoop({
53
+ projectRoot,
54
+ event,
55
+ exitProcess = (code) => process.exit(code),
56
+ }) {
57
+ const type = String(event?.type ?? "");
58
+ if (!LAND_LOOP_ENSURE_TYPES.has(type)) {
59
+ return { handled: false, reason: "not_land_loop_event" };
60
+ }
61
+
62
+ const loaded = loadSpineBatchState(projectRoot);
63
+ if (!loaded.raw?.batchId) {
64
+ return { handled: false, reason: "no_active_batch" };
65
+ }
66
+
67
+ const state = loaded.raw;
68
+ const batchId = String(state.batchId);
69
+ const resumed = readJournalEvents(projectRoot, batchId).some(
70
+ (entry) => entry.type === "batch.resumed",
71
+ );
72
+ const ensured = ensureLandLoopFinalizedAfterGateOrIntegrate({
73
+ projectRoot,
74
+ state,
75
+ batchId,
76
+ resumed,
77
+ resumeForced: Boolean(state.resilience?.resumeForced),
78
+ source: "attached_milestone_host_land_loop",
79
+ });
80
+
81
+ if (!ensured) {
82
+ return { handled: false, reason: "ensure_not_applicable" };
83
+ }
84
+
85
+ if (HOST_LAND_LOOP_EXIT_TYPES.has(type) || ensured.shouldExit) {
86
+ exitProcess(0);
87
+ return { handled: true, action: "exited_after_host_land_loop", batchId, result: ensured };
88
+ }
89
+
90
+ return {
91
+ handled: true,
92
+ action: ensured.changed ? "finalized_after_gate_opened" : "already_finalized",
93
+ batchId,
94
+ result: ensured,
95
+ };
96
+ }
97
+
28
98
  /** @type {boolean} */
29
99
  let attachedExitHandlersInstalled = false;
30
100
 
@@ -109,12 +179,14 @@ export function formatAttachedMilestoneLine(event) {
109
179
  * @param {string} params.projectRoot
110
180
  * @param {(line: string) => void} [params.write]
111
181
  * @param {number} [params.pollIntervalMs]
182
+ * @param {(code?: number) => void} [params.exitProcess]
112
183
  * @returns {Promise<{ stop: () => Promise<void> }>}
113
184
  */
114
185
  export async function startAttachedMilestoneReporter({
115
186
  projectRoot,
116
187
  write = (line) => process.stdout.write(line),
117
188
  pollIntervalMs,
189
+ exitProcess = (code) => process.exit(code),
118
190
  }) {
119
191
  const configResult = loadSpineConfig(projectRoot);
120
192
  const resolvedPollMs =
@@ -125,6 +197,26 @@ export async function startAttachedMilestoneReporter({
125
197
  let batchId = null;
126
198
  let stopped = false;
127
199
 
200
+ const emitAndMaybeFinalize = (event) => {
201
+ const key = milestoneEventKey(event);
202
+ if (printed.has(key)) return;
203
+ const type = String(event.type ?? "");
204
+ const isMilestone = ATTACHED_LAND_LOOP_MILESTONE_TYPES.has(type);
205
+ const isLandLoopEnsure = LAND_LOOP_ENSURE_TYPES.has(type);
206
+ if (!isMilestone && !isLandLoopEnsure) return;
207
+ printed.add(key);
208
+ if (isMilestone) {
209
+ write(formatAttachedMilestoneLine(event));
210
+ }
211
+ if (isLandLoopEnsure) {
212
+ maybeFinalizeAttachedEngineAfterHostLandLoop({
213
+ projectRoot,
214
+ event,
215
+ exitProcess,
216
+ });
217
+ }
218
+ };
219
+
128
220
  const loop = async () => {
129
221
  while (!stopped) {
130
222
  enforceOperatorPauseOnDisk(projectRoot);
@@ -135,11 +227,7 @@ export async function startAttachedMilestoneReporter({
135
227
  if (batchId) {
136
228
  const events = readJournalEventsCached(projectRoot, batchId);
137
229
  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));
230
+ emitAndMaybeFinalize(event);
143
231
  }
144
232
  }
145
233
  await sleep(resolvedPollMs);
@@ -155,11 +243,7 @@ export async function startAttachedMilestoneReporter({
155
243
  if (batchId) {
156
244
  const events = readJournalEventsCached(projectRoot, batchId);
157
245
  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));
246
+ emitAndMaybeFinalize(event);
163
247
  }
164
248
  }
165
249
  },
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Allow-listed BlockerCode values and `{ code, message }` helper (FR-REL250-03 / #122).
3
+ *
4
+ * Pure module — wired into `checkIntegrateGate` / approve fail paths (SP-626). Unknown codes fail closed.
5
+ */
6
+
7
+ /** @typedef {(typeof BLOCKER_CODES)[number]} BlockerCode */
8
+
9
+ /**
10
+ * @typedef {object} Blocker
11
+ * @property {BlockerCode} code
12
+ * @property {string} message
13
+ */
14
+
15
+ /**
16
+ * Integrate/gate codes cover `checkIntegrateGate` fail paths and SP-624 revision drift.
17
+ * Readiness codes mirror pi-conductor evidence-service names from #122 for automation parity.
18
+ *
19
+ * @type {readonly string[]}
20
+ */
21
+ export const BLOCKER_CODES = Object.freeze([
22
+ "missing_gate",
23
+ "gate_pending",
24
+ "gate_rejected",
25
+ "stale_revision",
26
+ "force_integrate_blocked",
27
+ "missing_task",
28
+ "task_not_terminal",
29
+ "open_gate",
30
+ "missing_completion_report",
31
+ "missing_test_result",
32
+ "missing_commit",
33
+ "missing_push",
34
+ "missing_ready_for_pr_gate",
35
+ ]);
36
+
37
+ /** @type {ReadonlySet<string>} */
38
+ const BLOCKER_CODE_SET = new Set(BLOCKER_CODES);
39
+
40
+ /**
41
+ * @param {unknown} code
42
+ * @returns {code is BlockerCode}
43
+ */
44
+ export function isBlockerCode(code) {
45
+ return typeof code === "string" && BLOCKER_CODE_SET.has(code);
46
+ }
47
+
48
+ /**
49
+ * Build a structured blocker. Rejects unknown codes and empty messages fail-closed.
50
+ *
51
+ * @param {string} code
52
+ * @param {string} message
53
+ * @returns {Blocker}
54
+ */
55
+ export function makeBlocker(code, message) {
56
+ if (!isBlockerCode(code)) {
57
+ throw new Error(`Unknown BlockerCode: ${String(code)}`);
58
+ }
59
+ if (typeof message !== "string" || message.trim().length === 0) {
60
+ throw new Error("Blocker message must be a non-empty string");
61
+ }
62
+ return { code, message };
63
+ }
@@ -7,11 +7,29 @@ import { buildWorkerDoneMissingAlternatives } from "./diagnosis-worker-done-miss
7
7
  * @param {string} diagnosis
8
8
  * @param {object} [ctx]
9
9
  * @param {string|null} [ctx.failedTaskId]
10
+ * @param {string|null} [ctx.batchId]
11
+ * @param {object[]} [ctx.pendingLaneLandTasks]
10
12
  */
11
13
  export function buildAlternatives(diagnosis, ctx = {}) {
12
14
  const common = ["spine status --diagnose"];
13
15
 
16
+ if ((ctx.pendingLaneLandTasks?.length ?? 0) > 0) {
17
+ return [
18
+ ctx.batchId
19
+ ? `spine batch salvage --batch ${ctx.batchId} --dry-run`
20
+ : "spine batch salvage --batch <batchId> --dry-run",
21
+ ...common,
22
+ ];
23
+ }
24
+
14
25
  switch (diagnosis) {
26
+ case "pending_lane_land":
27
+ return [
28
+ ctx.batchId
29
+ ? `spine batch salvage --batch ${ctx.batchId} --dry-run`
30
+ : "spine batch salvage --batch <batchId> --dry-run",
31
+ ...common,
32
+ ];
15
33
  case "limbo_stale":
16
34
  return ["spine batch complete --detect-manual-merge", ...common];
17
35
  case "completed_manual":
@@ -0,0 +1,23 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Gate-ready headline context — demote historical merge blockers (#195 / FR-REL231-01).
4
+ */
5
+
6
+ /**
7
+ * Gate-ready batches must not headline historical merge/gitignored blockers (#195 / FR-REL231-01).
8
+ *
9
+ * @param {string} diagnosis
10
+ * @param {object} [ctx]
11
+ * @param {boolean} [ctx.allTasksTerminalSuccess]
12
+ * @param {boolean} [ctx.integrateGateOpen]
13
+ * @returns {boolean}
14
+ */
15
+ export function isGateReadyHeadlineContext(diagnosis, ctx = {}) {
16
+ if (diagnosis === "needs_integrate") {
17
+ return true;
18
+ }
19
+ if (ctx.allTasksTerminalSuccess === true && ctx.integrateGateOpen === true) {
20
+ return true;
21
+ }
22
+ return false;
23
+ }
@@ -0,0 +1,63 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Pending lane land diagnosis — lane `.DONE` without main land (#201 / SP-645).
4
+ */
5
+
6
+ /**
7
+ * Tasks with lane `.DONE` but not on main — lane commits never landed (#201 / SP-645).
8
+ *
9
+ * @param {object[]|undefined} tasks
10
+ * @returns {object[]}
11
+ */
12
+ export function findPendingLaneLandTasks(tasks) {
13
+ if (!Array.isArray(tasks)) return [];
14
+ return tasks.filter((task) => task?.doneInLane === true && task?.doneOnMain !== true);
15
+ }
16
+
17
+ /**
18
+ * @param {object} signals
19
+ * @returns {boolean}
20
+ */
21
+ export function shouldDiagnosePendingLaneLand(signals) {
22
+ const pending = findPendingLaneLandTasks(signals.tasks);
23
+ if (pending.length === 0) return false;
24
+ // Only when orch already appears merged — otherwise healthy pre-integrate
25
+ // waves (doneInLane, awaiting integrate) must stay needs_integrate / settled.
26
+ if (signals.git?.orchMergedToBase !== true) return false;
27
+ if (signals.stateDrift?.drifted === true) return true;
28
+ if (signals.allTasksTerminalSuccess !== true) return false;
29
+ return true;
30
+ }
31
+
32
+ /**
33
+ * @param {string|null|undefined} batchId
34
+ * @param {object[]} pendingTasks
35
+ * @returns {string}
36
+ */
37
+ export function buildPendingLaneLandSuggestedCommand(batchId, pendingTasks) {
38
+ const laneNumber = Number(pendingTasks[0]?.laneNumber);
39
+ if (batchId && Number.isFinite(laneNumber) && laneNumber > 0) {
40
+ return `spine batch salvage --batch ${batchId} --lane ${laneNumber} --integrate`;
41
+ }
42
+ if (batchId) {
43
+ return `spine batch salvage --batch ${batchId} --dry-run`;
44
+ }
45
+ return "spine batch salvage --batch <batchId> --dry-run";
46
+ }
47
+
48
+ /**
49
+ * @param {string} batchLabel
50
+ * @param {object} ctx
51
+ * @param {string|null|undefined} [ctx.batchId]
52
+ * @param {object[]} [ctx.pendingLaneLandTasks]
53
+ * @param {string|null|undefined} [ctx.baseBranch]
54
+ * @returns {string}
55
+ */
56
+ export function buildPendingLaneLandHeadline(batchLabel, ctx = {}) {
57
+ const pendingTaskIds = (ctx.pendingLaneLandTasks ?? [])
58
+ .map((task) => String(task.taskId ?? ""))
59
+ .filter(Boolean);
60
+ const baseBranch = ctx.baseBranch ?? "main";
61
+ const taskSuffix = pendingTaskIds.length > 0 ? ` (${pendingTaskIds.join(", ")})` : "";
62
+ return `${batchLabel} has lane work not on ${baseBranch}${taskSuffix} — salvage integrate`;
63
+ }
@@ -0,0 +1,23 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Retry suggestion sanitization — journal salvage payloads may be stale.
4
+ */
5
+
6
+ const INVALID_BARE_RETRY_FORCE = /^spine batch retry --force$/;
7
+
8
+ /**
9
+ * Retry suggestions must include a task id; journal salvage payloads may be stale.
10
+ *
11
+ * @param {string|null|undefined} command
12
+ * @param {string|null|undefined} taskId
13
+ * @returns {string|null}
14
+ */
15
+ export function sanitizeRetrySuggestedCommand(command, taskId) {
16
+ if (typeof command !== "string" || command.length === 0) {
17
+ return command ?? null;
18
+ }
19
+ if (INVALID_BARE_RETRY_FORCE.test(command.trim())) {
20
+ return taskId ? `spine batch retry ${taskId}` : "spine status --diagnose";
21
+ }
22
+ return command;
23
+ }
@@ -7,12 +7,77 @@ import { macroPhaseLabel } from "./macro-phase.mjs";
7
7
 
8
8
  export { isRunningWithoutActiveWorkers };
9
9
 
10
+ /**
11
+ * Whether batch-state records a live resume/batch engine PID (#198 / SP-637).
12
+ *
13
+ * @param {object} ctx
14
+ * @returns {boolean}
15
+ */
16
+ export function isEngineStillRunning(ctx = {}) {
17
+ if (ctx.engineStillRunning === true) {
18
+ return true;
19
+ }
20
+ const enginePid = ctx.enginePid;
21
+ if (enginePid == null) {
22
+ return false;
23
+ }
24
+ if (ctx.staleEnginePid === true) {
25
+ return false;
26
+ }
27
+ return true;
28
+ }
29
+
30
+ /**
31
+ * Post-integrate limbo: orch merged, tasks terminal-success, engine PID still alive.
32
+ * Stale segment pending must not mask limbo when lane workers are idle (#198 / SP-637).
33
+ *
34
+ * @param {object} ctx
35
+ * @returns {boolean}
36
+ */
37
+ export function isPostIntegrateEngineLimbo(ctx = {}) {
38
+ if (ctx.allTasksTerminalSuccess !== true) {
39
+ return false;
40
+ }
41
+ if (ctx.gitMerged !== true) {
42
+ return false;
43
+ }
44
+ if (!isEngineStillRunning(ctx)) {
45
+ return false;
46
+ }
47
+ if (ctx.hasRunningTasks === true) {
48
+ return false;
49
+ }
50
+ const phase = ctx.phase ?? "";
51
+ if (phase !== "running" && phase !== "merging") {
52
+ return false;
53
+ }
54
+ return true;
55
+ }
56
+
57
+ /**
58
+ * @param {string} batchLabel
59
+ * @param {object} ctx
60
+ * @returns {string|null}
61
+ */
62
+ export function buildPostIntegrateEngineLimboHeadline(batchLabel, ctx = {}) {
63
+ const enginePid = ctx.enginePid;
64
+ const pidSuffix =
65
+ enginePid != null && Number.isFinite(Number(enginePid))
66
+ ? ` (PID ${enginePid})`
67
+ : "";
68
+ return `${batchLabel} resume engine still running after integrate${pidSuffix} — wait, abort, or batch complete after exit`;
69
+ }
70
+
10
71
  /**
11
72
  * @param {string} batchLabel
12
73
  * @param {object} ctx
13
74
  * @returns {string|null}
14
75
  */
15
76
  export function buildRunningTailHeadline(batchLabel, ctx = {}) {
77
+ if (isPostIntegrateEngineLimbo(ctx)) {
78
+ return buildPostIntegrateEngineLimboHeadline(batchLabel, ctx);
79
+ }
80
+
16
81
  if (!isRunningWithoutActiveWorkers(ctx)) {
17
82
  return null;
18
83
  }
@@ -38,6 +103,9 @@ export function buildRunningTailHeadline(batchLabel, ctx = {}) {
38
103
  }
39
104
 
40
105
  if (macroPhase === "reviewing") {
106
+ if (ctx.allTasksTerminalSuccess === true && isEngineStillRunning(ctx)) {
107
+ return buildPostIntegrateEngineLimboHeadline(batchLabel, ctx);
108
+ }
41
109
  return `${batchLabel} running reviews — no workers scheduled`;
42
110
  }
43
111