pi-spine 1.0.2 → 1.2.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 (129) hide show
  1. package/README.md +61 -489
  2. package/bin/get-version.mjs +1 -13
  3. package/bin/spine-batch.mjs +162 -51
  4. package/bin/spine-cli/batch.mjs +3 -3
  5. package/bin/spine-cli/lane-logs.mjs +24 -0
  6. package/bin/spine-cli/scenarios.mjs +298 -0
  7. package/bin/spine-cli/wait.mjs +30 -0
  8. package/bin/spine-cli/watch.mjs +27 -0
  9. package/bin/spine-config.mjs +1 -212
  10. package/bin/spine-doctor.mjs +2 -418
  11. package/bin/spine-init.mjs +1 -398
  12. package/bin/spine-issue.mjs +196 -0
  13. package/bin/spine-journal.mjs +1 -0
  14. package/bin/spine-preflight.mjs +1 -700
  15. package/bin/spine-review-step.mjs +6 -4
  16. package/bin/spine-run.mjs +30 -0
  17. package/bin/spine-status.mjs +19 -1
  18. package/bin/spine-tasks.mjs +112 -13
  19. package/bin/spine-worker-runner.mjs +24 -14
  20. package/bin/spine.mjs +52 -2
  21. package/extensions/spine/worker-tools.ts +14 -12
  22. package/package.json +5 -2
  23. package/skills/create-spine-tasks/SKILL.md +135 -6
  24. package/skills/create-spine-tasks/references/clarify-template.md +73 -0
  25. package/skills/create-spine-tasks/references/contract-template.md +19 -0
  26. package/skills/create-spine-tasks/references/prompt-template.md +2 -0
  27. package/skills/create-spine-tasks/references/requirements-checklist-template.md +94 -0
  28. package/src/batch/abort.mjs +3 -12
  29. package/src/batch/agent-session-worker.mjs +45 -5
  30. package/src/batch/attached-engine-handoff.mjs +188 -0
  31. package/src/batch/attached-runner.mjs +312 -0
  32. package/src/batch/contract-prelanded.mjs +180 -0
  33. package/src/batch/contract-verify.mjs +140 -2
  34. package/src/batch/detached-start.mjs +105 -7
  35. package/src/batch/diagnosis-alternatives.mjs +46 -0
  36. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  37. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  38. package/src/batch/diagnosis-stub.mjs +109 -0
  39. package/src/batch/diagnosis-task-done.mjs +110 -0
  40. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  41. package/src/batch/diagnosis.mjs +174 -62
  42. package/src/batch/engine-lanes/merge.mjs +168 -77
  43. package/src/batch/engine-lanes/queue.mjs +4 -1
  44. package/src/batch/engine-lanes/review.mjs +32 -74
  45. package/src/batch/engine-lanes/watch.mjs +29 -0
  46. package/src/batch/engine-lanes.mjs +1 -0
  47. package/src/batch/engine-scope.mjs +42 -5
  48. package/src/batch/engine.mjs +115 -68
  49. package/src/batch/evidence.mjs +81 -17
  50. package/src/batch/gate.mjs +46 -17
  51. package/src/batch/git-helpers.mjs +96 -0
  52. package/src/batch/heartbeat.mjs +73 -7
  53. package/src/batch/integrate.mjs +3 -5
  54. package/src/batch/journal.mjs +25 -0
  55. package/src/batch/lane-commit.mjs +90 -5
  56. package/src/batch/lifecycle.mjs +131 -4
  57. package/src/batch/macro-phase.mjs +226 -0
  58. package/src/batch/merge/adoption-doc-merge.mjs +243 -0
  59. package/src/batch/merge/wave-merge-state.mjs +108 -0
  60. package/src/batch/metrics.mjs +74 -5
  61. package/src/batch/orphan-detect.mjs +74 -0
  62. package/src/batch/pause.mjs +223 -0
  63. package/src/batch/post-merge-limbo.mjs +345 -17
  64. package/src/batch/reconcile.mjs +473 -50
  65. package/src/batch/resume-common.mjs +6 -2
  66. package/src/batch/resume-engine.mjs +58 -1
  67. package/src/batch/resume-lane-reviews.mjs +16 -0
  68. package/src/batch/resume-multi-lanes.mjs +56 -1
  69. package/src/batch/resume-multi-validate.mjs +148 -8
  70. package/src/batch/resume-multi.mjs +45 -44
  71. package/src/batch/resume.mjs +64 -47
  72. package/src/batch/retry.mjs +56 -5
  73. package/src/batch/review-shared.mjs +196 -0
  74. package/src/batch/review-spawn.mjs +326 -0
  75. package/src/batch/review.mjs +178 -212
  76. package/src/batch/rules-manifest-drift.mjs +157 -0
  77. package/src/batch/salvage.mjs +2 -1
  78. package/src/batch/sequence.mjs +454 -0
  79. package/src/batch/state.mjs +18 -3
  80. package/src/batch/status-json.mjs +67 -0
  81. package/src/batch/task-stall-budget.mjs +94 -10
  82. package/src/batch/worker-host.mjs +185 -37
  83. package/src/batch/worker-output.mjs +196 -3
  84. package/src/batch/worktree.mjs +10 -0
  85. package/src/cli/handoff.mjs +1 -1
  86. package/src/cli/issue-draft.mjs +180 -0
  87. package/src/cli/journal-follow.mjs +239 -0
  88. package/src/cli/lane-logs.mjs +291 -0
  89. package/src/cli/rules.mjs +1 -1
  90. package/src/cli/sequence.mjs +108 -0
  91. package/src/cli/settings-set.mjs +3 -22
  92. package/src/cli/settings-slash.mjs +27 -5
  93. package/src/cli/wait.mjs +187 -0
  94. package/src/cli/watch.mjs +160 -0
  95. package/src/config/agent-model-resolve.mjs +48 -0
  96. package/src/config/cursor-rules/discover.mjs +3 -21
  97. package/src/config/defaults.mjs +7 -1
  98. package/src/config/settings-fields.mjs +48 -0
  99. package/src/config/spine-config-load.mjs +221 -0
  100. package/src/config/spine-init-constants.mjs +424 -0
  101. package/src/config/spine-preflight-lib.mjs +1180 -0
  102. package/src/dashboard/lane-throughput.mjs +351 -0
  103. package/src/dashboard/public/dashboard.css +25 -1
  104. package/src/dashboard/public/dashboard.js +224 -40
  105. package/src/dashboard/public/index.html +15 -9
  106. package/src/dashboard/server.mjs +4 -0
  107. package/src/dashboard/snapshot.mjs +387 -6
  108. package/src/dashboard/view.mjs +170 -15
  109. package/src/doctor/agent-model-inherit.mjs +61 -6
  110. package/src/doctor/run-doctor-checks.mjs +483 -0
  111. package/src/doctor/sequence-safety.mjs +57 -0
  112. package/src/doctor/stale-path.mjs +22 -0
  113. package/src/doctor/stale-worktrees.mjs +102 -0
  114. package/src/fixtures/scenario-registry.mjs +194 -0
  115. package/src/fs/atomic-write.mjs +49 -0
  116. package/src/migrate/taskplane-config.mjs +1 -1
  117. package/src/planner/file-scope.mjs +246 -0
  118. package/src/planner/format-plan.mjs +9 -7
  119. package/src/planner/index.mjs +6 -2
  120. package/src/planner/pending.mjs +92 -1
  121. package/src/planner/wave-scope.mjs +136 -0
  122. package/src/planner/waves.mjs +133 -0
  123. package/src/tasks/analyze/index.mjs +453 -0
  124. package/src/tasks/packet/index.mjs +1 -0
  125. package/src/tasks/packet/parse-prompt.mjs +42 -1
  126. package/src/tasks/packet/validate-prompt.mjs +124 -0
  127. package/src/util/command-exists.mjs +19 -0
  128. package/templates/docs/constitution.md +61 -0
  129. package/templates/spine-config.json +9 -2
