pi-spine 1.0.2 → 1.1.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 (63) hide show
  1. package/README.md +61 -489
  2. package/bin/get-version.mjs +1 -13
  3. package/bin/spine-batch.mjs +5 -1
  4. package/bin/spine-config.mjs +1 -212
  5. package/bin/spine-doctor.mjs +2 -418
  6. package/bin/spine-init.mjs +1 -398
  7. package/bin/spine-preflight.mjs +1 -700
  8. package/bin/spine-review-step.mjs +6 -4
  9. package/bin/spine-tasks.mjs +96 -11
  10. package/bin/spine-worker-runner.mjs +14 -4
  11. package/bin/spine.mjs +3 -1
  12. package/extensions/spine/worker-tools.ts +14 -12
  13. package/package.json +5 -2
  14. package/skills/create-spine-tasks/SKILL.md +135 -6
  15. package/skills/create-spine-tasks/references/clarify-template.md +73 -0
  16. package/skills/create-spine-tasks/references/prompt-template.md +2 -0
  17. package/skills/create-spine-tasks/references/requirements-checklist-template.md +94 -0
  18. package/src/batch/abort.mjs +1 -1
  19. package/src/batch/detached-start.mjs +41 -7
  20. package/src/batch/diagnosis.mjs +51 -6
  21. package/src/batch/engine-lanes/merge.mjs +70 -7
  22. package/src/batch/engine-lanes/review.mjs +32 -74
  23. package/src/batch/engine-scope.mjs +31 -4
  24. package/src/batch/engine.mjs +40 -48
  25. package/src/batch/evidence.mjs +3 -2
  26. package/src/batch/gate.mjs +3 -3
  27. package/src/batch/integrate.mjs +1 -1
  28. package/src/batch/journal.mjs +22 -0
  29. package/src/batch/lifecycle.mjs +1 -1
  30. package/src/batch/merge/adoption-doc-merge.mjs +160 -0
  31. package/src/batch/merge/wave-merge-state.mjs +105 -0
  32. package/src/batch/post-merge-limbo.mjs +87 -15
  33. package/src/batch/reconcile.mjs +50 -2
  34. package/src/batch/resume-common.mjs +1 -1
  35. package/src/batch/resume-engine.mjs +58 -1
  36. package/src/batch/resume-multi-validate.mjs +82 -3
  37. package/src/batch/resume-multi.mjs +36 -40
  38. package/src/batch/resume.mjs +20 -10
  39. package/src/batch/review-shared.mjs +196 -0
  40. package/src/batch/review-spawn.mjs +320 -0
  41. package/src/batch/review.mjs +178 -212
  42. package/src/batch/task-stall-budget.mjs +72 -0
  43. package/src/batch/worker-host.mjs +94 -34
  44. package/src/batch/worktree.mjs +10 -0
  45. package/src/cli/handoff.mjs +1 -1
  46. package/src/cli/rules.mjs +1 -1
  47. package/src/cli/settings-set.mjs +1 -1
  48. package/src/cli/settings-slash.mjs +27 -5
  49. package/src/config/spine-config-load.mjs +221 -0
  50. package/src/config/spine-init-constants.mjs +423 -0
  51. package/src/config/spine-preflight-lib.mjs +725 -0
  52. package/src/dashboard/public/dashboard.js +4 -25
  53. package/src/dashboard/public/index.html +1 -7
  54. package/src/dashboard/snapshot.mjs +172 -5
  55. package/src/dashboard/view.mjs +2 -0
  56. package/src/doctor/run-doctor-checks.mjs +458 -0
  57. package/src/doctor/stale-path.mjs +22 -0
  58. package/src/migrate/taskplane-config.mjs +1 -1
  59. package/src/planner/pending.mjs +92 -1
  60. package/src/tasks/analyze/index.mjs +453 -0
  61. package/src/util/command-exists.mjs +19 -0
  62. package/templates/docs/constitution.md +61 -0
  63. package/templates/spine-config.json +1 -1
