pi-spine 1.1.0 → 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 (102) hide show
  1. package/bin/spine-batch.mjs +160 -53
  2. package/bin/spine-cli/batch.mjs +3 -3
  3. package/bin/spine-cli/lane-logs.mjs +24 -0
  4. package/bin/spine-cli/scenarios.mjs +298 -0
  5. package/bin/spine-cli/wait.mjs +30 -0
  6. package/bin/spine-cli/watch.mjs +27 -0
  7. package/bin/spine-issue.mjs +196 -0
  8. package/bin/spine-journal.mjs +1 -0
  9. package/bin/spine-run.mjs +30 -0
  10. package/bin/spine-status.mjs +19 -1
  11. package/bin/spine-tasks.mjs +16 -2
  12. package/bin/spine-worker-runner.mjs +10 -10
  13. package/bin/spine.mjs +49 -1
  14. package/package.json +1 -1
  15. package/skills/create-spine-tasks/references/contract-template.md +19 -0
  16. package/src/batch/abort.mjs +2 -11
  17. package/src/batch/agent-session-worker.mjs +45 -5
  18. package/src/batch/attached-engine-handoff.mjs +188 -0
  19. package/src/batch/attached-runner.mjs +312 -0
  20. package/src/batch/contract-prelanded.mjs +180 -0
  21. package/src/batch/contract-verify.mjs +140 -2
  22. package/src/batch/detached-start.mjs +66 -2
  23. package/src/batch/diagnosis-alternatives.mjs +46 -0
  24. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  25. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  26. package/src/batch/diagnosis-stub.mjs +109 -0
  27. package/src/batch/diagnosis-task-done.mjs +110 -0
  28. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  29. package/src/batch/diagnosis.mjs +135 -68
  30. package/src/batch/engine-lanes/merge.mjs +110 -82
  31. package/src/batch/engine-lanes/queue.mjs +4 -1
  32. package/src/batch/engine-lanes/watch.mjs +29 -0
  33. package/src/batch/engine-lanes.mjs +1 -0
  34. package/src/batch/engine-scope.mjs +11 -1
  35. package/src/batch/engine.mjs +79 -24
  36. package/src/batch/evidence.mjs +78 -15
  37. package/src/batch/gate.mjs +43 -14
  38. package/src/batch/git-helpers.mjs +96 -0
  39. package/src/batch/heartbeat.mjs +73 -7
  40. package/src/batch/integrate.mjs +2 -4
  41. package/src/batch/journal.mjs +3 -0
  42. package/src/batch/lane-commit.mjs +90 -5
  43. package/src/batch/lifecycle.mjs +130 -3
  44. package/src/batch/macro-phase.mjs +226 -0
  45. package/src/batch/merge/adoption-doc-merge.mjs +93 -10
  46. package/src/batch/merge/wave-merge-state.mjs +3 -0
  47. package/src/batch/metrics.mjs +74 -5
  48. package/src/batch/orphan-detect.mjs +74 -0
  49. package/src/batch/pause.mjs +223 -0
  50. package/src/batch/post-merge-limbo.mjs +264 -8
  51. package/src/batch/reconcile.mjs +429 -54
  52. package/src/batch/resume-common.mjs +5 -1
  53. package/src/batch/resume-lane-reviews.mjs +16 -0
  54. package/src/batch/resume-multi-lanes.mjs +56 -1
  55. package/src/batch/resume-multi-validate.mjs +67 -6
  56. package/src/batch/resume-multi.mjs +9 -4
  57. package/src/batch/resume.mjs +52 -45
  58. package/src/batch/retry.mjs +56 -5
  59. package/src/batch/review-spawn.mjs +8 -2
  60. package/src/batch/rules-manifest-drift.mjs +157 -0
  61. package/src/batch/salvage.mjs +2 -1
  62. package/src/batch/sequence.mjs +454 -0
  63. package/src/batch/state.mjs +18 -3
  64. package/src/batch/status-json.mjs +67 -0
  65. package/src/batch/task-stall-budget.mjs +22 -10
  66. package/src/batch/worker-host.mjs +95 -7
  67. package/src/batch/worker-output.mjs +196 -3
  68. package/src/cli/issue-draft.mjs +180 -0
  69. package/src/cli/journal-follow.mjs +239 -0
  70. package/src/cli/lane-logs.mjs +291 -0
  71. package/src/cli/sequence.mjs +108 -0
  72. package/src/cli/settings-set.mjs +2 -21
  73. package/src/cli/wait.mjs +187 -0
  74. package/src/cli/watch.mjs +160 -0
  75. package/src/config/agent-model-resolve.mjs +48 -0
  76. package/src/config/cursor-rules/discover.mjs +3 -21
  77. package/src/config/defaults.mjs +7 -1
  78. package/src/config/settings-fields.mjs +48 -0
  79. package/src/config/spine-init-constants.mjs +1 -0
  80. package/src/config/spine-preflight-lib.mjs +471 -16
  81. package/src/dashboard/lane-throughput.mjs +351 -0
  82. package/src/dashboard/public/dashboard.css +25 -1
  83. package/src/dashboard/public/dashboard.js +223 -18
  84. package/src/dashboard/public/index.html +14 -2
  85. package/src/dashboard/server.mjs +4 -0
  86. package/src/dashboard/snapshot.mjs +215 -1
  87. package/src/dashboard/view.mjs +170 -17
  88. package/src/doctor/agent-model-inherit.mjs +61 -6
  89. package/src/doctor/run-doctor-checks.mjs +26 -1
  90. package/src/doctor/sequence-safety.mjs +57 -0
  91. package/src/doctor/stale-worktrees.mjs +102 -0
  92. package/src/fixtures/scenario-registry.mjs +194 -0
  93. package/src/fs/atomic-write.mjs +49 -0
  94. package/src/planner/file-scope.mjs +246 -0
  95. package/src/planner/format-plan.mjs +9 -7
  96. package/src/planner/index.mjs +6 -2
  97. package/src/planner/wave-scope.mjs +136 -0
  98. package/src/planner/waves.mjs +133 -0
  99. package/src/tasks/packet/index.mjs +1 -0
  100. package/src/tasks/packet/parse-prompt.mjs +42 -1
  101. package/src/tasks/packet/validate-prompt.mjs +124 -0
  102. package/templates/spine-config.json +8 -1