@@ -5,8 +5,9 @@
5
5
  import crypto from "node:crypto";
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
- import { loadSpineConfig } from "../../bin/spine-config.mjs";
9
- import { collectEvidenceBundle } from "./evidence.mjs";
8
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
+ import { writeJsonAtomic } from "../fs/atomic-write.mjs";
10
+ import { collectCoreEvidenceBundle, collectExtendedEvidenceBundle, finalizeEvidenceBundleComplete } from "./evidence.mjs";
10
11
  import { appendJournalEvent } from "./journal.mjs";
11
12
 
12
13
  /**
@@ -39,15 +40,7 @@ export function loadGateRecord(projectRoot, batchId) {
39
40
  */
40
41
  export function saveGateRecord(projectRoot, gate) {
41
42
  const filePath = gateRecordPath(projectRoot, gate.batchId);
42
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
43
- fs.writeFileSync(filePath, `${JSON.stringify(gate, null, 2)}\n`, "utf-8");
44
-
45
- const fd = fs.openSync(filePath, "r");
46
- try {
47
- fs.fsyncSync(fd);
48
- } finally {
49
- fs.closeSync(fd);
50
- }
43
+ writeJsonAtomic(filePath, gate);
51
44
  }
52
45
 
53
46
  /**
@@ -65,7 +58,7 @@ export function formatGateSummary(gate) {
65
58
  * @param {string} ctx.projectRoot
66
59
  * @param {string} ctx.batchId
67
60
  * @param {object|null} [ctx.batchState]
68
- * @param {import("../../bin/spine-config.mjs").SpineConfig|null} [ctx.config]
61
+ * @param {ReturnType<typeof loadSpineConfig>["config"]} [ctx.config]
69
62
  */
