pi-spine 1.0.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 (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +563 -0
  3. package/bin/get-version.mjs +35 -0
  4. package/bin/spine-batch.mjs +425 -0
  5. package/bin/spine-cli/batch.mjs +47 -0
  6. package/bin/spine-cli/gate.mjs +10 -0
  7. package/bin/spine-cli/integrate.mjs +10 -0
  8. package/bin/spine-cli/plan.mjs +12 -0
  9. package/bin/spine-cli/shared.mjs +73 -0
  10. package/bin/spine-cli/status.mjs +18 -0
  11. package/bin/spine-cli/verify.mjs +199 -0
  12. package/bin/spine-config.mjs +212 -0
  13. package/bin/spine-dashboard.mjs +178 -0
  14. package/bin/spine-deps.mjs +69 -0
  15. package/bin/spine-doctor.mjs +468 -0
  16. package/bin/spine-gate.mjs +137 -0
  17. package/bin/spine-init.mjs +398 -0
  18. package/bin/spine-integrate.mjs +77 -0
  19. package/bin/spine-journal.mjs +198 -0
  20. package/bin/spine-migrate-from-taskplane.mjs +136 -0
  21. package/bin/spine-plan.mjs +83 -0
  22. package/bin/spine-preflight.mjs +700 -0
  23. package/bin/spine-report-progress.d.mts +28 -0
  24. package/bin/spine-report-progress.mjs +126 -0
  25. package/bin/spine-review-step.d.mts +24 -0
  26. package/bin/spine-review-step.mjs +124 -0
  27. package/bin/spine-rules.mjs +35 -0
  28. package/bin/spine-settings.mjs +186 -0
  29. package/bin/spine-state.mjs +110 -0
  30. package/bin/spine-status.mjs +79 -0
  31. package/bin/spine-tasks.mjs +293 -0
  32. package/bin/spine-worker-runner.mjs +314 -0
  33. package/bin/spine.mjs +404 -0
  34. package/extensions/spine/settings-slash.ts +20 -0
  35. package/extensions/spine/slash-commands.ts +806 -0
  36. package/extensions/spine/worker-tools.ts +279 -0
  37. package/extensions/spine-orchestrator.ts +12 -0
  38. package/package.json +72 -0
  39. package/skills/.gitkeep +0 -0
  40. package/skills/create-spine-tasks/SKILL.md +375 -0
  41. package/skills/create-spine-tasks/references/context-template.md +25 -0
  42. package/skills/create-spine-tasks/references/contract-template.md +98 -0
  43. package/skills/create-spine-tasks/references/explore-template.md +63 -0
  44. package/skills/create-spine-tasks/references/prompt-template.md +276 -0
  45. package/src/batch/abort.mjs +272 -0
  46. package/src/batch/agent-session-worker.mjs +297 -0
  47. package/src/batch/batch-state-io.mjs +53 -0
  48. package/src/batch/contract-verify.mjs +310 -0
  49. package/src/batch/detached-start.mjs +778 -0
  50. package/src/batch/diagnosis.mjs +378 -0
  51. package/src/batch/engine-lanes/merge.mjs +632 -0
  52. package/src/batch/engine-lanes/queue.mjs +208 -0
  53. package/src/batch/engine-lanes/review.mjs +970 -0
  54. package/src/batch/engine-lanes.mjs +388 -0
  55. package/src/batch/engine-scope.mjs +251 -0
  56. package/src/batch/engine.mjs +445 -0
  57. package/src/batch/evidence-command.mjs +157 -0
  58. package/src/batch/evidence.mjs +203 -0
  59. package/src/batch/gate.mjs +359 -0
  60. package/src/batch/git-commit-env.mjs +46 -0
  61. package/src/batch/git-exec.mjs +26 -0
  62. package/src/batch/heartbeat.mjs +430 -0
  63. package/src/batch/integrate.mjs +414 -0
  64. package/src/batch/journal-rebuild.mjs +388 -0
  65. package/src/batch/journal.mjs +373 -0
  66. package/src/batch/lane-commit.mjs +153 -0
  67. package/src/batch/lifecycle.mjs +364 -0
  68. package/src/batch/metrics.mjs +265 -0
  69. package/src/batch/orphan-detect.mjs +210 -0
  70. package/src/batch/post-merge-limbo.mjs +80 -0
  71. package/src/batch/postmortem.mjs +296 -0
  72. package/src/batch/readers/spine-state.mjs +95 -0
  73. package/src/batch/readers/taskplane-state.mjs +136 -0
  74. package/src/batch/reconcile.mjs +729 -0
  75. package/src/batch/resume-common.mjs +104 -0
  76. package/src/batch/resume-engine.mjs +66 -0
  77. package/src/batch/resume-multi-lanes.mjs +479 -0
  78. package/src/batch/resume-multi-validate.mjs +187 -0
  79. package/src/batch/resume-multi.mjs +254 -0
  80. package/src/batch/resume.mjs +475 -0
  81. package/src/batch/retry.mjs +257 -0
  82. package/src/batch/review-scope.mjs +136 -0
  83. package/src/batch/review.mjs +1045 -0
  84. package/src/batch/salvage.mjs +332 -0
  85. package/src/batch/state.mjs +680 -0
  86. package/src/batch/task-stall-budget.mjs +88 -0
  87. package/src/batch/worker-host.mjs +683 -0
  88. package/src/batch/worker-output.mjs +253 -0
  89. package/src/batch/worker-prompt.mjs +84 -0
  90. package/src/batch/worktree.mjs +290 -0
  91. package/src/cli/deps.mjs +141 -0
  92. package/src/cli/handoff.mjs +364 -0
  93. package/src/cli/rules.mjs +429 -0
  94. package/src/cli/settings-set.mjs +171 -0
  95. package/src/cli/settings-show.mjs +140 -0
  96. package/src/cli/settings-slash.mjs +107 -0
  97. package/src/config/contract.mjs +56 -0
  98. package/src/config/cursor-rules/discover.mjs +416 -0
  99. package/src/config/cursor-rules/index.mjs +39 -0
  100. package/src/config/cursor-rules/match-globs.mjs +132 -0
  101. package/src/config/cursor-rules/parse-frontmatter.mjs +222 -0
  102. package/src/config/cursor-rules/priority.mjs +26 -0
  103. package/src/config/cursor-rules/profile.mjs +403 -0
  104. package/src/config/cursor-rules/select.mjs +259 -0
  105. package/src/config/defaults.mjs +36 -0
  106. package/src/config/env-overrides.mjs +207 -0
  107. package/src/config/merge-defaults.mjs +47 -0
  108. package/src/config/pi-spine-root.mjs +93 -0
  109. package/src/config/reviewer-context.mjs +243 -0
  110. package/src/config/settings-fields.mjs +265 -0
  111. package/src/config/worker-backend.mjs +116 -0
  112. package/src/config/worker-context.mjs +402 -0
  113. package/src/config/worker-launch-script.mjs +130 -0
  114. package/src/config/worktree-setup-hook.mjs +122 -0
  115. package/src/dashboard/public/dashboard.css +77 -0
  116. package/src/dashboard/public/dashboard.js +349 -0
  117. package/src/dashboard/public/index.html +80 -0
  118. package/src/dashboard/server.mjs +155 -0
  119. package/src/dashboard/snapshot.mjs +414 -0
  120. package/src/dashboard/sse.mjs +15 -0
  121. package/src/dashboard/view.mjs +292 -0
  122. package/src/doctor/agent-model-inherit.mjs +101 -0
  123. package/src/doctor/batch-size-guidance.mjs +72 -0
  124. package/src/doctor/coexistence.mjs +312 -0
  125. package/src/doctor/rules-manifest.mjs +133 -0
  126. package/src/doctor/stale-path.mjs +156 -0
  127. package/src/doctor/stall-config.mjs +108 -0
  128. package/src/doctor/suggest-max-parallel.mjs +53 -0
  129. package/src/doctor/task-packet-size.mjs +110 -0
  130. package/src/doctor/worktree-health.mjs +71 -0
  131. package/src/migrate/taskplane-config.mjs +116 -0
  132. package/src/planner/cycles.mjs +63 -0
  133. package/src/planner/format-plan.mjs +132 -0
  134. package/src/planner/graph.mjs +99 -0
  135. package/src/planner/index.mjs +125 -0
  136. package/src/planner/lanes.mjs +111 -0
  137. package/src/planner/pending.mjs +39 -0
  138. package/src/planner/scope.mjs +142 -0
  139. package/src/process/liveness.mjs +21 -0
  140. package/src/tasks/packet/discover.mjs +40 -0
  141. package/src/tasks/packet/index.mjs +81 -0
  142. package/src/tasks/packet/merge-deps.mjs +79 -0
  143. package/src/tasks/packet/parse-prompt.mjs +445 -0
  144. package/src/tasks/packet/parse-status.mjs +118 -0
  145. package/src/tasks/packet/validate-contract.mjs +115 -0
  146. package/src/tasks/packet/validate-prompt.mjs +99 -0
  147. package/src/worker-tools/report-progress.d.mts +18 -0
  148. package/src/worker-tools/report-progress.mjs +59 -0
  149. package/src/worker-tools/request-gate.d.mts +17 -0
  150. package/src/worker-tools/request-gate.mjs +54 -0
  151. package/templates/agents/reviewer.md +123 -0
  152. package/templates/agents/supervisor.md +59 -0
  153. package/templates/agents/worker.md +122 -0
  154. package/templates/rules-profile.json +27 -0
  155. package/templates/spine-config.json +64 -0
  156. package/templates/tasks/CONTEXT.md +30 -0
@@ -0,0 +1,632 @@
1
+ /**
2
+ * Engine lane merge-phase wiring — lane→orch merges and rules-manifest conflict resolution.
3
+ */
4
+
5
+ import { execFileSync } from "node:child_process";
6
+ import { gitExec } from "../git-exec.mjs";
7
+ import {
8
+ parseRulesManifestJson,
9
+ resolveRulesManifestGeneratedAtMerge,
10
+ RULES_MANIFEST_REL_PATH,
11
+ writeRulesManifestAtomic,
12
+ loadRulesManifest,
13
+ fingerprintRulesManifest,
14
+ } from "../../config/cursor-rules/discover.mjs";
15
+ import { matchesContractPattern } from "../contract-verify.mjs";
16
+ import { appendJournalEvent } from "../journal.mjs";
17
+ import { countCommitsAhead, gitPorcelain } from "../lane-commit.mjs";
18
+ import { saveSpineBatchState } from "../state.mjs";
19
+ import { loadTaskFileScopePaths } from "./queue.mjs";
20
+ import { laneTaskBranch } from "../worktree.mjs";
21
+
22
+ /**
23
+ * @param {string} projectRoot
24
+ * @param {string[]} args
25
+ * @param {{ throwOnError?: boolean }} [options]
26
+ */
27
+ function git(projectRoot, args, { throwOnError = true } = {}) {
28
+ return gitExec(projectRoot, args, { throwOnError, projectRoot });
29
+ }
30
+
31
+ /**
32
+ * @param {string} projectRoot
33
+ */
34
+ function abortInProgressMerge(projectRoot) {
35
+ try {
36
+ execFileSync("git", ["merge", "--abort"], {
37
+ cwd: projectRoot,
38
+ stdio: "ignore",
39
+ });
40
+ } catch {
41
+ // best effort — leave checkout restoration to caller
42
+ }
43
+ }
44
+
45
+ /**
46
+ * @param {string} projectRoot
47
+ */
48
+ function listUnmergedPaths(projectRoot) {
49
+ const output = git(projectRoot, ["diff", "--name-only", "--diff-filter=U"], {
50
+ throwOnError: false,
51
+ });
52
+ if (!output) return [];
53
+ return output.split("\n").map((line) => line.trim()).filter(Boolean);
54
+ }
55
+
56
+ /**
57
+ * @param {string} projectRoot
58
+ * @param {string} ref
59
+ */
60
+ function readRulesManifestFromRef(projectRoot, ref) {
61
+ const output = git(projectRoot, ["show", `${ref}:${RULES_MANIFEST_REL_PATH}`], {
62
+ throwOnError: false,
63
+ });
64
+ if (output == null) {
65
+ return { ok: false, error: `missing ${RULES_MANIFEST_REL_PATH} at ${ref}` };
66
+ }
67
+ return parseRulesManifestJson(output);
68
+ }
69
+
70
+ /**
71
+ * @param {string} line
72
+ * @returns {string | null}
73
+ */
74
+ function extractPorcelainPath(line) {
75
+ if (!line.trim()) return null;
76
+ let filePath = line.length > 2 && line[2] === " " ? line.slice(3) : line.slice(2);
77
+ filePath = filePath.trim();
78
+ if (!filePath) return null;
79
+ if (filePath.includes(" -> ")) {
80
+ return filePath.split(" -> ").pop()?.trim() ?? null;
81
+ }
82
+ return filePath;
83
+ }
84
+
85
+ /**
86
+ * @param {string} projectRoot
87
+ */
88
+ function listDirtyPaths(projectRoot) {
89
+ const output = gitPorcelain(projectRoot);
90
+ if (!output) return [];
91
+ return output
92
+ .split("\n")
93
+ .map((line) => extractPorcelainPath(line))
94
+ .filter((entry) => Boolean(entry));
95
+ }
96
+
97
+ /**
98
+ * Before orch→main integrate, auto-resolve uncommitted generatedAt-only drift on rules-manifest.
99
+ *
100
+ * @param {object} params
101
+ * @param {string} params.projectRoot
102
+ * @param {string} params.baseBranch
103
+ * @param {string} params.orchBranch
104
+ */
105
+ export function resolveRulesManifestIntegrateDrift({ projectRoot, baseBranch, orchBranch }) {
106
+ const dirtyPaths = listDirtyPaths(projectRoot);
107
+ if (dirtyPaths.length === 0) {
108
+ return { ok: true, resolved: false };
109
+ }
110
+ if (dirtyPaths.length !== 1 || dirtyPaths[0] !== RULES_MANIFEST_REL_PATH) {
111
+ return { ok: true, resolved: false };
112
+ }
113
+
114
+ const working = loadRulesManifest(projectRoot);
115
+ if (!working) {
116
+ return {
117
+ ok: false,
118
+ failureClass: "DirtyWorktree",
119
+ error: `${RULES_MANIFEST_REL_PATH} is dirty but unreadable`,
120
+ };
121
+ }
122
+
123
+ const headResult = readRulesManifestFromRef(projectRoot, baseBranch);
124
+ const orchResult = readRulesManifestFromRef(projectRoot, orchBranch);
125
+ if (!headResult.ok || !orchResult.ok) {
126
+ return {
127
+ ok: false,
128
+ failureClass: "DirtyWorktree",
129
+ error: "unable to read rules-manifest from base or orch branch",
130
+ };
131
+ }
132
+
133
+ if (fingerprintRulesManifest(working) !== fingerprintRulesManifest(headResult.manifest)) {
134
+ return {
135
+ ok: false,
136
+ failureClass: "DirtyWorktree",
137
+ error:
138
+ `${RULES_MANIFEST_REL_PATH} has uncommitted content changes beyond generatedAt — commit or stash before integrate`,
139
+ };
140
+ }
141
+
142
+ if (fingerprintRulesManifest(headResult.manifest) !== fingerprintRulesManifest(orchResult.manifest)) {
143
+ const contentMerge = resolveRulesManifestGeneratedAtMerge({
144
+ ours: headResult.manifest,
145
+ theirs: orchResult.manifest,
146
+ });
147
+ if (!contentMerge.ok) {
148
+ return contentMerge;
149
+ }
150
+ }
151
+
152
+ gitExec(
153
+ projectRoot,
154
+ ["restore", "--source=HEAD", "--staged", "--worktree", RULES_MANIFEST_REL_PATH],
155
+ { projectRoot },
156
+ );
157
+ return {
158
+ ok: true,
159
+ resolved: true,
160
+ action: "restored_head_for_merge",
161
+ };
162
+ }
163
+
164
+ /**
165
+ * @param {string} projectRoot
166
+ * @param {2 | 3} stage
167
+ */
168
+ function readRulesManifestMergeStage(projectRoot, stage) {
169
+ const output = git(projectRoot, ["show", `:${stage}:${RULES_MANIFEST_REL_PATH}`], {
170
+ throwOnError: false,
171
+ });
172
+ if (output == null) {
173
+ return { ok: false, error: `missing merge stage ${stage} for ${RULES_MANIFEST_REL_PATH}` };
174
+ }
175
+ return parseRulesManifestJson(output);
176
+ }
177
+
178
+ /**
179
+ * @param {string} filePath
180
+ * @param {string[]} laneFileScopePaths
181
+ */
182
+ function pathInLaneFileScope(filePath, laneFileScopePaths) {
183
+ if (!Array.isArray(laneFileScopePaths) || laneFileScopePaths.length === 0) {
184
+ return false;
185
+ }
186
+ return laneFileScopePaths.some((pattern) => matchesContractPattern(filePath, pattern));
187
+ }
188
+
189
+ /**
190
+ * @param {string} projectRoot
191
+ * @param {string} mergeBase
192
+ * @param {string} taskBranch
193
+ * @returns {Set<string>}
194
+ */
195
+ function listBranchChangedFiles(projectRoot, mergeBase, taskBranch) {
196
+ const output = git(projectRoot, ["diff", "--name-only", `${mergeBase}..${taskBranch}`], {
197
+ throwOnError: false,
198
+ });
199
+ if (!output) return new Set();
200
+ return new Set(
201
+ output
202
+ .split("\n")
203
+ .map((line) => line.trim())
204
+ .filter(Boolean),
205
+ );
206
+ }
207
+
208
+ /**
209
+ * @param {string} projectRoot
210
+ */
211
+ function resolveRulesManifestMergeConflict(projectRoot) {
212
+ const oursResult = readRulesManifestMergeStage(projectRoot, 2);
213
+ const theirsResult = readRulesManifestMergeStage(projectRoot, 3);
214
+ if (!oursResult.ok || !theirsResult.ok) {
215
+ return {
216
+ ok: false,
217
+ error: "unable to read rules-manifest merge stages",
218
+ };
219
+ }
220
+
221
+ const resolved = resolveRulesManifestGeneratedAtMerge({
222
+ ours: oursResult.manifest,
223
+ theirs: theirsResult.manifest,
224
+ });
225
+ if (!resolved.ok) {
226
+ return resolved;
227
+ }
228
+
229
+ writeRulesManifestAtomic(projectRoot, resolved.manifest);
230
+ gitExec(projectRoot, ["add", RULES_MANIFEST_REL_PATH], { projectRoot });
231
+ return {
232
+ ok: true,
233
+ autoResolved: true,
234
+ generatedAt: resolved.manifest.generatedAt,
235
+ };
236
+ }
237
+
238
+ /**
239
+ * Prefer orch (merge --ours) for stale dependency artifacts outside lane file scope.
240
+ *
241
+ * @param {object} params
242
+ * @param {string} params.projectRoot
243
+ * @param {string} params.filePath
244
+ * @param {string[]} params.laneFileScopePaths
245
+ * @param {Set<string>} params.laneChangedFiles
246
+ */
247
+ function tryAutoResolveOutOfScopeMergeConflict({
248
+ projectRoot,
249
+ filePath,
250
+ laneFileScopePaths,
251
+ laneChangedFiles,
252
+ }) {
253
+ if (pathInLaneFileScope(filePath, laneFileScopePaths)) {
254
+ return { ok: false, reason: "in_lane_file_scope" };
255
+ }
256
+
257
+ gitExec(projectRoot, ["checkout", "--ours", "--", filePath], { projectRoot });
258
+ gitExec(projectRoot, ["add", "--", filePath], { projectRoot });
259
+ return { ok: true, strategy: "prefer_orch_out_of_scope" };
260
+ }
261
+
262
+ /**
263
+ * @param {object} state
264
+ * @param {number} laneNumber
265
+ * @param {string[]} waveTaskIds
266
+ */
267
+ function collectLaneWaveFileScope(state, laneNumber, waveTaskIds) {
268
+ /** @type {Set<string>} */
269
+ const patterns = new Set();
270
+ for (const taskId of waveTaskIds) {
271
+ const task = (state.tasks ?? []).find((entry) => entry?.taskId === taskId);
272
+ if (!task || task.laneNumber !== laneNumber) continue;
273
+ const folder = task.taskFolder;
274
+ if (!folder) continue;
275
+ const scope = loadTaskFileScopePaths(folder);
276
+ if (scope.ok) {
277
+ for (const pattern of scope.fileScopePaths) {
278
+ patterns.add(pattern);
279
+ }
280
+ }
281
+ }
282
+ return [...patterns];
283
+ }
284
+
285
+ /**
286
+ * @param {string} projectRoot
287
+ * @param {object} [options]
288
+ * @param {string[]} [options.laneFileScopePaths]
289
+ * @param {string} [options.taskBranch]
290
+ * @param {string} [options.orchBranch]
291
+ */
292
+ export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
293
+ const { laneFileScopePaths = [], taskBranch, orchBranch } = options;
294
+ const unmerged = listUnmergedPaths(projectRoot);
295
+ if (unmerged.length === 0) {
296
+ const dirtyPaths = listDirtyPaths(projectRoot);
297
+ const dirtyHint =
298
+ dirtyPaths.length > 0
299
+ ? ` (dirty: ${dirtyPaths.join(", ")})`
300
+ : "";
301
+ return {
302
+ ok: false,
303
+ error: `merge failed without unmerged paths${dirtyHint}`,
304
+ };
305
+ }
306
+
307
+ const canResolveOutOfScope =
308
+ Array.isArray(laneFileScopePaths) &&
309
+ laneFileScopePaths.length > 0 &&
310
+ Boolean(taskBranch) &&
311
+ Boolean(orchBranch);
312
+
313
+ /** @type {Set<string>} */
314
+ let laneChangedFiles = new Set();
315
+ if (canResolveOutOfScope) {
316
+ const mergeBase = git(projectRoot, ["merge-base", orchBranch, taskBranch], {
317
+ throwOnError: false,
318
+ });
319
+ if (mergeBase) {
320
+ laneChangedFiles = listBranchChangedFiles(projectRoot, mergeBase, taskBranch);
321
+ }
322
+ }
323
+
324
+ /** @type {string[]} */
325
+ const resolvedOutOfScope = [];
326
+ /** @type {string[]} */
327
+ const remaining = [];
328
+
329
+ for (const filePath of unmerged) {
330
+ if (filePath === RULES_MANIFEST_REL_PATH) {
331
+ remaining.push(filePath);
332
+ continue;
333
+ }
334
+ if (!canResolveOutOfScope) {
335
+ remaining.push(filePath);
336
+ continue;
337
+ }
338
+ const resolved = tryAutoResolveOutOfScopeMergeConflict({
339
+ projectRoot,
340
+ filePath,
341
+ laneFileScopePaths,
342
+ laneChangedFiles,
343
+ });
344
+ if (resolved.ok) {
345
+ resolvedOutOfScope.push(filePath);
346
+ } else {
347
+ remaining.push(filePath);
348
+ }
349
+ }
350
+
351
+ if (remaining.includes(RULES_MANIFEST_REL_PATH)) {
352
+ const manifestResult = resolveRulesManifestMergeConflict(projectRoot);
353
+ if (manifestResult.ok) {
354
+ resolvedOutOfScope.push(RULES_MANIFEST_REL_PATH);
355
+ const withoutManifest = remaining.filter((filePath) => filePath !== RULES_MANIFEST_REL_PATH);
356
+ if (withoutManifest.length === 0) {
357
+ return {
358
+ ...manifestResult,
359
+ outOfScopePaths: resolvedOutOfScope,
360
+ };
361
+ }
362
+ remaining.length = 0;
363
+ remaining.push(...withoutManifest);
364
+ }
365
+ }
366
+
367
+ if (remaining.length === 1 && remaining[0] === RULES_MANIFEST_REL_PATH) {
368
+ const manifestResult = resolveRulesManifestMergeConflict(projectRoot);
369
+ if (!manifestResult.ok) {
370
+ return manifestResult;
371
+ }
372
+ return {
373
+ ...manifestResult,
374
+ outOfScopePaths: resolvedOutOfScope,
375
+ };
376
+ }
377
+
378
+ if (remaining.length === 0) {
379
+ return {
380
+ ok: true,
381
+ autoResolved: true,
382
+ outOfScopePaths: resolvedOutOfScope,
383
+ };
384
+ }
385
+
386
+ return {
387
+ ok: false,
388
+ failureClass: "MergeConflict",
389
+ error:
390
+ `merge conflict on ${remaining.join(", ")}; automatic resolution supports ${RULES_MANIFEST_REL_PATH} ` +
391
+ "and out-of-scope dependency drift (prefer orch when the lane did not commit the path)",
392
+ outOfScopePaths: resolvedOutOfScope,
393
+ };
394
+ }
395
+
396
+ /** @deprecated use tryAutoResolveMergeConflicts */
397
+ export function tryAutoResolveRulesManifestMergeConflict(projectRoot) {
398
+ return tryAutoResolveMergeConflicts(projectRoot, {});
399
+ }
400
+
401
+ /**
402
+ * @param {string} projectRoot
403
+ * @param {string[]} args
404
+ */
405
+ function gitStrict(projectRoot, args) {
406
+ return git(projectRoot, args);
407
+ }
408
+
409
+ /**
410
+ * @param {object} params
411
+ * @param {boolean} [params.requireLaneCommits] When true, task branch must be ahead of orch before merge (post lane auto-commit).
412
+ */
413
+ /**
414
+ * Clear generatedAt-only rules-manifest drift on the working tree before lane→orch merge.
415
+ * Workers refresh the manifest during pi sessions; an uncommitted copy blocks `git merge`.
416
+ *
417
+ * @param {string} projectRoot
418
+ */
419
+ function resolveRulesManifestPreMergeDrift(projectRoot) {
420
+ const dirtyPaths = listDirtyPaths(projectRoot);
421
+ if (dirtyPaths.length === 0) {
422
+ return { ok: true, resolved: false };
423
+ }
424
+ if (dirtyPaths.length !== 1 || dirtyPaths[0] !== RULES_MANIFEST_REL_PATH) {
425
+ return { ok: true, resolved: false };
426
+ }
427
+
428
+ const headRef = gitStrict(projectRoot, ["rev-parse", "HEAD"]);
429
+ const headResult = readRulesManifestFromRef(projectRoot, headRef);
430
+ const working = loadRulesManifest(projectRoot);
431
+ if (!working) {
432
+ return {
433
+ ok: false,
434
+ failureClass: "DirtyWorktree",
435
+ error: `${RULES_MANIFEST_REL_PATH} is dirty but unreadable`,
436
+ };
437
+ }
438
+ if (!headResult.ok) {
439
+ return {
440
+ ok: false,
441
+ failureClass: "DirtyWorktree",
442
+ error: `unable to read ${RULES_MANIFEST_REL_PATH} at HEAD`,
443
+ };
444
+ }
445
+
446
+ if (fingerprintRulesManifest(working) !== fingerprintRulesManifest(headResult.manifest)) {
447
+ return {
448
+ ok: false,
449
+ failureClass: "DirtyWorktree",
450
+ error:
451
+ `${RULES_MANIFEST_REL_PATH} has uncommitted content changes beyond generatedAt — commit or stash before merge`,
452
+ };
453
+ }
454
+
455
+ gitExec(
456
+ projectRoot,
457
+ ["restore", "--source=HEAD", "--staged", "--worktree", RULES_MANIFEST_REL_PATH],
458
+ { projectRoot },
459
+ );
460
+ return { ok: true, resolved: true, action: "restored_head_for_lane_merge" };
461
+ }
462
+
463
+ export function mergeLaneToOrch({
464
+ projectRoot,
465
+ baseBranch,
466
+ orchBranch,
467
+ taskBranch,
468
+ batchId,
469
+ requireLaneCommits = false,
470
+ laneFileScopePaths = [],
471
+ }) {
472
+ const previous = gitStrict(projectRoot, ["rev-parse", "--abbrev-ref", "HEAD"]);
473
+ let mergeInProgress = false;
474
+ try {
475
+ const drift = resolveRulesManifestPreMergeDrift(projectRoot);
476
+ if (!drift.ok) {
477
+ return {
478
+ ok: false,
479
+ failureClass: drift.failureClass ?? "DirtyWorktree",
480
+ error: drift.error ?? "dirty worktree blocks lane merge",
481
+ };
482
+ }
483
+
484
+ const orchHeadBefore = gitStrict(projectRoot, ["rev-parse", orchBranch]);
485
+ const commitsAhead = countCommitsAhead(projectRoot, orchBranch, taskBranch);
486
+
487
+ if (requireLaneCommits && commitsAhead === 0) {
488
+ return {
489
+ ok: false,
490
+ failureClass: "EmptyMerge",
491
+ error:
492
+ `Task branch ${taskBranch} has no commits ahead of ${orchBranch} after lane auto-commit. ` +
493
+ `Worker may have created .DONE without persisting file changes to git.`,
494
+ };
495
+ }
496
+
497
+ gitStrict(projectRoot, ["checkout", orchBranch]);
498
+ try {
499
+ gitStrict(projectRoot, [
500
+ "merge",
501
+ "--no-ff",
502
+ taskBranch,
503
+ "-m",
504
+ `merge ${taskBranch} into ${orchBranch}`,
505
+ ]);
506
+ } catch {
507
+ mergeInProgress = true;
508
+ const autoResolved = tryAutoResolveMergeConflicts(projectRoot, {
509
+ laneFileScopePaths,
510
+ taskBranch,
511
+ orchBranch,
512
+ });
513
+ if (!autoResolved.ok) {
514
+ abortInProgressMerge(projectRoot);
515
+ return {
516
+ ok: false,
517
+ failureClass: autoResolved.failureClass ?? "MergeConflict",
518
+ error: autoResolved.error ?? "merge conflict",
519
+ outOfScopePaths: autoResolved.outOfScopePaths ?? [],
520
+ };
521
+ }
522
+ gitStrict(projectRoot, ["commit", "--no-edit"]);
523
+ }
524
+
525
+ const mergeCommit = gitStrict(projectRoot, ["rev-parse", "HEAD"]);
526
+
527
+ if (requireLaneCommits && mergeCommit === orchHeadBefore) {
528
+ return {
529
+ ok: false,
530
+ failureClass: "EmptyMerge",
531
+ error:
532
+ `Merge into ${orchBranch} did not advance HEAD (still ${orchHeadBefore.slice(0, 7)}). ` +
533
+ `Lane work was not integrated.`,
534
+ };
535
+ }
536
+
537
+ return { ok: true, mergeCommit, commitsAhead };
538
+ } catch (err) {
539
+ if (mergeInProgress) {
540
+ abortInProgressMerge(projectRoot);
541
+ }
542
+ return {
543
+ ok: false,
544
+ error: err instanceof Error ? err.message : String(err),
545
+ };
546
+ } finally {
547
+ try {
548
+ gitStrict(projectRoot, ["checkout", previous || baseBranch]);
549
+ } catch {
550
+ gitStrict(projectRoot, ["checkout", baseBranch]);
551
+ }
552
+ }
553
+ }
554
+
555
+ /**
556
+ * @param {object} params
557
+ */
558
+ export async function mergeWaveLanesToOrch({
559
+ projectRoot,
560
+ state,
561
+ batchId,
562
+ baseBranch,
563
+ orchBranch,
564
+ waveIndex,
565
+ }) {
566
+ const waveTaskIds = state.wavePlan?.[waveIndex] ?? [];
567
+ const needsReplanTask = (state.tasks ?? []).find(
568
+ (entry) =>
569
+ waveTaskIds.includes(entry?.taskId) && entry?.exitReason === "needs_replan",
570
+ );
571
+ if (needsReplanTask) {
572
+ return {
573
+ ok: false,
574
+ error: `wave merge blocked: task ${needsReplanTask.taskId} has exitReason needs_replan`,
575
+ blockedBy: needsReplanTask.taskId,
576
+ exitReason: "needs_replan",
577
+ };
578
+ }
579
+
580
+ const lanes = state.lanes ?? [];
581
+ let lastMergeCommit = null;
582
+
583
+ for (const lane of lanes) {
584
+ const laneNumber = lane.laneNumber;
585
+ const waveTaskIds = state.wavePlan?.[waveIndex] ?? [];
586
+ const laneSucceeded = waveTaskIds.some((taskId) => {
587
+ const task = (state.tasks ?? []).find((entry) => entry?.taskId === taskId);
588
+ return task && task.laneNumber === laneNumber && task.status === "succeeded";
589
+ });
590
+ if (!laneSucceeded) continue;
591
+
592
+ const taskBranch = lane.branch ?? laneTaskBranch(batchId, laneNumber);
593
+ const laneFileScopePaths = collectLaneWaveFileScope(state, laneNumber, waveTaskIds);
594
+ appendJournalEvent(projectRoot, batchId, "batch.merge_started", {
595
+ taskBranch,
596
+ orchBranch,
597
+ laneNumber,
598
+ waveIndex,
599
+ laneFileScopePaths,
600
+ });
601
+
602
+ const merge = mergeLaneToOrch({
603
+ projectRoot,
604
+ baseBranch,
605
+ orchBranch,
606
+ taskBranch,
607
+ batchId,
608
+ requireLaneCommits: false,
609
+ laneFileScopePaths,
610
+ });
611
+ if (!merge.ok) {
612
+ return { ok: false, error: merge.error ?? "merge_failed", laneNumber };
613
+ }
614
+ lastMergeCommit = merge.mergeCommit;
615
+ appendJournalEvent(projectRoot, batchId, "batch.merge_completed", {
616
+ mergeCommit: merge.mergeCommit,
617
+ laneNumber,
618
+ waveIndex,
619
+ });
620
+ }
621
+
622
+ state.mergeResults.push({
623
+ waveIndex,
624
+ status: "succeeded",
625
+ failedLane: null,
626
+ failureReason: null,
627
+ mergeCommit: lastMergeCommit,
628
+ });
629
+ saveSpineBatchState(projectRoot, state);
630
+
631
+ return { ok: true, mergeCommit: lastMergeCommit };
632
+ }