@@ -10,11 +10,72 @@ 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
 
@@ -0,0 +1,226 @@
1
+ /**
2
+ * Batch macro-phase derivation (Phase 41 — operator lifecycle label).
3
+ *
4
+ * Maps reconciliation signals to a stable macro-phase enum distinct from
5
+ * diagnosis (actionable) and lane activityPhase (per-lane detail).
6
+ *
7
+ * Mapping table (priority top → bottom; first match wins):
8
+ *
9
+ * | Macro phase | Signals |
10
+ * |--------------|---------|
11
+ * | idle | diagnosis null/undefined (no active batch) |
12
+ * | aborted | batchPhase or diagnosis `aborted` |
13
+ * | failed | batchPhase `failed`, or terminal-failure diagnoses (needs_retry, worker_orphaned, …) |
14
+ * | paused | batchPhase or diagnosis `paused` (when not failed) |
15
+ * | gating | integrate gate record `pending`, or postMergeLimbo awaiting operator gate approval |
16
+ * | integrating | open `integrate.started` journal event, or diagnosis `needs_integrate` |
17
+ * | completed | batchPhase `completed` without integrate pending, or diagnosis `completed` / `completed_manual` / `limbo_stale` |
18
+ * | merging | batchPhase `merging`, or diagnosis `needs_merge` |
19
+ * | reviewing | open `review.started` without matching `review.completed` / `review.failed` |
20
+ * | planning | batchPhase `planning` |
21
+ * | executing | default for active batch (running diagnosis, running/executing phase) |
22
+ */
23
+
24
+ /** @typedef {(typeof MACRO_PHASES)[number]} MacroPhase */
25
+
26
+ export const MACRO_PHASES = /** @type {const} */ ([
27
+ "idle",
28
+ "planning",
29
+ "executing",
30
+ "merging",
31
+ "reviewing",
32
+ "gating",
33
+ "integrating",
34
+ "completed",
35
+ "failed",
36
+ "aborted",
37
+ "paused",
38
+ ]);
39
+
40
+ /** @type {Record<MacroPhase, string>} */
41
+ export const MACRO_PHASE_LABELS = {
42
+ idle: "Idle",
43
+ planning: "Planning",
44
+ executing: "Executing",
45
+ merging: "Merging",
46
+ reviewing: "Reviewing",
47
+ gating: "Gating",
48
+ integrating: "Integrating",
49
+ completed: "Completed",
50
+ failed: "Failed",
51
+ aborted: "Aborted",
52
+ paused: "Paused",
53
+ };
54
+
55
+ const COMPLETED_DIAGNOSES = new Set(["completed", "completed_manual", "limbo_stale"]);
56
+
57
+ const FAILED_DIAGNOSES = new Set([
58
+ "failed",
59
+ "needs_retry",
60
+ "worker_orphaned",
61
+ "engine_orphaned",
62
+ "state_drift",
63
+ "worker_done_missing",
64
+ "needs_replan",
65
+ "git_unavailable",
66
+ ]);
67
+
68
+ const INTEGRATE_EVENT_TYPES = new Set(["integrate.started", "integrate.completed", "integrate.failed"]);
69
+
70
+ /**
71
+ * @param {string|null|undefined} phase
72
+ * @returns {phase is MacroPhase}
73
+ */
74
+ export function isMacroPhase(phase) {
75
+ return MACRO_PHASES.includes(/** @type {MacroPhase} */ (phase));
76
+ }
77
+
78
+ /**
79
+ * @param {MacroPhase} phase
80
+ * @returns {string}
81
+ */
82
+ export function macroPhaseLabel(phase) {
83
+ return MACRO_PHASE_LABELS[phase] ?? String(phase);
84
+ }
85
+
86
+ /**
87
+ * @param {object} event
88
+ * @returns {string|null}
89
+ */
90
+ function journalEventTaskId(event) {
91
+ if (typeof event.taskId === "string" && event.taskId) return event.taskId;
92
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
93
+ return typeof payload.taskId === "string" ? payload.taskId : null;
94
+ }
95
+
96
+ /**
97
+ * @param {object[]} journalEvents
98
+ * @returns {boolean}
99
+ */
100
+ function hasOpenReview(journalEvents) {
101
+ if (!Array.isArray(journalEvents) || journalEvents.length === 0) return false;
102
+
103
+ /** @type {Map<string, { taskId: string, reviewType: string, stepNumber: unknown }>} */
104
+ const openReviews = new Map();
105
+
106
+ for (const event of journalEvents) {
107
+ if (event.type === "review.started") {
108
+ const taskId = journalEventTaskId(event);
109
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
110
+ const reviewType = payload.reviewType;
111
+ if (!taskId || typeof reviewType !== "string") continue;
112
+ const key = `${taskId}:${reviewType}:${String(payload.stepNumber ?? "")}`;
113
+ openReviews.set(key, { taskId, reviewType, stepNumber: payload.stepNumber });
114
+ continue;
115
+ }
116
+
117
+ if (event.type !== "review.completed" && event.type !== "review.failed") continue;
118
+
119
+ const taskId = journalEventTaskId(event);
120
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
121
+ const reviewType = payload.reviewType;
122
+ if (!taskId || typeof reviewType !== "string") continue;
123
+ const key = `${taskId}:${reviewType}:${String(payload.stepNumber ?? "")}`;
124
+ openReviews.delete(key);
125
+ }
126
+
127
+ return openReviews.size > 0;
128
+ }
129
+
130
+ /**
131
+ * @param {object[]} journalEvents
132
+ * @returns {boolean}
133
+ */
134
+ function hasOpenIntegrate(journalEvents) {
135
+ if (!Array.isArray(journalEvents) || journalEvents.length === 0) return false;
136
+
137
+ let lastIntegrateIdx = -1;
138
+ let lastIntegrateType = null;
139
+
140
+ for (let index = 0; index < journalEvents.length; index += 1) {
141
+ const type = journalEvents[index]?.type;
142
+ if (typeof type === "string" && INTEGRATE_EVENT_TYPES.has(type)) {
143
+ lastIntegrateIdx = index;
144
+ lastIntegrateType = type;
145
+ }
146
+ }
147
+
148
+ return lastIntegrateIdx >= 0 && lastIntegrateType === "integrate.started";
149
+ }
150
+
151
+ /**
152
+ * @param {object|null|undefined} gateRecord
153
+ * @param {boolean} postMergeLimbo
154
+ * @param {string|null|undefined} diagnosis
155
+ * @returns {boolean}
156
+ */
157
+ function isGatingState(gateRecord, postMergeLimbo, diagnosis) {
158
+ if (gateRecord && gateRecord.status === "pending") return true;
159
+ if (postMergeLimbo && diagnosis === "needs_integrate") return true;
160
+ return false;
161
+ }
162
+
163
+ /**
164
+ * @typedef {object} DeriveMacroPhaseInput
165
+ * @property {string|null|undefined} diagnosis
166
+ * @property {string|null|undefined} batchPhase
167
+ * @property {number|null|undefined} [currentWaveIndex]
168
+ * @property {unknown[]} [mergeResults]
169
+ * @property {object|null|undefined} [gateRecord]
170
+ * @property {boolean} [postMergeLimbo]
171
+ * @property {object[]} [journalEvents]
172
+ */
173
+
174
+ /**
175
+ * @param {DeriveMacroPhaseInput} input
176
+ * @returns {MacroPhase}
177
+ */
178
+ export function deriveMacroPhase(input) {
179
+ const diagnosis = input.diagnosis ?? null;
180
+ const batchPhase = input.batchPhase ?? null;
181
+ const postMergeLimbo = input.postMergeLimbo === true;
182
+ const journalEvents = input.journalEvents ?? [];
183
+ const gateRecord = input.gateRecord ?? null;
184
+
185
+ if (diagnosis == null && batchPhase == null) {
186
+ return "idle";
187
+ }
188
+
189
+ if (batchPhase === "aborted" || diagnosis === "aborted") {
190
+ return "aborted";
191
+ }
192
+
193
+ if (batchPhase === "failed" || batchPhase === "merge_blocked" || (diagnosis != null && FAILED_DIAGNOSES.has(diagnosis))) {
194
+ return "failed";
195
+ }
196
+
197
+ if (batchPhase === "paused" || diagnosis === "paused") {
198
+ return "paused";
199
+ }
200
+
201
+ if (isGatingState(gateRecord, postMergeLimbo, diagnosis)) {
202
+ return "gating";
203
+ }
204
+
205
+ if (hasOpenIntegrate(journalEvents) || diagnosis === "needs_integrate") {
206
+ return "integrating";
207
+ }
208
+
209
+ if (batchPhase === "completed" || (diagnosis != null && COMPLETED_DIAGNOSES.has(diagnosis))) {
210
+ return "completed";
211
+ }
212
+
213
+ if (batchPhase === "merging" || diagnosis === "needs_merge") {
214
+ return "merging";
215
+ }
216
+
217
+ if (hasOpenReview(journalEvents)) {
218
+ return "reviewing";
219
+ }
220
+
221
+ if (batchPhase === "planning") {
222
+ return "planning";
223
+ }
224
+
225
+ return "executing";
226
+ }
@@ -7,9 +7,11 @@ import { execFileSync } from "node:child_process";
7
7
  import fs from "node:fs";