70
63
  export function openIntegrateGate(ctx) {
71
64
  const { projectRoot, batchId, batchState = null, config = null } = ctx;
@@ -74,15 +67,18 @@ export function openIntegrateGate(ctx) {
74
67
  return { gate: existing, opened: false, evidenceRefs: existing.evidenceRefs ?? [] };
75
68
  }
76
69
 
77
- const evidence = collectEvidenceBundle({ projectRoot, batchId, batchState, config });
70
+ const core = collectCoreEvidenceBundle({ projectRoot, batchId, batchState, config });
71
+ /** @type {string[]} */
72
+ let evidenceRefs = [...core.evidenceRefs];
73
+
78
74
  const gate = {
79
75
  gateId: crypto.randomUUID(),
80
76
  batchId,
81
77
  kind: "integrate",
82
78
  status: "pending",
83
79
  openedAt: new Date().toISOString(),
84
- evidenceRefs: evidence.evidenceRefs,
85
- summary: formatGateSummary({ kind: "integrate", status: "pending", evidenceRefs: evidence.evidenceRefs }),
80
+ evidenceRefs,
81
+ summary: formatGateSummary({ kind: "integrate", status: "pending", evidenceRefs }),
86
82
  };
87
83
 
88
84
  saveGateRecord(projectRoot, gate);
@@ -93,7 +89,40 @@ export function openIntegrateGate(ctx) {
93
89
  evidenceRefs: gate.evidenceRefs,
94
90
  });
95
91
 
96
- return { gate, opened: true, evidenceRefs: evidence.evidenceRefs };
92
+ appendJournalEvent(projectRoot, batchId, "gate.evidence_collecting", {
93
+ stage: "extended",
94
+ });
95
+
96
+ /** @type {string | null} */
97
+ let extendedError = null;
98
+ try {
99
+ const extended = collectExtendedEvidenceBundle({
100
+ projectRoot,
101
+ batchId,
102
+ batchState,
103
+ config,
104
+ evidenceRefs,
105
+ });
106
+ evidenceRefs = extended.evidenceRefs;
107
+ appendJournalEvent(projectRoot, batchId, "gate.evidence_completed", {
108
+ evidenceRefCount: evidenceRefs.length,
109
+ });
110
+ } catch (err) {
111
+ extendedError = err instanceof Error ? err.message : String(err);
112
+ appendJournalEvent(projectRoot, batchId, "gate.evidence_failed", {
113
+ message: extendedError.slice(0, 500),
114
+ });
115
+ }
116
+
117
+ gate.evidenceRefs = evidenceRefs;
118
+ gate.summary = formatGateSummary({ kind: "integrate", status: "pending", evidenceRefs: gate.evidenceRefs });
119
+ saveGateRecord(projectRoot, gate);
120
+
121
+ if (!extendedError) {
122
+ finalizeEvidenceBundleComplete(projectRoot, batchId, evidenceRefs);
123
+ }
124
+
125
+ return { gate, opened: true, evidenceRefs: gate.evidenceRefs, extendedError };
97
126
  }
98
127
 
99
128
  /**
@@ -277,7 +306,7 @@ export function getIntegrateGateStatus(ctx) {
277
306
  * @param {object} ctx
278
307
  * @param {string} ctx.projectRoot
279
308
  * @param {string} ctx.batchId
280
- * @param {import("../../bin/spine-config.mjs").SpineConfig|null} [ctx.config]
309
+ * @param {ReturnType<typeof loadSpineConfig>["config"]} [ctx.config]
281
310
  * @param {boolean} [ctx.forceIntegrate]
282
311
  * @param {boolean} [ctx.dryRun]
283
312
  */
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Shared git path helpers for spine batch merge and lane commit.
3
+ */
4
+
5
+ import { execFileSync } from "node:child_process";
6
+ import { gitExec } from "./git-exec.mjs";
7
+
8
+ /**
9
+ * @param {string} projectRoot
10
+ * @param {string[]} paths
11
+ * @returns {{ stageable: string[], skipped: string[] }}
12
+ */
13
+ export function filterGitignoredPaths(projectRoot, paths) {
14
+ const normalized = [...new Set(paths.filter(Boolean))];
15
+ if (normalized.length === 0) {
16
+ return { stageable: [], skipped: [] };
17
+ }
18
+
19
+ /** @type {Set<string>} */
20
+ let ignoredSet = new Set();
21
+ try {
22
+ const output = execFileSync("git", ["check-ignore", "--no-index", "--stdin"], {
23
+ cwd: projectRoot,
24
+ input: `${normalized.join("\n")}\n`,
25
+ encoding: "utf-8",
26
+ stdio: ["pipe", "pipe", "pipe"],
27
+ });
28
+ for (const line of output.split("\n")) {
29
+ const trimmed = line.trim();
30
+ if (trimmed) ignoredSet.add(trimmed);
31
+ }
32
+ } catch (err) {
33
+ const execErr = /** @type {NodeJS.ErrnoException & { status?: number }} */ (err);
34
+ if (execErr.status === 1) {
35
+ return { stageable: normalized, skipped: [] };
36
+ }
37
+ throw err;
38
+ }
39
+
40
+ /** @type {string[]} */
41
+ const stageable = [];
42
+ /** @type {string[]} */
43
+ const skipped = [];
44
+ for (const filePath of normalized) {
45
+ if (ignoredSet.has(filePath)) {
46
+ skipped.push(filePath);
47
+ } else {
48
+ stageable.push(filePath);
49
+ }
50
+ }
51
+ return { stageable, skipped };
52
+ }
53
+
54
+ /**
55
+ * Stage paths while skipping gitignored entries. Never throws solely because a path is ignored.
56
+ *
57
+ * @param {string} cwd
58
+ * @param {string[]} paths
59
+ * @param {{ projectRoot?: string, throwOnError?: boolean }} [options]
60
+ * @returns {{ added: string[], skipped: string[] }}
61
+ */
62
+ export function gitAddFilteredPaths(cwd, paths, { projectRoot, throwOnError = true } = {}) {
63
+ const identityRoot = projectRoot ?? cwd;
64
+ const { stageable, skipped } = filterGitignoredPaths(cwd, paths);
65
+ if (stageable.length > 0) {
66
+ try {
67
+ gitExec(cwd, ["add", "--", ...stageable], { projectRoot: identityRoot, throwOnError });
68
+ } catch (err) {
69
+ const message = err instanceof Error ? err.message : String(err);
70
+ if (
71
+ throwOnError &&
72
+ skipped.length === 0 &&
73
+ (message.includes("ignored") || message.includes("check-ignore"))
74
+ ) {
75
+ const gitignoredErr = new Error(message);
76
+ gitignoredErr.name = "MergeGitignoredAddError";
77
+ throw gitignoredErr;
78
+ }
79
+ throw err;
80
+ }
81
+ }
82
+ return { added: stageable, skipped };
83
+ }
84
+
85
+ /**
86
+ * @param {unknown} err
87
+ */
88
+ export function isGitignoredAddError(err) {
89
+ if (!(err instanceof Error)) return false;
90
+ if (err.name === "MergeGitignoredAddError") return true;
91
+ const message = err.message.toLowerCase();
92
+ return (
93
+ message.includes("ignored by one of your .gitignore files") ||
94
+ (message.includes("git add") && message.includes("ignored"))
95
+ );
96
+ }
@@ -12,6 +12,7 @@ const DEFAULT_GRACE_AFTER_PROGRESS_MIN = 15;
12
12
  const DEFAULT_HEARTBEAT_INTERVAL_MIN = 10;
