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
@@ -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
+ }
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Safe auto-merge for additive conflicts in docs/adoption/* during lane→orch wave merge.
3
+ * @see GitHub #14 — serial README wave tasks overlapping operator-runbook.md
4
+ */
5
+
6
+ import { execFileSync } from "node:child_process";
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { gitAddFilteredPaths } from "../git-helpers.mjs";
11
+ import { gitExec } from "../git-exec.mjs";
12
+
13
+ export const ADOPTION_DOC_PREFIX = "docs/adoption/";
14
+ export const PRD_DOC_REL_PATH = "docs/PRD.md";
15
+
16
+ /**
17
+ * @param {string} filePath
18
+ */
19
+ export function isAdoptionDocPath(filePath) {
20
+ const normalized = String(filePath ?? "").replace(/\\/g, "/");
21
+ return normalized.startsWith(ADOPTION_DOC_PREFIX);
22
+ }
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
+
32
+ /**
33
+ * @param {string} projectRoot
34
+ * @param {string} filePath
35
+ * @param {1 | 2 | 3} stage
36
+ */
37
+ function readMergeStageContent(projectRoot, filePath, stage) {
38
+ const output = gitExec(
39
+ projectRoot,
40
+ ["show", `:${stage}:${filePath}`],
41
+ { throwOnError: false, projectRoot },
42
+ );
43
+ if (output == null) {
44
+ return null;
45
+ }
46
+ return output;
47
+ }
48
+
49
+ /**
50
+ * @param {string} ours
51
+ * @param {string} base
52
+ * @param {string} theirs
53
+ */
54
+ function runGitMergeFile(ours, base, theirs) {
55
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "spine-adoption-merge-"));
56
+ const oursPath = path.join(tempDir, "ours");
57
+ const basePath = path.join(tempDir, "base");
58
+ const theirsPath = path.join(tempDir, "theirs");
59
+ try {
60
+ fs.writeFileSync(oursPath, ours, "utf-8");
61
+ fs.writeFileSync(basePath, base, "utf-8");
62
+ fs.writeFileSync(theirsPath, theirs, "utf-8");
63
+ let merged = "";
64
+ let exitCode = 0;
65
+ try {
66
+ merged = execFileSync("git", ["merge-file", "-p", oursPath, basePath, theirsPath], {
67
+ encoding: "utf-8",
68
+ stdio: ["ignore", "pipe", "pipe"],
69
+ });
70
+ } catch (err) {
71
+ const execErr = /** @type {NodeJS.ErrnoException & { status?: number, stdout?: string }} */ (err);
72
+ exitCode = Number(execErr.status ?? 1);
73
+ merged = String(execErr.stdout ?? "");
74
+ }
75
+ return { exitCode, merged };
76
+ } finally {
77
+ fs.rmSync(tempDir, { recursive: true, force: true });
78
+ }
79
+ }
80
+
81
+ /**
82
+ * @param {string} merged
83
+ * @returns {string[]}
84
+ */
85
+ function extractConflictHunkLabels(merged) {
86
+ const labels = [];
87
+ const pattern = /^<<<<<<< (.+)$/gm;
88
+ for (const match of merged.matchAll(pattern)) {
89
+ if (match[1]) labels.push(match[1].trim());
90
+ }
91
+ return labels;
92
+ }
93
+
94
+ /**
95
+ * @param {object} params
96
+ * @param {string} params.filePath
97
+ * @param {number} [params.waveIndex]
98
+ * @param {string[]} [params.conflictHunks]
99
+ */
100
+ export function formatAdoptionDocMergeFailure({ filePath, waveIndex, conflictHunks = [] }) {
101
+ const lines = [
102
+ `merge conflict on ${filePath} — adoption doc hunks could not be auto-merged safely`,
103
+ ];
104
+ if (conflictHunks.length > 0) {
105
+ lines.push(`Conflicting hunks: ${conflictHunks.join(", ")}`);
106
+ }
107
+ lines.push(
108
+ "Recovery: resolve conflicts in the lane worktree, commit on the lane branch, then `spine batch resume`",
109
+ );
110
+ if (waveIndex != null && Number.isFinite(waveIndex)) {
111
+ lines.push(
112
+ `Mixed-outcome override only: \`spine batch force-merge --wave ${waveIndex}\` then \`spine batch resume --force\``,
113
+ );
114
+ }
115
+ lines.push(
116
+ "Manual merge path: docs/adoption/operator-runbook.md § Lane merge conflicts; design: docs/design/integrate-conflict-recovery.md",
117
+ );
118
+ return lines.join("\n");
119
+ }
120
+
121
+ /**
122
+ * @param {object} params
123
+ * @param {string} params.filePath
124
+ * @param {number} [params.waveIndex]
125
+ * @param {string[]} [params.conflictHunks]
126
+ */
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(", ")}`);
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
+ }
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
+ }) {
163
+ const base = readMergeStageContent(projectRoot, filePath, 1);
164
+ const ours = readMergeStageContent(projectRoot, filePath, 2);
165
+ const theirs = readMergeStageContent(projectRoot, filePath, 3);
166
+ if (base == null || ours == null || theirs == null) {
167
+ return {
168
+ ok: false,
169
+ failureClass: "MergeConflict",
170
+ error: formatFailure({
171
+ filePath,
172
+ waveIndex,
173
+ conflictHunks: ["missing merge stages"],
174
+ }),
175
+ };
176
+ }
177
+
178
+ const { exitCode, merged } = runGitMergeFile(ours, base, theirs);
179
+ if (exitCode !== 0) {
180
+ const conflictHunks = extractConflictHunkLabels(merged);
181
+ return {
182
+ ok: false,
183
+ failureClass: "MergeConflict",
184
+ error: formatFailure({ filePath, waveIndex, conflictHunks }),
185
+ conflictHunks,
186
+ };
187
+ }
188
+
189
+ const absPath = path.join(projectRoot, filePath);
190
+ fs.mkdirSync(path.dirname(absPath), { recursive: true });
191
+ fs.writeFileSync(absPath, merged, "utf-8");
192
+ gitAddFilteredPaths(projectRoot, [filePath], { projectRoot });
193
+ return {
194
+ ok: true,
195
+ autoResolved: true,
196
+ strategy,
197
+ filePath,
198
+ };
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
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Wave merge bookkeeping — detect waves missing mergeResults entries.
3
+ */
4
+
5
+ /**
6
+ * @param {object} state
7
+ * @returns {Set<number>}
8
+ */
9
+ export function succeededWaveMergeIndices(state) {
10
+ const mergeResults = state.mergeResults ?? [];
11
+ return new Set(
12
+ mergeResults
13
+ .filter((entry) => String(entry?.status ?? "").toLowerCase() === "succeeded")
14
+ .map((entry) => Number(entry.waveIndex))
15
+ .filter((waveIndex) => Number.isFinite(waveIndex)),
16
+ );
17
+ }
18
+
19
+ /**
20
+ * @param {object} state
21
+ * @param {number} waveIndex
22
+ */
23
+ export function waveTasksAllTerminal(state, waveIndex) {
24
+ const waveTaskIds = state.wavePlan?.[waveIndex] ?? [];
25
+ const tasks = state.tasks ?? [];
26
+ if (waveTaskIds.length === 0) {
27
+ return false;
28
+ }
29
+ return waveTaskIds.every((taskId) => {
30
+ const task = tasks.find((entry) => entry?.taskId === taskId);
31
+ if (!task) return false;
32
+ const status = String(task.status ?? "").toLowerCase();
33
+ return status === "succeeded" || status === "skipped";
34
+ });
35
+ }
36
+
37
+ /**
38
+ * First wave index whose tasks are terminal but lacks a succeeded mergeResults row.
39
+ *
40
+ * @param {object} state
41
+ * @returns {number | null}
42
+ */
43
+ export function findFirstWaveNeedingMerge(state) {
44
+ const succeeded = succeededWaveMergeIndices(state);
45
+ const wavePlan = state.wavePlan ?? [];
46
+ for (let waveIndex = 0; waveIndex < wavePlan.length; waveIndex++) {
47
+ if (succeeded.has(waveIndex)) {
48
+ continue;
49
+ }
50
+ if (waveTasksAllTerminal(state, waveIndex)) {
51
+ return waveIndex;
52
+ }
53
+ }
54
+ return null;
55
+ }
56
+
57
+ /**
58
+ * @param {object} state
59
+ */
60
+ export function hasPendingWaveMerge(state) {
61
+ return findFirstWaveNeedingMerge(state) != null;
62
+ }
63
+
64
+ /**
65
+ * @param {object} state
66
+ * @param {number} waveIndex
67
+ */
68
+ export function isWaveForceMerged(state, waveIndex) {
69
+ return (state.resilience?.forceMergedWaves ?? []).includes(waveIndex);
70
+ }
71
+
72
+ /**
73
+ * @param {object} params
74
+ * @param {object} params.state
75
+ * @param {number} params.waveIndex
76
+ * @param {"succeeded" | "failed"} params.status
77
+ * @param {string | null} [params.mergeCommit]
78
+ * @param {number | null} [params.failedLane]
79
+ * @param {string | null} [params.failureReason]
80
+ * @param {string | null} [params.failureClass]
81
+ */
82
+ export function recordWaveMergeResult({
83
+ state,
84
+ waveIndex,
85
+ status,
86
+ mergeCommit = null,
87
+ failedLane = null,
88
+ failureReason = null,
89
+ failureClass = null,
90
+ }) {
91
+ state.mergeResults = state.mergeResults ?? [];
92
+ const existingIndex = state.mergeResults.findIndex((entry) => entry?.waveIndex === waveIndex);
93
+ const row = {
94
+ waveIndex,
95
+ status,
96
+ forceMerged: isWaveForceMerged(state, waveIndex),
97
+ failedLane,
98
+ failureReason,
99
+ failureClass,
100
+ mergeCommit,
101
+ };
102
+ if (existingIndex >= 0) {
103
+ state.mergeResults[existingIndex] = { ...state.mergeResults[existingIndex], ...row };
104
+ } else {
105
+ state.mergeResults.push(row);
106
+ }
107
+ return row;
108
+ }
@@ -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