8
8
  import os from "node:os";
9
9
  import path from "node:path";
10
+ import { gitAddFilteredPaths } from "../git-helpers.mjs";
10
11
  import { gitExec } from "../git-exec.mjs";
11
12
 
12
13
  export const ADOPTION_DOC_PREFIX = "docs/adoption/";
14
+ export const PRD_DOC_REL_PATH = "docs/PRD.md";
13
15
 
14
16
  /**
15
17
  * @param {string} filePath
@@ -19,6 +21,14 @@ export function isAdoptionDocPath(filePath) {
19
21
  return normalized.startsWith(ADOPTION_DOC_PREFIX);
20
22
  }
21
23
 
24
+ /**
25
+ * @param {string} filePath
26
+ */
27
+ export function isPrdDocPath(filePath) {
28
+ const normalized = String(filePath ?? "").replace(/\\/g, "/");
29
+ return normalized === PRD_DOC_REL_PATH;
30
+ }
31
+
22
32
  /**
23
33
  * @param {string} projectRoot
24
34
  * @param {string} filePath
@@ -109,18 +119,47 @@ export function formatAdoptionDocMergeFailure({ filePath, waveIndex, conflictHun
109
119
  }
110
120
 
111
121
  /**
112
- * Attempt 3-way merge for docs/adoption/* using git merge-file (non-overlapping additive edits).
113
- *
114
122
  * @param {object} params
115
- * @param {string} params.projectRoot
116
123
  * @param {string} params.filePath
117
124
  * @param {number} [params.waveIndex]
125
+ * @param {string[]} [params.conflictHunks]
118
126
  */