13
13
  const DEFAULT_CHECKPOINT_WARNING_MIN = 10;
14
14
  const DEFAULT_POST_DONE_GRACE_MIN = 4;
15
+ const DEFAULT_PROGRESS_SNAPSHOT_INTERVAL_MIN = 2;
15
16
  const POLL_INTERVAL_MS = 30_000;
16
17
 
17
18
  const CHECKPOINT_WARNING_SUGGESTION =
@@ -44,6 +45,8 @@ export function resolveStallConfig(config = {}) {
44
45
  Number(lanes.checkpointWarningMinutes) || DEFAULT_CHECKPOINT_WARNING_MIN;
45
46
  const postDoneGraceMinutes =
46
47
  Number(lanes.postDoneGraceMinutes) || DEFAULT_POST_DONE_GRACE_MIN;
48
+ const progressSnapshotIntervalMinutes =
49
+ Number(lanes.progressSnapshotIntervalMinutes) || DEFAULT_PROGRESS_SNAPSHOT_INTERVAL_MIN;
47
50
 
48
51
  return {
49
52
  stallTimeoutMs: stallTimeoutMinutes * 60 * 1000,
@@ -51,6 +54,7 @@ export function resolveStallConfig(config = {}) {
51
54
  heartbeatIntervalMs: heartbeatIntervalMinutes * 60 * 1000,
52
55
  checkpointWarningMs: checkpointWarningMinutes * 60 * 1000,
53
56
  postDoneGraceMs: postDoneGraceMinutes * 60 * 1000,
57
+ progressSnapshotIntervalMs: progressSnapshotIntervalMinutes * 60 * 1000,
54
58
  extendGraceOnFileScope: lanes.extendGraceOnFileScope === true,
55
59
  pollIntervalMs: POLL_INTERVAL_MS,
56
60
  };
@@ -297,13 +301,13 @@ export function shouldEmitCheckpointWarning({
297
301
  return now - lastCheckpointAt >= stallConfig.checkpointWarningMs;
298
302
  }
299
303
 
300
- /**
301
- * @param {object} params
302
- */
303
- export function computeStallDeadline({ startedAt, lastProgressAt, stallConfig }) {
304
- const hardDeadline = startedAt + stallConfig.stallTimeoutMs;
305
- const progressDeadline = lastProgressAt + stallConfig.graceAfterProgressMs;
306
- return Math.max(hardDeadline, progressDeadline);
304
+ /** @param {object} params @param {number} params.startedAt @param {number} params.lastProgressAt @param {number} [params.lastAliveAt] @param {ReturnType<typeof resolveStallConfig>} params.stallConfig */
305
+ export function computeStallDeadline({ startedAt, lastProgressAt, lastAliveAt, stallConfig }) {
306
+ const stallAnchorAt = lastAliveAt ?? startedAt;
307
+ return Math.max(
308
+ stallAnchorAt + stallConfig.stallTimeoutMs,
309
+ lastProgressAt + stallConfig.graceAfterProgressMs,
310
+ );
307
311
  }
308
312
 
309
313
  /**
@@ -352,6 +356,68 @@ export function buildHeartbeatPayloadFields(signals, workerPhase, heartbeatKind)
352
356
  };
353
357
  }
354
358
 
359
+ /**
360
+ * Bounded lane.progress_snapshot payload (issue #48).
361
+ *
362
+ * @param {object} signals
363
+ * @param {WorkerPhase} workerPhase
364
+ */
365
+ export function buildProgressSnapshotPayload(signals, workerPhase) {
366
+ return {
367
+ workerPhase,
368
+ dirtyPathCount: signals.dirtyPaths?.length ?? 0,
369
+ lastCommitAtMs: signals.lastCommitAtMs ?? null,
370
+ statusMtimeMs: signals.statusMtimeMs ?? null,
371
+ stepCompletedAtMs: signals.stepCompletedAtMs ?? null,
372
+ };
373
+ }
374
+
375
+ /**
376
+ * @param {object | null} prev
377
+ * @param {object} next
378
+ */
379
+ export function progressSnapshotPayloadChanged(prev, next) {
380
+ if (!prev) return true;
381
+ if (prev.workerPhase !== next.workerPhase) return true;
382
+ if (prev.dirtyPathCount !== next.dirtyPathCount) return true;
383
+ if (prev.lastCommitAtMs !== next.lastCommitAtMs) return true;
384
+ if (prev.statusMtimeMs !== next.statusMtimeMs) return true;
385
+ if (prev.stepCompletedAtMs !== next.stepCompletedAtMs) return true;
386
+ return false;
387
+ }
388
+
389
+ /**
390
+ * @param {object} params
391
+ * @param {number} params.now
392
+ * @param {number} params.lastEmittedAt
393
+ * @param {number} params.intervalMs
394
+ */
395
+ export function shouldEmitProgressSnapshot({ now, lastEmittedAt, intervalMs }) {
396
+ if (!intervalMs || intervalMs <= 0) return false;
397
+ return now - lastEmittedAt >= intervalMs;
398
+ }
399
+
400
+ /**
401
+ * @param {object} params
402
+ */
403
+ export function recordLaneProgressSnapshot({
404
+ projectRoot,
405
+ batchId,
406
+ laneNumber,
407
+ taskId,
408
+ signals,
409
+ correlationId,
410
+ workerPhase = "unknown",
411
+ }) {
412
+ const snapshot = buildProgressSnapshotPayload(signals, workerPhase);
413
+ appendJournalEvent(projectRoot, batchId, "lane.progress_snapshot", {
414
+ laneNumber,
415
+ taskId,
416
+ correlationId,
417
+ ...snapshot,
418
+ });
419
+ }
420
+
355
421
  /**
356
422
  * @param {object} params
357
423
  * @param {WorkerPhase} [params.workerPhase]
@@ -4,11 +4,9 @@
4
4
 
5
5
  import { execFileSync } from "node:child_process";
6
6
  import { gitExec } from "./git-exec.mjs";
7
- import { loadSpineConfig } from "../../bin/spine-config.mjs";
8
- import {
9
- resolveRulesManifestIntegrateDrift,
10
- tryAutoResolveRulesManifestMergeConflict,
11
- } from "./engine-lanes.mjs";
7
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
8
+ import { tryAutoResolveRulesManifestMergeConflict } from "./engine-lanes.mjs";
9
+ import { resolveRulesManifestIntegrateDrift } from "./rules-manifest-drift.mjs";
12
10
  import { checkIntegrateGate } from "./gate.mjs";
13
11
  import { appendJournalEvent } from "./journal.mjs";
14
12
  import { countCommitsAhead } from "./lane-commit.mjs";
@@ -275,6 +275,9 @@ export function summarizeJournalEvent(event) {
275
275
  if (payload.error) parts.push(String(payload.error).slice(0, 80));
276
276
  if (payload.classification) parts.push(String(payload.classification));
277
277
  if (payload.workerPhase) parts.push(`phase ${payload.workerPhase}`);
278
+ if (payload.dirtyPathCount != null && event.type === "lane.progress_snapshot") {
279
+ parts.push(`${payload.dirtyPathCount} dirty path(s)`);
280
+ }
278
281
  if (payload.workerOutputLogRef) parts.push(`→ ${payload.workerOutputLogRef}`);
279
282
  if (payload.exitReason) parts.push(String(payload.exitReason));
280
283
  if (payload.mergeCommit) parts.push(`merge ${String(payload.mergeCommit).slice(0, 8)}`);
@@ -371,3 +374,25 @@ export function extractJournalDiagnosisHints(events) {
371
374
 
372
375
  return hints;
373
376
  }
377
+
378
+ /**
379
+ * True when journal shows plan `review.failed` with `nested_spawn_blocked` for a task.
380
+ * Stale PATH spine pre-SP-278 behavior (batch 20260619T020951 / issue #12).
381
+ *
382
+ * @param {object[]} journalEvents
383
+ * @param {string|null} [taskId]
384
+ */
385
+ export function findPlanReviewNestedSpawnBlockedFailure(journalEvents, taskId) {
386
+ if (!Array.isArray(journalEvents) || journalEvents.length === 0) return false;
387
+ for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
388
+ const event = journalEvents[index];
389
+ if (event.type !== "review.failed") continue;
390
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
391
+ if (payload.reason !== "nested_spawn_blocked") continue;
392
+ if (payload.reviewType !== "plan") continue;
393
+ const eventTaskId = event.taskId ?? payload.taskId;
394
+ if (taskId && eventTaskId && eventTaskId !== taskId) continue;
395
+ return true;
396
+ }
397
+ return false;
398
+ }
@@ -5,7 +5,14 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { execFileSync } from "node:child_process";
8
+ import { filterGitignoredPaths, gitAddFilteredPaths } from "./git-helpers.mjs";
8
9
  import { gitExec } from "./git-exec.mjs";
10
+ import { parseContract } from "../tasks/packet/parse-prompt.mjs";
11
+ import {
12
+ hasReleaseCriticalContract,
13
+ shouldEnforceStubContractAtLaneCommit,
14
+ verifyStubFileScopeMustChange,
15
+ } from "./contract-verify.mjs";
9
16
 
10
17
  /**
11
18
  * @param {string} worktreePath
@@ -104,6 +111,31 @@ export function countCommitsAhead(projectRoot, baseRef, headRef) {
104
111
  return Number.parseInt(count, 10) || 0;
105
112
  }
106
113
 
114
+ /**
115
+ * @param {string} worktreePath
116
+ */
117
+ function listIgnoredUntrackedPaths(worktreePath) {
118
+ const output = execFileSync("git", ["ls-files", "-o", "-i", "--exclude-standard"], {
119
+ cwd: worktreePath,
120
+ encoding: "utf-8",
121
+ stdio: ["ignore", "pipe", "pipe"],
122
+ }).trim();
123
+ if (!output) return [];
124
+ return output.split("\n").map((line) => line.trim()).filter(Boolean);
125
+ }
126
+
127
+ /**
128
+ * @param {string} porcelain
129
+ * @returns {string[]}
130
+ */
131
+ function listPorcelainPaths(porcelain) {
132
+ if (!porcelain?.trim()) return [];
133
+ return porcelain
134
+ .split("\n")
135
+ .map((line) => extractPorcelainPath(line))
136
+ .filter((entry) => Boolean(entry));
137
+ }
138
+
107
139
  /**
108
140
  * Stage and commit uncommitted lane work when the worker left a `.DONE` marker.
109
141
  *
@@ -114,13 +146,24 @@ export function countCommitsAhead(projectRoot, baseRef, headRef) {
114
146
  * @param {string} params.batchId
115
147
  * @param {string} params.taskFolder Absolute path to task folder (for `.DONE` check)
116
148
  * @param {string} [params.projectRoot] Main repo root for git identity resolution
117
- * @returns {{ ok: true, committed: boolean, commitSha?: string } | { ok: false, error: string, failureClass: string }}
149
+ * @param {string} [params.baseBranch] Base branch for stub contract diff (default main)
150
+ * @returns {{ ok: true, committed: boolean, commitSha?: string, skippedGitignoredPaths?: string[] } | { ok: false, error: string, failureClass: string, gitignoredPaths?: string[] }}
118
151
  */
119
- export function commitLaneWorktree({ worktreePath, taskBranch, taskId, batchId, taskFolder, projectRoot }) {
152
+ export function commitLaneWorktree({
153
+ worktreePath,
154
+ taskBranch,
155
+ taskId,
156
+ batchId,
157
+ taskFolder,
158
+ projectRoot,
159
+ baseBranch = "main",
160
+ }) {
120
161
  const identityRoot = projectRoot ?? worktreePath;
121
162
  try {
122
163
  const porcelain = gitPorcelain(worktreePath);
123
- if (!porcelain) {
164
+ const dirtyPaths = listPorcelainPaths(porcelain);
165
+ const ignoredUntrackedPaths = listIgnoredUntrackedPaths(worktreePath);
166
+ if (dirtyPaths.length === 0 && ignoredUntrackedPaths.length === 0) {
124
167
  return { ok: true, committed: false };
125
168
  }
126
169
 
@@ -133,15 +176,57 @@ export function commitLaneWorktree({ worktreePath, taskBranch, taskId, batchId,
133
176
  };
134
177
  }
135
178
 
179
+ if (shouldEnforceStubContractAtLaneCommit(donePath)) {
180
+ const promptPath = path.join(taskFolder, "PROMPT.md");
181
+ const parsedContract = fs.existsSync(promptPath)
182
+ ? parseContract(fs.readFileSync(promptPath, "utf-8"))
183
+ : { fileScopeMustChange: [] };
184
+ if (hasReleaseCriticalContract(parsedContract)) {
185
+ const scopeCheck = verifyStubFileScopeMustChange(
186
+ worktreePath,
187
+ parsedContract,
188
+ baseBranch,
189
+ dirtyPaths,
190
+ );
191
+ if (!scopeCheck.ok) {
192
+ return {
193
+ ok: false,
194
+ error: `Stub worker completed without required file-scope changes: ${scopeCheck.failures.join("; ")}`,
195
+ failureClass: "stub",
196
+ };
197
+ }
198
+ }
199
+ }
200
+
201
+ const { stageable, skipped: gitignoredDirtyPaths } = filterGitignoredPaths(worktreePath, dirtyPaths);
202
+ const gitignoredPaths = [...new Set([...gitignoredDirtyPaths, ...ignoredUntrackedPaths])];
203
+ if (stageable.length === 0 && gitignoredPaths.length > 0) {
204
+ const preview = gitignoredPaths.slice(0, 20).join(", ");
205
+ const suffix = gitignoredPaths.length > 20 ? "…" : "";
206
+ return {
207
+ ok: false,
208
+ error:
209
+ `Lane worktree has gitignored dirty files only (${preview}${suffix}) — ` +
210
+ "remove from the index with git rm --cached on the task branch before resume",
211
+ failureClass: "GitignoredDirtyWorktree",
212
+ gitignoredPaths,
213
+ };
214
+ }
215
+
136
216
  const currentBranch = git(worktreePath, ["rev-parse", "--abbrev-ref", "HEAD"], identityRoot);
137
217
  if (currentBranch !== taskBranch) {
138
218
  git(worktreePath, ["checkout", taskBranch], identityRoot);
139
219
  }
140
- git(worktreePath, ["add", "-A"], identityRoot);
220
+ const addResult = gitAddFilteredPaths(worktreePath, stageable, { projectRoot: identityRoot });
141
221
  const message = `feat(${taskId}): batch ${batchId} worker completion`;
142
222
  git(worktreePath, ["commit", "-m", message], identityRoot);
143
223
  const commitSha = git(worktreePath, ["rev-parse", "HEAD"], identityRoot);
144
- return { ok: true, committed: true, commitSha };
224
+ return {
225
+ ok: true,
226
+ committed: true,
227
+ commitSha,
228
+ skippedGitignoredPaths: [...addResult.skipped, ...gitignoredPaths],
229
+ };
145
230
  } catch (err) {
146
231
  const message = err instanceof Error ? err.message : String(err);
147
232
  return {
@@ -6,15 +6,76 @@ import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { buildDiagnosisOutput } from "./diagnosis.mjs";
8
8
  import { assertOrchIntegratable } from "./integrate.mjs";
9
- import { loadSpineConfig } from "../../bin/spine-config.mjs";
9
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
10
10
  import { appendJournalEvent } from "./journal.mjs";
11
11
  import { recordBatchTerminalMetric } from "./metrics.mjs";
12
12
  import { writeBatchPostMortem } from "./postmortem.mjs";
13
- import { appendBatchHistoryEntry } from "./state.mjs";
13
+ import {
14
+ appendBatchHistoryEntry,
15
+ clearBatchEnginePid,
16
+ saveSpineBatchState,
17
+ } from "./state.mjs";
14
18
  import { loadBatchStateFile, parseBatchState, reconcileBatch } from "./reconcile.mjs";
19
+ import { terminateLaneWorkers } from "./worker-host.mjs";
20
+ import { removeLaneWorktrees } from "./worktree.mjs";
15
21
 
16
22
  const DISMISS_ALLOWED = new Set(["limbo_stale", "completed_manual", "aborted"]);
17
23
 
24
+ /**
25
+ * Terminal merge-blocked state when the engine exits after a wave merge failure (GitHub #38).
26
+ * Clears stale enginePid so status does not imply an in-progress merge.
27
+ *
28
+ * @param {object} params
29
+ * @param {string} params.projectRoot
30
+ * @param {object} params.state
31
+ * @param {string} params.batchId
32
+ * @param {string} params.error
33
+ * @param {number|null} [params.waveIndex]
34
+ * @param {number|null} [params.laneNumber]
35
+ * @param {string|null} [params.failureClass]
36
+ * @param {string[]} [params.failedTaskIds]
37
+ * @param {string[]} [params.pendingTaskIds]
38
+ * @param {string} [params.reason]
39
+ */
40
+ export function recordMergeBlocked({
41
+ projectRoot,
42
+ state,
43
+ batchId,
44
+ error,
45
+ waveIndex = null,
46
+ laneNumber = null,
47
+ failureClass = null,
48
+ failedTaskIds = null,
49
+ pendingTaskIds = null,
50
+ reason = "merge_failed",
51
+ }) {
52
+ const fromPhase = String(state.phase ?? "running");
53
+ const message = String(error ?? "merge blocked").slice(0, 500);
54
+ state.endedAt = Date.now();
55
+ state.lastError = message;
56
+ state.phase = "merge_blocked";
57
+ clearBatchEnginePid(state);
58
+
59
+ appendJournalEvent(projectRoot, batchId, "batch.merge_blocked", {
60
+ fromPhase,
61
+ reason,
62
+ waveIndex,
63
+ laneNumber,
64
+ failureClass,
65
+ failedTaskIds,
66
+ pendingTaskIds,
67
+ error: message,
68
+ });
69
+
70
+ saveSpineBatchState(projectRoot, state);
71
+
72
+ return {
73
+ phase: "merge_blocked",
74
+ fromPhase,
75
+ lastError: message,
76
+ };
77
+ }
78
+
18
79
  /**
19
80
  * @param {string} projectRoot
20
81
  * @param {string} batchId
@@ -52,6 +113,48 @@ function clearActiveBatchState(batchStatePath) {
52
113
  }
53
114
  }
54
115
 
116
+ /**
117
+ * @param {unknown} raw
118
+ */
119
+ function maxLaneNumberFromBatchState(raw) {
120
+ const lanes = /** @type {{ lanes?: unknown }} */ (raw)?.lanes;
121
+ if (!Array.isArray(lanes) || lanes.length === 0) return 1;
122
+ let max = 1;
123
+ for (const lane of lanes) {
124
+ if (!lane || typeof lane !== "object") continue;
125
+ const laneNumber = Number(/** @type {{ laneNumber?: number }} */ (lane).laneNumber);
126
+ if (Number.isFinite(laneNumber) && laneNumber > max) {
127
+ max = laneNumber;
128
+ }
129
+ }
130
+ return max;
131
+ }
132
+
133
+ /**
134
+ * @param {object|null|undefined} config
135
+ */
136
+ function shouldCleanupWorktreesOnComplete(config) {
137
+ if (config?.lanes?.cleanupWorktreesOnComplete === false) return false;
138
+ return true;
139
+ }
140
+
141
+ /**
142
+ * @param {object} params
143
+ * @param {string} params.projectRoot
144
+ * @param {string} params.batchId
145
+ * @param {unknown} params.batchState
146
+ * @param {object} params.config
147
+ */
148
+ function cleanupBatchLaneWorktrees({ projectRoot, batchId, batchState, config }) {
149
+ if (!shouldCleanupWorktreesOnComplete(config)) return;
150
+ const laneCount = maxLaneNumberFromBatchState(batchState);
151
+ removeLaneWorktrees(projectRoot, batchId, laneCount);
152
+ appendJournalEvent(projectRoot, batchId, "batch.worktrees_cleaned", {
153
+ batchId,
154
+ laneCount,
155
+ });
156
+ }
157
+
55
158
  /**
56
159
  * @param {object} signals
57
160
  */
@@ -160,6 +263,16 @@ export function dismissBatch(ctx) {
160
263
  };
161
264
  }
162
265
 
266
+ const terminatedWorkers = terminateLaneWorkers(loaded.raw.lanes, { hard: true });
267
+ for (const entry of terminatedWorkers) {
268
+ appendJournalEvent(projectRoot, batchId, "lane.worker_terminated", {
269
+ laneNumber: entry.laneNumber,
270
+ workerPid: entry.workerPid,
271
+ signal: entry.signal,
272
+ reason: "batch_dismiss",
273
+ force,
274
+ });
275
+ }
163
276
  const archivePath = archiveBatchState(projectRoot, batchId, loaded.raw);
164
277
  const postMortemPath = writeBatchPostMortem({
165
278
  projectRoot,
@@ -182,12 +295,19 @@ export function dismissBatch(ctx) {
182
295
  archivePath: path.relative(projectRoot, archivePath),
183
296
  });
184
297
  const configResult = loadSpineConfig(projectRoot);
298
+ const config = configResult.config ?? {};
185
299
  recordBatchTerminalMetric({
186
300
  projectRoot,
187
301
  batchId,
188
302
  batchState: { ...loaded.raw, endedAt },
189
303
  diagnosis: diagnosis ?? "dismissed",
190
- config: configResult.config ?? {},
304
+ config,
305
+ });
306
+ cleanupBatchLaneWorktrees({
307
+ projectRoot,
308
+ batchId,
309
+ batchState: loaded.raw,
310
+ config,
191
311
  });
192
312
  clearActiveBatchState(loaded.path);
193
313
 
@@ -342,12 +462,19 @@ export function completeBatch(ctx) {
342
462
  lifecycle: "complete",
343
463
  });
344
464
  const configResult = loadSpineConfig(projectRoot);
465
+ const config = configResult.config ?? {};
345
466
  recordBatchTerminalMetric({
346
467
  projectRoot,
347
468
  batchId,
348
469
  batchState: { ...loaded.raw, endedAt },
349
470
  diagnosis: "completed",
350
- config: configResult.config ?? {},
471
+ config,
472
+ });
473
+ cleanupBatchLaneWorktrees({
474
+ projectRoot,
475
+ batchId,
476
+ batchState: loaded.raw,
477
+ config,
351
478
  });
352
479
  clearActiveBatchState(loaded.path);
353
480