@@ -0,0 +1,94 @@
1
+ # Requirements checklist template
2
+
3
+ Use for **Step A.6 — Requirements checklist (optional)** in the create-spine-tasks skill.
4
+ Output path: `{tasksRoot}/_authoring/{slug}/checklist.md`
5
+
6
+ **Purpose:** "Unit tests for requirements" — validate PRD/brief quality before task slicing. Inspired by spec-kit `/speckit.checklist`. This is **not** implementation verification; it checks whether requirements are complete, clear, measurable, and ready for decomposition.
7
+
8
+ **Ordering:** Run after **Step A.5 — Clarify** (`clarify.md` in the same `_authoring/{slug}/` folder) and before **Step B — Slice into spine tasks**.
9
+
10
+ **Constraints:** read-only on source docs; no commits; no file edits outside authoring output. `spine tasks validate` does **not** require checklist artifacts.
11
+
12
+ **Do not duplicate** Step 0 explore `findings.md` content — explore maps codebase touch points; checklist validates requirement quality.
13
+
14
+ ---
15
+
16
+ ```markdown
17
+ # Requirements checklist: {slug}
18
+
19
+ **Date:** YYYY-MM-DD
20
+ **Status:** complete | superseded
21
+ **Sources:** (PRD/brief paths reviewed)
22
+
23
+ ## Summary
24
+
25
+ (1–3 sentences: overall readiness for decomposition and top gaps found.)
26
+
27
+ ## Acceptance criteria quality
28
+
29
+ - [ ] CHK001 — Are success criteria measurable for each deliverable? [Measurability]
30
+ - [ ] CHK002 — Can completion be verified without subjective judgment? [Clarity]
31
+ - [ ] CHK003 — Are acceptance criteria traceable to user-facing outcomes? [Traceability]
32
+
33
+ ## Security
34
+
35
+ - [ ] CHK010 — Are authn/authz requirements specified for protected operations? [Coverage, Gap]
36
+ - [ ] CHK011 — Are secrets, credentials, and sensitive data handling defined? [Completeness]
37
+ - [ ] CHK012 — Are input validation and fail-secure defaults documented? [Security]
38
+
39
+ ## Edge cases
40
+
41
+ - [ ] CHK020 — Are empty, null, and zero-state scenarios addressed? [Edge Case]
42
+ - [ ] CHK021 — Are error and partial-failure paths specified? [Exception Flow]
43
+ - [ ] CHK022 — Are rollback or recovery requirements defined when state mutates? [Recovery, Gap]
44
+
45
+ ## Testability
46
+
47
+ - [ ] CHK030 — Is the project's test command identifiable for downstream tasks? [Testability]
48
+ - [ ] CHK031 — Are verifiable behaviors separated from implementation details? [Clarity]
49
+ - [ ] CHK032 — Can workers derive a Testing step from the requirements? [Completeness]
50
+
51
+ ## Non-functional requirements
52
+
53
+ - [ ] CHK040 — Are performance or latency targets quantified (not "fast")? [NFR, Clarity]
54
+ - [ ] CHK041 — Are observability, logging, or operability needs specified? [NFR, Gap]
55
+ - [ ] CHK042 — Are compatibility, migration, or reversibility constraints documented? [NFR]
56
+
57
+ ## Gaps and blockers
58
+
59
+ - (items marked `[Gap]` or unresolved from clarify.md — None if ready to slice)
60
+ ```
61
+
62
+ ---
63
+
64
+ ## When to run
65
+
66
+ | Signal | Why checklist helps |
67
+ |--------|---------------------|
68
+ | After clarify with open assumptions | Surfaces requirement gaps before slicing |
69
+ | L/XL epic or multi-task decomposition | Catches missing NFRs and edge cases early |
70
+ | Security- or compliance-touching work | Forces explicit auth/data handling in requirements |
71
+ | Vague acceptance language ("robust", "fast") | Converts ambiguity into measurable criteria |
72
+ | Parallel wave planning | Ensures disjoint scopes are justified by clear requirements |
73
+
74
+ ## When to skip
75
+
76
+ - Single S/M task with concrete File Scope and measurable acceptance criteria already
77
+ - Greenfield with a short, unambiguous brief and no security surface
78
+ - Migrating existing spine packets unchanged
79
+ - Step 0 explore not run and requirements are already validated elsewhere
80
+
81
+ ## Authoring pipeline order
82
+
83
+ ```
84
+ Step A (Read sources)
85
+ → Step A.5 Clarify → {tasksRoot}/_authoring/{slug}/clarify.md
86
+ → Step A.6 Checklist → {tasksRoot}/_authoring/{slug}/checklist.md
87
+ → Step B (Slice into spine tasks)
88
+ ```
89
+
90
+ Resolve or explicitly defer checklist gaps before Step B. Link the slug in `{tasksRoot}/CONTEXT.md` when checklist informs decomposition (same pattern as explore findings).
91
+
92
+ ## External equivalent
93
+
94
+ - spec-kit: `/speckit.checklist` — [github/spec-kit](https://github.com/github/spec-kit) (`templates/commands/checklist.md`)
@@ -4,7 +4,7 @@
4
4
 
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
- import { loadSpineConfig } from "../../bin/spine-config.mjs";
7
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
8
8
  import { archiveBatchStatePath } from "./lifecycle.mjs";
9
9
  import { appendJournalEvent, journalPath, readJournalEvents, readJournalTail } from "./journal.mjs";
10
10
  import { loadBatchStateFile } from "./reconcile.mjs";
@@ -5,13 +5,14 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { spawn } from "node:child_process";
8
- import { loadSpineConfig } from "../../bin/spine-config.mjs";
9
- import { runBatchPreflight } from "../../bin/spine-preflight.mjs";
8
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
+ import { runBatchPreflight } from "../config/spine-preflight-lib.mjs";
10
10
  import { loadGateRecord } from "./gate.mjs";
11
11
  import { reconcileBatch } from "./reconcile.mjs";
12
12
  import { validateResumeBatch } from "./resume.mjs";
13
+ import { assessRunningPhaseResumeEligibility } from "./resume-multi-validate.mjs";
13
14
  import { readLastTaskFailedEvent } from "./journal.mjs";
14
- import { terminateStaleDetachedEngine } from "./resume-engine.mjs";
15
+ import { prepareOrphanResumeHandoff } from "./resume-engine.mjs";
15
16
  import {
16
17
  ACTIVE_PHASES,
17
18
  loadSpineBatchState,
@@ -56,6 +57,20 @@ const TERMINAL_TASK_STATUSES = new Set(["succeeded", "failed", "skipped", "abort
56
57
 
57
58
  const FAILURE_LOG_TAIL_LINES = 20;
58
59
 
60
+ /** Default wait when --wait-terminal blocks on orphan/drift resume (real workers exceed 30s). */
61
+ const DETACHED_WAIT_TERMINAL_TIMEOUT_MS = 2 * 60 * 60 * 1000;
62
+
63
+ /**
64
+ * @param {boolean} waitTerminal
65
+ * @param {number} [explicitTimeoutMs]
66
+ */
67
+ export function resolveDetachedWaitTimeoutMs(waitTerminal, explicitTimeoutMs) {
68
+ if (Number.isFinite(explicitTimeoutMs) && explicitTimeoutMs > 0) {
69
+ return explicitTimeoutMs;
70
+ }
71
+ return waitTerminal ? DETACHED_WAIT_TERMINAL_TIMEOUT_MS : 30_000;
72
+ }
73
+
59
74
  /**
60
75
  * @param {string} filePath
61
76
  * @param {number} [lineCount]
@@ -271,14 +286,16 @@ export function detachedEngineLogPath(projectRoot) {
271
286
  * @param {object} params
272
287
  * @param {string} params.scope
273
288
  * @param {boolean} [params.skipPreflight]
289
+ * @param {boolean} [params.forceSuperseded]
274
290
  */
275
- export function buildAttachedBatchStartArgv({ scope, skipPreflight = false }) {
291
+ export function buildAttachedBatchStartArgv({ scope, skipPreflight = false, forceSuperseded = false }) {
276
292
  const tokens = String(scope ?? "")
277
293
  .trim()
278
294
  .split(/\s+/)
279
295
  .filter(Boolean);
280
296
  const args = ["batch", "start", ...tokens, "--attached"];
281
297
  if (skipPreflight) args.push("--skip-preflight");
298
+ if (forceSuperseded) args.push("--force-superseded");
282
299
  return args;
283
300
  }
284
301
 
@@ -335,6 +352,7 @@ function persistDetachedEnginePid(projectRoot, enginePid) {
335
352
  /**
336
353
  * Kill a stale detached engine and persist cleared PID before spawning resume engine (SP-254).
337
354
  * Resume child records its own PID after terminateStaleDetachedEngine runs in-process.
355
+ * Running-phase orphan resume (SP-296) clears a dead engine PID without requiring pause first.
338
356
  *
339
357
  * @param {string} projectRoot
340
358
  */
@@ -347,15 +365,27 @@ export function prepareDetachedResumeEngineHandoff(projectRoot) {
347
365
  const state = loaded.raw;
348
366
  const batchId = String(state.batchId ?? "");
349
367
  const fromPhase = String(state.phase ?? "");
350
- const terminateResult = terminateStaleDetachedEngine({
368
+ const orphanEligibility =
369
+ fromPhase === "running"
370
+ ? assessRunningPhaseResumeEligibility({ projectRoot, state })
371
+ : { engineConfirmedDead: false, allowOrphanResume: false };
372
+ const handoff = prepareOrphanResumeHandoff({
351
373
  projectRoot,
352
374
  state,
353
375
  batchId,
354
376
  fromPhase,
377
+ orphanResume: orphanEligibility.allowOrphanResume,
378
+ engineConfirmedDead: orphanEligibility.engineConfirmedDead,
355
379
  });
356
380
  saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
357
381
 
358
- return { ok: true, batchId, fromPhase, terminateResult };
382
+ return {
383
+ ok: true,
384
+ batchId,
385
+ fromPhase,
386
+ terminateResult: handoff.terminateResult,
387
+ orphanResume: orphanEligibility.allowOrphanResume,
388
+ };
359
389
  }
360
390
 
361
391
  /**
@@ -598,6 +628,7 @@ export function formatDetachedBatchStartOutput(result, json = false) {
598
628
  * @param {string} params.spineBin
599
629
  * @param {string} params.scope
600
630
  * @param {boolean} [params.skipPreflight]
631
+ * @param {boolean} [params.forceSuperseded]
601
632
  * @param {boolean} [params.waitTerminal]
602
633
  * @param {boolean} [params.json]
603
634
  */
@@ -606,6 +637,7 @@ export async function startBatchDetached({
606
637
  spineBin,
607
638
  scope,
608
639
  skipPreflight = false,
640
+ forceSuperseded = false,
609
641
  waitTerminal = false,
610
642
  json = false,
611
643
  }) {
@@ -628,7 +660,7 @@ export async function startBatchDetached({
628
660
 
629
661
  const before = loadSpineBatchState(projectRoot);
630
662
  const previousBatchId = before.raw?.batchId ?? null;
631
- const argv = buildAttachedBatchStartArgv({ scope, skipPreflight: true });
663
+ const argv = buildAttachedBatchStartArgv({ scope, skipPreflight: true, forceSuperseded });
632
664
  const { enginePid, logPath } = spawnDetachedBatchEngine({ projectRoot, spineBin, argv });
633
665
  persistDetachedEnginePid(projectRoot, enginePid);
634
666
  const wait = await waitForDetachedBatchStart({ projectRoot, previousBatchId, waitTerminal });
@@ -722,12 +754,14 @@ export async function resumeBatchDetached({
722
754
  prepareDetachedResumeEngineHandoff(projectRoot);
723
755
  const argv = buildAttachedBatchResumeArgv({ force });
724
756
  const { enginePid, logPath } = spawnDetachedBatchEngine({ projectRoot, spineBin, argv });
757
+ const waitTimeoutMs = resolveDetachedWaitTimeoutMs(waitTerminal);
725
758
  const wait = await waitForDetachedBatchResume({
726
759
  projectRoot,
727
760
  batchId,
728
761
  updatedAtBefore: updatedAt,
729
762
  taskId,
730
763
  waitTerminal,
764
+ timeoutMs: waitTimeoutMs,
731
765
  });
732
766
 
733
767
  if (!wait.ok) {
@@ -21,13 +21,20 @@ export const DIAGNOSIS_TAXONOMY = [
21
21
  "aborted",
22
22
  ];
23
23
 
24
- const NO_PAUSE_DIAGNOSES = new Set(["limbo_stale", "completed_manual", "needs_integrate"]);
24
+ const NO_PAUSE_DIAGNOSES = new Set([
25
+ "limbo_stale",
26
+ "completed_manual",
27
+ "needs_integrate",
28
+ "engine_orphaned",
29
+ ]);
25
30
 
26
31
  const LANE_COMMIT_EXIT_REASONS = new Set(["DirtyWorktree", "lane_commit_failed"]);
27
32
 
28
33
  const REVIEW_SPAWN_FAILURE_EXIT_REASONS = new Set([
29
34
  "code_review_spawn_failed",
35
+ "code_review_timeout",
30
36
  "final_review_spawn_failed",
37
+ "final_review_timeout",
31
38
  ]);
32
39
 
33
40
  /**
@@ -175,6 +182,19 @@ export function buildSuggestedCommand(diagnosis, ctx = {}) {
175
182
  ? `spine batch retry ${ctx.failedTaskId}`
176
183
  : "spine status --diagnose";
177
184
  case "worker_orphaned":
185
+ if (ctx.planReviewNestedSpawnBlocked) {
186
+ if (ctx.stalePathSpine) {
187
+ return ctx.failedTaskId
188
+ ? `node bin/spine.mjs batch retry ${ctx.failedTaskId}`
189
+ : "npm link && spine batch resume --attached";
190
+ }
191
+ if (ctx.failedTaskId) {
192
+ return `spine batch retry ${ctx.failedTaskId}`;
193
+ }
194
+ }
195
+ if (ctx.engineDead) {
196
+ return "spine batch resume --attached --force";
197
+ }
178
198
  if (ctx.ghostRunningCluster) return "spine batch abort";
179
199
  if (ctx.launchFailureKind === "pi_spine_root" || ctx.launchFailureKind === "launch_failed") {
180
200
  return "spine doctor";
@@ -187,13 +207,17 @@ export function buildSuggestedCommand(diagnosis, ctx = {}) {
187
207
  ? `spine batch retry ${ctx.failedTaskId}`
188
208
  : "spine batch abort";
189
209
  case "engine_orphaned":
190
- return ctx.failedTaskId
191
- ? `spine batch retry ${ctx.failedTaskId}`
192
- : "spine batch abort";
210
+ return "spine batch resume --attached";
193
211
  case "needs_merge":
194
212
  return "/spine-resume --force";
195
213
  case "needs_integrate":
196
214
  if (ctx.postMergeLimbo && ctx.phase === "running") {
215
+ if (ctx.integrateGateOpen) {
216
+ return "spine gate approve";
217
+ }
218
+ if (ctx.stalePathSpine) {
219
+ return "node bin/spine.mjs batch resume --attached";
220
+ }
197
221
  return "spine batch resume";
198
222
  }
199
223
  return "spine integrate";
@@ -253,7 +277,10 @@ export function buildHeadline(diagnosis, ctx = {}) {
253
277
  }
254
278
  if (REVIEW_SPAWN_FAILURE_EXIT_REASONS.has(ctx.exitReason ?? "")) {
255
279
  const reviewKind =
256
- ctx.exitReason === "final_review_spawn_failed" ? "final review" : "code review";
280
+ ctx.exitReason === "final_review_spawn_failed" ||
281
+ ctx.exitReason === "final_review_timeout"
282
+ ? "final review"
283
+ : "code review";
257
284
  return ctx.failedTaskId
258
285
  ? `${batchLabel} ${reviewKind} timed out for task ${ctx.failedTaskId} — retry or increase SPINE_REVIEW_TIMEOUT_MS`
259
286
  : `${batchLabel} reviewer spawn timed out — retry`;
@@ -269,6 +296,16 @@ export function buildHeadline(diagnosis, ctx = {}) {
269
296
  ? `${batchLabel} batch-state drift for task ${ctx.failedTaskId} — journal disagrees with cache`
270
297
  : `${batchLabel} batch-state drift — journal disagrees with cache`;
271
298
  case "worker_orphaned":
299
+ if (ctx.planReviewNestedSpawnBlocked) {
300
+ return ctx.failedTaskId
301
+ ? `${batchLabel} plan review nested_spawn_blocked (stale PATH spine or pre-SP-278) — retry task ${ctx.failedTaskId}`
302
+ : `${batchLabel} plan review nested_spawn_blocked — retry after npm link or use node bin/spine.mjs`;
303
+ }
304
+ if (ctx.engineDead) {
305
+ return ctx.failedTaskId
306
+ ? `${batchLabel} engine and worker died while task ${ctx.failedTaskId} was running — resume attached with --force`
307
+ : `${batchLabel} engine and worker died while running — resume attached with --force`;
308
+ }
272
309
  if (ctx.launchFailureKind === "pi_spine_root" || ctx.launchFailureKind === "launch_failed") {
273
310
  return `${batchLabel} lane worker orphaned during launch — fix PI_SPINE_ROOT/devcontainer, then retry`;
274
311
  }
@@ -291,6 +328,12 @@ export function buildHeadline(diagnosis, ctx = {}) {
291
328
  return `${batchLabel} tasks done — lane merges pending`;
292
329
  case "needs_integrate":
293
330
  if (ctx.postMergeLimbo && ctx.phase === "running") {
331
+ if (ctx.integrateGateOpen) {
332
+ return `${batchLabel} gate opened — approve to continue land loop`;
333
+ }
334
+ if (ctx.stalePathSpine) {
335
+ return `${batchLabel} merged but gate not opened — use node bin/spine.mjs batch resume --attached (PATH spine may be stale)`;
336
+ }
294
337
  return `${batchLabel} merged but gate not opened — resume to complete land loop`;
295
338
  }
296
339
  return `${batchLabel} ready to integrate orch branch to main`;
@@ -336,7 +379,9 @@ export function buildAlternatives(diagnosis, ctx = {}) {
336
379
  case "worker_orphaned":
337
380
  return ["spine batch abort", "spine batch resume --force", ...common];
338
381
  case "engine_orphaned":
339
- return ["spine batch abort", "spine batch resume --force", ...common];
382
+ return ctx.failedTaskId
383
+ ? [`spine batch retry ${ctx.failedTaskId}`, "spine batch abort", ...common]
384
+ : ["spine batch abort", "spine batch resume --force", ...common];
340
385
  case "needs_merge":
341
386
  return ["/spine-status --diagnose", ...common];
342
387
  case "needs_integrate":
@@ -13,8 +13,15 @@ import {
13
13
  fingerprintRulesManifest,
14
14
  } from "../../config/cursor-rules/discover.mjs";
15
15
  import { matchesContractPattern } from "../contract-verify.mjs";
16
+ import {
17
+ formatAdoptionDocMergeFailure,
18
+ isAdoptionDocPath,
19
+ tryResolveAdoptionDocMergeConflict,
20
+ } from "../merge/adoption-doc-merge.mjs";
21
+ import { recordWaveMergeResult } from "../merge/wave-merge-state.mjs";
16
22
  import { appendJournalEvent } from "../journal.mjs";
17
23
  import { countCommitsAhead, gitPorcelain } from "../lane-commit.mjs";
24
+ import { maybeFinalizeAfterWaveMerge } from "../post-merge-limbo.mjs";
18
25
  import { saveSpineBatchState } from "../state.mjs";
19
26
  import { loadTaskFileScopePaths } from "./queue.mjs";
20
27
  import { laneTaskBranch } from "../worktree.mjs";
@@ -288,9 +295,10 @@ function collectLaneWaveFileScope(state, laneNumber, waveTaskIds) {
288
295
  * @param {string[]} [options.laneFileScopePaths]
289
296
  * @param {string} [options.taskBranch]
290
297
  * @param {string} [options.orchBranch]
298
+ * @param {number} [options.waveIndex]
291
299
  */
292
300
  export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
293
- const { laneFileScopePaths = [], taskBranch, orchBranch } = options;
301
+ const { laneFileScopePaths = [], taskBranch, orchBranch, waveIndex } = options;
294
302
  const unmerged = listUnmergedPaths(projectRoot);
295
303
  if (unmerged.length === 0) {
296
304
  const dirtyPaths = listDirtyPaths(projectRoot);
@@ -326,11 +334,27 @@ export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
326
334
  /** @type {string[]} */
327
335
  const remaining = [];
328
336
 
337
+ /** @type {string[]} */
338
+ const resolvedAdoptionDocs = [];
339
+
329
340
  for (const filePath of unmerged) {
330
341
  if (filePath === RULES_MANIFEST_REL_PATH) {
331
342
  remaining.push(filePath);
332
343
  continue;
333
344
  }
345
+ if (isAdoptionDocPath(filePath)) {
346
+ const adoptionResult = tryResolveAdoptionDocMergeConflict({
347
+ projectRoot,
348
+ filePath,
349
+ waveIndex,
350
+ });
351
+ if (adoptionResult.ok) {
352
+ resolvedAdoptionDocs.push(filePath);
353
+ } else {
354
+ remaining.push(filePath);
355
+ }
356
+ continue;
357
+ }
334
358
  if (!canResolveOutOfScope) {
335
359
  remaining.push(filePath);
336
360
  continue;
@@ -380,6 +404,19 @@ export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
380
404
  ok: true,
381
405
  autoResolved: true,
382
406
  outOfScopePaths: resolvedOutOfScope,
407
+ adoptionDocPaths: resolvedAdoptionDocs,
408
+ };
409
+ }
410
+
411
+ const adoptionRemaining = remaining.filter((filePath) => isAdoptionDocPath(filePath));
412
+ if (adoptionRemaining.length > 0) {
413
+ const firstAdoption = adoptionRemaining[0];
414
+ return {
415
+ ok: false,
416
+ failureClass: "MergeConflict",
417
+ error: formatAdoptionDocMergeFailure({ filePath: firstAdoption, waveIndex }),
418
+ outOfScopePaths: resolvedOutOfScope,
419
+ adoptionDocPaths: resolvedAdoptionDocs,
383
420
  };
384
421
  }
385
422
 
@@ -387,9 +424,10 @@ export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
387
424
  ok: false,
388
425
  failureClass: "MergeConflict",
389
426
  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)",
427
+ `merge conflict on ${remaining.join(", ")}; automatic resolution supports docs/adoption/*, ` +
428
+ `${RULES_MANIFEST_REL_PATH}, and out-of-scope dependency drift (prefer orch when the lane did not commit the path)`,
392
429
  outOfScopePaths: resolvedOutOfScope,
430
+ adoptionDocPaths: resolvedAdoptionDocs,
393
431
  };
394
432
  }
395
433
 
@@ -468,6 +506,7 @@ export function mergeLaneToOrch({
468
506
  batchId,
469
507
  requireLaneCommits = false,
470
508
  laneFileScopePaths = [],
509
+ waveIndex,
471
510
  }) {
472
511
  const previous = gitStrict(projectRoot, ["rev-parse", "--abbrev-ref", "HEAD"]);
473
512
  let mergeInProgress = false;
@@ -509,6 +548,7 @@ export function mergeLaneToOrch({
509
548
  laneFileScopePaths,
510
549
  taskBranch,
511
550
  orchBranch,
551
+ waveIndex,
512
552
  });
513
553
  if (!autoResolved.ok) {
514
554
  abortInProgressMerge(projectRoot);
@@ -562,6 +602,7 @@ export async function mergeWaveLanesToOrch({
562
602
  baseBranch,
563
603
  orchBranch,
564
604
  waveIndex,
605
+ resumed = false,
565
606
  }) {
566
607
  const waveTaskIds = state.wavePlan?.[waveIndex] ?? [];
567
608
  const needsReplanTask = (state.tasks ?? []).find(
@@ -607,8 +648,17 @@ export async function mergeWaveLanesToOrch({
607
648
  batchId,
608
649
  requireLaneCommits: false,
609
650
  laneFileScopePaths,
651
+ waveIndex,
610
652
  });
611
653
  if (!merge.ok) {
654
+ recordWaveMergeResult({
655
+ state,
656
+ waveIndex,
657
+ status: "failed",
658
+ failedLane: laneNumber,
659
+ failureReason: merge.error ?? "merge_failed",
660
+ });
661
+ saveSpineBatchState(projectRoot, state);
612
662
  return { ok: false, error: merge.error ?? "merge_failed", laneNumber };
613
663
  }
614
664
  lastMergeCommit = merge.mergeCommit;
@@ -619,14 +669,27 @@ export async function mergeWaveLanesToOrch({
619
669
  });
620
670
  }
621
671
 
622
- state.mergeResults.push({
672
+ recordWaveMergeResult({
673
+ state,
623
674
  waveIndex,
624
675
  status: "succeeded",
625
- failedLane: null,
626
- failureReason: null,
627
676
  mergeCommit: lastMergeCommit,
628
677
  });
629
678
  saveSpineBatchState(projectRoot, state);
630
679
 
631
- return { ok: true, mergeCommit: lastMergeCommit };
680
+ const finalizeResult = maybeFinalizeAfterWaveMerge({
681
+ projectRoot,
682
+ state,
683
+ batchId,
684
+ orchBranch,
685
+ waveIndex,
686
+ resumed,
687
+ });
688
+
689
+ return {
690
+ ok: true,
691
+ mergeCommit: lastMergeCommit,
692
+ finalized: finalizeResult != null,
693
+ finalizeResult,
694
+ };
632
695
  }