119
- export function tryResolveAdoptionDocMergeConflict({ projectRoot, filePath, waveIndex }) {
120
- if (!isAdoptionDocPath(filePath)) {
121
- return { ok: false, reason: "not_adoption_doc" };
127
+ export function formatPrdDocMergeFailure({ filePath, waveIndex, conflictHunks = [] }) {
128
+ const lines = [
129
+ `merge conflict on ${filePath} — release-recovery PRD hunks could not be auto-merged safely`,
130
+ ];
131
+ if (conflictHunks.length > 0) {
132
+ lines.push(`Conflicting hunks: ${conflictHunks.join(", ")}`);
122
133
  }
134
+ lines.push(
135
+ "Recovery: in the lane worktree resolve docs/PRD.md, commit on the lane branch, then `spine batch resume`",
136
+ );
137
+ if (waveIndex != null && Number.isFinite(waveIndex)) {
138
+ lines.push(
139
+ `Mixed-outcome override only: \`spine batch force-merge --wave ${waveIndex}\` then \`spine batch resume --force\``,
140
+ );
141
+ }
142
+ lines.push(
143
+ "Manual merge path: docs/adoption/operator-runbook.md § Lane merge conflicts; design: docs/design/integrate-conflict-recovery.md",
144
+ );
145
+ return lines.join("\n");
146
+ }
123
147
 
148
+ /**
149
+ * @param {object} params
150
+ * @param {string} params.projectRoot
151
+ * @param {string} params.filePath
152
+ * @param {number} [params.waveIndex]
153
+ * @param {(failure: { filePath: string, waveIndex?: number, conflictHunks?: string[] }) => string} params.formatFailure
154
+ * @param {string} params.strategy
155
+ */
156
+ function tryResolveAdditiveDocMergeConflict({
157
+ projectRoot,
158
+ filePath,
159
+ waveIndex,
160
+ formatFailure,
161
+ strategy,
162
+ }) {
124
163
  const base = readMergeStageContent(projectRoot, filePath, 1);
125
164
  const ours = readMergeStageContent(projectRoot, filePath, 2);
126
165
  const theirs = readMergeStageContent(projectRoot, filePath, 3);
@@ -128,7 +167,7 @@ export function tryResolveAdoptionDocMergeConflict({ projectRoot, filePath, wave
128
167
  return {
129
168
  ok: false,
130
169
  failureClass: "MergeConflict",
131
- error: formatAdoptionDocMergeFailure({
170
+ error: formatFailure({
132
171
  filePath,
133
172
  waveIndex,
134
173
  conflictHunks: ["missing merge stages"],
@@ -142,7 +181,7 @@ export function tryResolveAdoptionDocMergeConflict({ projectRoot, filePath, wave
142
181
  return {
143
182
  ok: false,
144
183
  failureClass: "MergeConflict",
145
- error: formatAdoptionDocMergeFailure({ filePath, waveIndex, conflictHunks }),
184
+ error: formatFailure({ filePath, waveIndex, conflictHunks }),
146
185
  conflictHunks,
147
186
  };
148
187
  }
@@ -150,11 +189,55 @@ export function tryResolveAdoptionDocMergeConflict({ projectRoot, filePath, wave
150
189
  const absPath = path.join(projectRoot, filePath);
151
190
  fs.mkdirSync(path.dirname(absPath), { recursive: true });
152
191
  fs.writeFileSync(absPath, merged, "utf-8");
153
- gitExec(projectRoot, ["add", "--", filePath], { projectRoot });
192
+ gitAddFilteredPaths(projectRoot, [filePath], { projectRoot });
154
193
  return {
155
194
  ok: true,
156
195
  autoResolved: true,
157
- strategy: "adoption_doc_merge_file",
196
+ strategy,
158
197
  filePath,
159
198
  };
160
199
  }
200
+
201
+ /**
202
+ * Attempt 3-way merge for docs/adoption/* using git merge-file (non-overlapping additive edits).
203
+ *
204
+ * @param {object} params
205
+ * @param {string} params.projectRoot
206
+ * @param {string} params.filePath
207
+ * @param {number} [params.waveIndex]
208
+ */
209
+ export function tryResolveAdoptionDocMergeConflict({ projectRoot, filePath, waveIndex }) {
210
+ if (!isAdoptionDocPath(filePath)) {
211
+ return { ok: false, reason: "not_adoption_doc" };
212
+ }
213
+
214
+ return tryResolveAdditiveDocMergeConflict({
215
+ projectRoot,
216
+ filePath,
217
+ waveIndex,
218
+ formatFailure: formatAdoptionDocMergeFailure,
219
+ strategy: "adoption_doc_merge_file",
220
+ });
221
+ }
222
+
223
+ /**
224
+ * Attempt 3-way merge for docs/PRD.md (release-recovery origin/main merges).
225
+ *
226
+ * @param {object} params
227
+ * @param {string} params.projectRoot
228
+ * @param {string} params.filePath
229
+ * @param {number} [params.waveIndex]
230
+ */
231
+ export function tryResolvePrdDocMergeConflict({ projectRoot, filePath, waveIndex }) {
232
+ if (!isPrdDocPath(filePath)) {
233
+ return { ok: false, reason: "not_prd_doc" };
234
+ }
235
+
236
+ return tryResolveAdditiveDocMergeConflict({
237
+ projectRoot,
238
+ filePath,
239
+ waveIndex,
240
+ formatFailure: formatPrdDocMergeFailure,
241
+ strategy: "prd_doc_merge_file",
242
+ });
243
+ }
@@ -77,6 +77,7 @@ export function isWaveForceMerged(state, waveIndex) {
77
77
  * @param {string | null} [params.mergeCommit]
78
78
  * @param {number | null} [params.failedLane]
79
79
  * @param {string | null} [params.failureReason]
80
+ * @param {string | null} [params.failureClass]
80
81
  */
81
82
  export function recordWaveMergeResult({
82
83
  state,
@@ -85,6 +86,7 @@ export function recordWaveMergeResult({
85
86
  mergeCommit = null,
86
87
  failedLane = null,
87
88
  failureReason = null,
89
+ failureClass = null,
88
90
  }) {
89
91
  state.mergeResults = state.mergeResults ?? [];
90
92
  const existingIndex = state.mergeResults.findIndex((entry) => entry?.waveIndex === waveIndex);
@@ -94,6 +96,7 @@ export function recordWaveMergeResult({
94
96
  forceMerged: isWaveForceMerged(state, waveIndex),
95
97
  failedLane,
96
98
  failureReason,
99
+ failureClass,
97
100
  mergeCommit,
98
101
  };
99
102
  if (existingIndex >= 0) {
@@ -4,6 +4,7 @@
4
4
 
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
+ import { execFileSync } from "node:child_process";
7
8
  import { METRICS_DEFAULTS } from "../config/defaults.mjs";
8
9
  import { readReviewLevel } from "./review.mjs";
9
10
 
@@ -25,6 +26,57 @@ export function metricsFilePath(projectRoot, config = {}) {
25
26
  return path.join(projectRoot, relPath);
26
27
  }
27
28
 
29
+ /**
30
+ * True when the only dirty path is the configured metrics file and working tree is append-only vs HEAD.
31
+ *
32
+ * @param {string} projectRoot
33
+ * @param {string[]} dirtyPaths Trimmed paths from `git status --porcelain` (no status prefix).
34
+ * @param {string} [metricsRelPath]
35
+ * @returns {{ ok: boolean, reason?: string, metricsPath?: string }}
36
+ */
37
+ export function isRunMetricsAppendOnlyDrift(
38
+ projectRoot,
39
+ dirtyPaths,
40
+ metricsRelPath = METRICS_DEFAULTS.path,
41
+ ) {
42
+ const normalizedDirty = (dirtyPaths ?? [])
43
+ .map((entry) => String(entry).trim().replace(/\\/g, "/"))
44
+ .filter(Boolean);
45
+ if (normalizedDirty.length !== 1) {
46
+ return { ok: false, reason: "not_metrics_only" };
47
+ }
48
+
49
+ const normalizedMetrics = String(metricsRelPath).trim().replace(/\\/g, "/");
50
+ const dirtyPath = normalizedDirty[0].replace(/\\/g, "/");
51
+ if (dirtyPath !== normalizedMetrics) {
52
+ return { ok: false, reason: "not_metrics_path" };
53
+ }
54
+
55
+ const filePath = path.join(projectRoot, normalizedMetrics);
56
+ if (!fs.existsSync(filePath)) {
57
+ return { ok: false, reason: "metrics_missing" };
58
+ }
59
+
60
+ let headText = "";
61
+ try {
62
+ headText = execFileSync("git", ["show", `HEAD:${normalizedMetrics}`], {
63
+ cwd: projectRoot,
64
+ encoding: "utf-8",
65
+ stdio: ["ignore", "pipe", "pipe"],
66
+ timeout: 5000,
67
+ });
68
+ } catch {
69
+ return { ok: false, reason: "no_head_metrics" };
70
+ }
71
+
72
+ const workText = fs.readFileSync(filePath, "utf-8");
73
+ if (!workText.startsWith(headText)) {
74
+ return { ok: false, reason: "non_append_change" };
75
+ }
76
+
77
+ return { ok: true, metricsPath: normalizedMetrics };
78
+ }
79
+
28
80
  /**
29
81
  * @param {unknown} value
30
82
  * @returns {unknown}
@@ -77,9 +129,13 @@ export function resolveTaskMetricOutcome(task) {
77
129
  * @param {object} [params.config]
78
130
  * @param {string} [params.taskFolder]
79
131
  */
80
- export function buildTaskMetricRecord({ batchId, task, config = {}, taskFolder }) {
132
+ export function buildTaskMetricRecord({ batchId, task, config = {}, taskFolder, laneNumber }) {
81
133
  const worker = config?.agents?.worker ?? {};
82
134
  const reviewLevel = taskFolder ? readReviewLevel(taskFolder) : Number(task.reviewLevel ?? 0);
135
+ const startedMs = Number(task.startedAt ?? Date.now());
136
+ const endedMs = Number(task.endedAt ?? Date.now());
137
+ const resolvedLaneNumber =
138
+ laneNumber ?? (Number.isFinite(task.laneNumber) ? task.laneNumber : undefined);
83
139
 
84
140
  /** @type {Record<string, unknown>} */
85
141
  const record = {
@@ -96,11 +152,17 @@ export function buildTaskMetricRecord({ batchId, task, config = {}, taskFolder }
96
152
  worker.thinking === "high"
97
153
  ? worker.thinking
98
154
  : "high",
99
- startedAt: new Date(task.startedAt ?? Date.now()).toISOString(),
100
- endedAt: new Date(task.endedAt ?? Date.now()).toISOString(),
155
+ startedAt: new Date(startedMs).toISOString(),
156
+ endedAt: new Date(endedMs).toISOString(),
101
157
  outcome: resolveTaskMetricOutcome(task),
102
158
  };
103
159
 
160
+ if (Number.isFinite(resolvedLaneNumber) && resolvedLaneNumber > 0) {
161
+ record.laneNumber = resolvedLaneNumber;
162
+ }
163
+ if (Number.isFinite(startedMs) && Number.isFinite(endedMs)) {
164
+ record.durationMs = Math.max(0, endedMs - startedMs);
165
+ }
104
166
  if (task.exitReason) record.exitReason = task.exitReason;
105
167
  if (reviewLevel > 0) record.reviewLevel = reviewLevel;
106
168
  if (task.finalVerdict != null) record.finalVerdict = task.finalVerdict;
@@ -134,9 +196,16 @@ export function appendTaskMetric(projectRoot, record, config = {}) {
134
196
  * @param {object} [params.config]
135
197
  * @param {string} [params.taskFolder]
136
198
  */
137
- export function recordTaskTerminalMetric({ projectRoot, batchId, task, config = {}, taskFolder }) {
199
+ export function recordTaskTerminalMetric({
200
+ projectRoot,
201
+ batchId,
202
+ task,
203
+ config = {},
204
+ taskFolder,
205
+ laneNumber,
206
+ }) {
138
207
  if (!isMetricsEnabled(config)) return null;
139
- const record = buildTaskMetricRecord({ batchId, task, config, taskFolder });
208
+ const record = buildTaskMetricRecord({ batchId, task, config, taskFolder, laneNumber });
140
209
  return appendTaskMetric(projectRoot, record, config);
141
210
  }
142
211