pi-spine 1.2.0 → 1.4.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 (76) hide show
  1. package/README.md +4 -4
  2. package/bin/spine-cli/verify.mjs +6 -0
  3. package/bin/spine-deps.mjs +0 -2
  4. package/bin/spine-plan.mjs +49 -1
  5. package/bin/spine-rules.mjs +0 -2
  6. package/bin/spine-settings.mjs +0 -2
  7. package/bin/spine-worker-runner.mjs +136 -4
  8. package/bin/spine.mjs +2 -5
  9. package/package.json +2 -2
  10. package/skills/create-spine-tasks/SKILL.md +7 -2
  11. package/skills/create-spine-tasks/references/contract-template.md +95 -3
  12. package/src/batch/attached-engine-handoff.mjs +0 -1
  13. package/src/batch/attached-runner.mjs +81 -5
  14. package/src/batch/contract-stub-delivery.mjs +110 -0
  15. package/src/batch/contract-task-start.mjs +204 -0
  16. package/src/batch/contract-verify.mjs +160 -16
  17. package/src/batch/detached-start.mjs +72 -2
  18. package/src/batch/diagnosis-launch-failure.mjs +114 -0
  19. package/src/batch/diagnosis-primary-failure.mjs +89 -0
  20. package/src/batch/diagnosis-retry-limbo.mjs +1 -1
  21. package/src/batch/diagnosis-tail-state.mjs +57 -0
  22. package/src/batch/diagnosis.mjs +22 -114
  23. package/src/batch/engine-lanes/commit.mjs +145 -0
  24. package/src/batch/engine-lanes/merge.mjs +1 -2
  25. package/src/batch/engine-lanes/review.mjs +124 -121
  26. package/src/batch/engine-lanes.mjs +21 -81
  27. package/src/batch/engine.mjs +46 -1
  28. package/src/batch/evidence.mjs +1 -2
  29. package/src/batch/git-exec.mjs +5 -2
  30. package/src/batch/heartbeat.mjs +2 -2
  31. package/src/batch/integrate-assert.mjs +69 -0
  32. package/src/batch/integrate-worktree.mjs +354 -0
  33. package/src/batch/integrate.mjs +195 -102
  34. package/src/batch/journal-rebuild.mjs +158 -3
  35. package/src/batch/journal.mjs +63 -0
  36. package/src/batch/lane-commit.mjs +6 -5
  37. package/src/batch/lane-dirty-check.mjs +513 -0
  38. package/src/batch/limbo-detect.mjs +34 -0
  39. package/src/batch/macro-phase.mjs +76 -0
  40. package/src/batch/metrics.mjs +2 -0
  41. package/src/batch/pause.mjs +18 -7
  42. package/src/batch/post-merge-limbo.mjs +3 -28
  43. package/src/batch/reconcile.mjs +79 -10
  44. package/src/batch/resume-common.mjs +27 -0
  45. package/src/batch/resume-multi-lanes.mjs +11 -0
  46. package/src/batch/resume-multi.mjs +3 -1
  47. package/src/batch/resume.mjs +8 -4
  48. package/src/batch/retry.mjs +41 -10
  49. package/src/batch/review-spawn.mjs +1 -1
  50. package/src/batch/review.mjs +0 -4
  51. package/src/batch/rules-manifest-drift.mjs +43 -2
  52. package/src/batch/sequence-state.mjs +290 -0
  53. package/src/batch/sequence.mjs +113 -51
  54. package/src/batch/state.mjs +16 -0
  55. package/src/batch/worker-host.mjs +14 -5
  56. package/src/cli/deps.mjs +0 -2
  57. package/src/cli/sequence.mjs +14 -1
  58. package/src/cli/settings-set.mjs +33 -3
  59. package/src/config/contract.mjs +10 -0
  60. package/src/config/model-id.mjs +103 -0
  61. package/src/config/spine-init-constants.mjs +1 -0
  62. package/src/config/spine-preflight-lib.mjs +23 -1
  63. package/src/dashboard/public/dashboard.css +8 -0
  64. package/src/dashboard/public/dashboard.js +36 -9
  65. package/src/dashboard/running-tail-state.mjs +31 -0
  66. package/src/dashboard/server.mjs +4 -0
  67. package/src/dashboard/snapshot.mjs +260 -29
  68. package/src/dashboard/view.mjs +112 -2
  69. package/src/doctor/agent-models.mjs +53 -0
  70. package/src/doctor/batch-size-guidance.mjs +30 -2
  71. package/src/doctor/pi-extension-conflict.mjs +169 -0
  72. package/src/doctor/run-doctor-checks.mjs +6 -0
  73. package/src/planner/scope.mjs +5 -1
  74. package/src/tasks/packet/parse-prompt.mjs +31 -1
  75. package/src/tasks/packet/validate-contract.mjs +108 -0
  76. package/src/tasks/packet/validate-prompt.mjs +0 -1
@@ -32,7 +32,6 @@ import { resolveWorktreeSetupHook } from "../config/worktree-setup-hook.mjs";
32
32
  import {
33
33
  assessWaveMergeEligibility,
34
34
  canStartMultiTaskBatch,
35
- countPlanTasks,
36
35
  maxLaneNumberForPlan,
37
36
  resolveBatchStartScope,
38
37
  shouldAutoIntegrateAfterWave,
@@ -72,6 +71,29 @@ export {
72
71
  } from "./engine-scope.mjs";
73
72
  export { loadTaskFileScopePaths, mergeLaneToOrch } from "./engine-lanes.mjs";
74
73
 
74
+ const WORKTREE_SPINE_PATTERN = /[/\\]\.worktrees[/\\]spine-/;
75
+
76
+ /**
77
+ * Detect whether the current process is running inside a spine worker context.
78
+ * Returns a human-readable reason string if nested, or null if safe to proceed.
79
+ *
80
+ * Two guards: (1) SPINE_IS_WORKER env set by worker-host, and
81
+ * (2) projectRoot inside a .worktrees/spine-* directory (catches cases where
82
+ * the env was not inherited but the target is clearly a lane worktree).
83
+ *
84
+ * @param {string} projectRoot — the directory where the batch would run
85
+ * @returns {string | null}
86
+ */
87
+ export function detectNestedWorkerContext(projectRoot) {
88
+ if (process.env.SPINE_IS_WORKER === "1") {
89
+ return "SPINE_IS_WORKER=1 is set (running inside a worker process)";
90
+ }
91
+ if (WORKTREE_SPINE_PATTERN.test(projectRoot)) {
92
+ return "projectRoot is inside a .worktrees/spine-* lane directory";
93
+ }
94
+ return null;
95
+ }
96
+
75
97
  /**
76
98
  * @param {object} options
77
99
  * @param {string} options.projectRoot
@@ -89,6 +111,29 @@ export async function startBatch({
89
111
  forceSuperseded = false,
90
112
  waveFilter = null,
91
113
  }) {
114
+ const nestedReason = detectNestedWorkerContext(projectRoot);
115
+ if (nestedReason) {
116
+ const parentBatchId = process.env.SPINE_BATCH_ID ?? "unknown";
117
+ try {
118
+ appendJournalEvent(projectRoot, parentBatchId, "engine.nested_spawn_blocked", {
119
+ projectRoot,
120
+ parentBatchId,
121
+ reason: nestedReason,
122
+ });
123
+ } catch {
124
+ // Journal may not be writable from a worker worktree; best-effort.
125
+ }
126
+ return {
127
+ ok: false,
128
+ exitCode: 1,
129
+ error: "nested_batch_spawn_blocked",
130
+ output:
131
+ `Nested batch start blocked: ${nestedReason}. ` +
132
+ `Workers must not spawn batch engines. ` +
133
+ `Parent batch: ${parentBatchId}, projectRoot: ${projectRoot}\n`,
134
+ };
135
+ }
136
+
92
137
  if (!skipPreflight) {
93
138
  const preflight = runBatchPreflight({ projectRoot, skipDoctor: false });
94
139
  if (!preflight.ok) {
@@ -10,7 +10,6 @@ import { runEvidenceCommand } from "./evidence-command.mjs";
10
10
  import { readJournalEvents, readJournalTail } from "./journal.mjs";
11
11
  import { generateBatchPostMortem } from "./postmortem.mjs";
12
12
  import { reconcileBatch } from "./reconcile.mjs";
13
- import { loadSpineConfig } from "../config/spine-config-load.mjs";
14
13
 
15
14
  const TASKPLANE_CONFIG_PATH = ".pi/taskplane-config.json";
16
15
 
@@ -185,7 +184,7 @@ export function collectCoreEvidenceBundle(ctx) {
185
184
  * @param {string[]} [ctx.evidenceRefs]
186
185
  */
187
186
  export function collectExtendedEvidenceBundle(ctx) {
188
- const { projectRoot, batchId, batchState = null, config = null } = ctx;
187
+ const { projectRoot, batchId, config = null } = ctx;
189
188
  const dir = evidenceDir(projectRoot, batchId);
190
189
  fs.mkdirSync(dir, { recursive: true });
191
190
 
@@ -5,18 +5,21 @@
5
5
  import { execFileSync } from "node:child_process";
6
6
  import { resolveGitCommitEnv } from "./git-commit-env.mjs";
7
7
 
8
+ const GIT_EXEC_MAX_BUFFER = 10 * 1024 * 1024;
9
+
8
10
  /**
9
11
  * @param {string} cwd
10
12
  * @param {string[]} args
11
- * @param {{ throwOnError?: boolean; projectRoot?: string }} [options]
13
+ * @param {{ throwOnError?: boolean; projectRoot?: string; maxBuffer?: number }} [options]
12
14
  */
13
- export function gitExec(cwd, args, { throwOnError = true, projectRoot } = {}) {
15
+ export function gitExec(cwd, args, { throwOnError = true, projectRoot, maxBuffer = GIT_EXEC_MAX_BUFFER } = {}) {
14
16
  const identityRoot = projectRoot ?? cwd;
15
17
  try {
16
18
  return execFileSync("git", args, {
17
19
  cwd,
18
20
  encoding: "utf-8",
19
21
  stdio: ["ignore", "pipe", "pipe"],
22
+ maxBuffer,
20
23
  env: { ...process.env, ...resolveGitCommitEnv(identityRoot) },
21
24
  }).trim();
22
25
  } catch (err) {
@@ -5,7 +5,7 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { execFileSync } from "node:child_process";
8
- import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
8
+ import { appendJournalEvent, readJournalEventsCached } from "./journal.mjs";
9
9
 
10
10
  const DEFAULT_STALL_TIMEOUT_MIN = 60;
11
11
  const DEFAULT_GRACE_AFTER_PROGRESS_MIN = 15;
@@ -200,7 +200,7 @@ export function collectProgressSignals({
200
200
 
201
201
  let stepCompletedAtMs = null;
202
202
  if (journalContext?.projectRoot && journalContext?.batchId) {
203
- const events = readJournalEvents(journalContext.projectRoot, journalContext.batchId);
203
+ const events = readJournalEventsCached(journalContext.projectRoot, journalContext.batchId);
204
204
  stepCompletedAtMs = findLatestStepCompletedMs(events, {
205
205
  laneNumber: journalContext.laneNumber,
206
206
  laneId: journalContext.laneId,
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Orch integratability checks shared by integrate and lifecycle (avoids import cycles).
3
+ */
4
+
5
+ import { countCommitsAhead } from "./lane-commit.mjs";
6
+
7
+ /**
8
+ * Validates orch branch state before `spine batch complete` (FR-BATCH-16).
9
+ *
10
+ * @param {string} projectRoot
11
+ * @param {object} ctx
12
+ * @param {string} ctx.baseBranch
13
+ * @param {string|null} ctx.orchBranch
14
+ * @param {boolean} ctx.mergeResultsEmpty
15
+ * @param {boolean} ctx.orchMergedToBase
16
+ */
17
+ export function assertOrchIntegratable(projectRoot, ctx) {
18
+ const { baseBranch, orchBranch, mergeResultsEmpty, orchMergedToBase } = ctx;
19
+
20
+ if (orchMergedToBase) {
21
+ return { ok: true, reason: "orch_merged_to_base" };
22
+ }
23
+
24
+ if (mergeResultsEmpty) {
25
+ return { ok: true, reason: "no_merge_claimed" };
26
+ }
27
+
28
+ if (!orchBranch) {
29
+ return {
30
+ ok: false,
31
+ failureClass: "EmptyMerge",
32
+ error: "Batch mergeResults claim success but no orch branch is recorded",
33
+ suggestedCommand: "spine status --diagnose",
34
+ };
35
+ }
36
+
37
+ let commitsAhead = 0;
38
+ try {
39
+ commitsAhead = countCommitsAhead(projectRoot, baseBranch, orchBranch);
40
+ } catch (err) {
41
+ const message = err instanceof Error ? err.message : String(err);
42
+ return {
43
+ ok: false,
44
+ failureClass: "EmptyMerge",
45
+ error: `Cannot compare ${orchBranch} to ${baseBranch}: ${message}`,
46
+ suggestedCommand: "spine status --diagnose",
47
+ };
48
+ }
49
+
50
+ if (commitsAhead === 0) {
51
+ return {
52
+ ok: false,
53
+ failureClass: "EmptyMerge",
54
+ error:
55
+ `Orch branch ${orchBranch} has no commits ahead of ${baseBranch} but mergeResults claim success. ` +
56
+ `Re-run the batch or land lane work on the orch branch before completing.`,
57
+ suggestedCommand: "spine status --diagnose",
58
+ };
59
+ }
60
+
61
+ return {
62
+ ok: false,
63
+ failureClass: "NeedsIntegrate",
64
+ error:
65
+ `Orch branch ${orchBranch} is ${commitsAhead} commit(s) ahead of ${baseBranch} — run integrate before completing the batch record.`,
66
+ suggestedCommand: "spine integrate",
67
+ commitsAhead,
68
+ };
69
+ }
@@ -0,0 +1,354 @@
1
+ /**
2
+ * Isolated orch→base integrate (FR-WT-08 / #91 slice 1).
3
+ * Never checks out baseBranch in the human projectRoot worktree.
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { execFileSync } from "node:child_process";
9
+ import { gitExec } from "./git-exec.mjs";
10
+ import { resolveGitCommitEnv } from "./git-commit-env.mjs";
11
+ import { tryAutoResolveRulesManifestMergeConflict } from "./engine-lanes/merge.mjs";
12
+ import { appendJournalEvent } from "./journal.mjs";
13
+
14
+ export const DEFAULT_SYNC_TIMEOUT_MS = 60_000;
15
+
16
+ /**
17
+ * Record base branch tip at batch start for isolated integrate (FR-WT-08 / #91).
18
+ *
19
+ * @param {string} projectRoot
20
+ * @param {object} state
21
+ */
22
+ export function recordBatchBaseSnapshot(projectRoot, state) {
23
+ const batchId = String(state?.batchId ?? "");
24
+ const baseBranch = String(state?.baseBranch ?? "");
25
+ if (!batchId || !baseBranch) {
26
+ return state;
27
+ }
28
+
29
+ let baseBranchHeadAtStart = "";
30
+ try {
31
+ baseBranchHeadAtStart = gitExec(projectRoot, ["rev-parse", baseBranch], { projectRoot });
32
+ } catch (err) {
33
+ const message = err instanceof Error ? err.message : String(err);
34
+ throw new Error(`Cannot record base snapshot for ${baseBranch}: ${message}`);
35
+ }
36
+
37
+ const integrateWorktreePath = path.relative(
38
+ projectRoot,
39
+ resolveIntegrateWorktreePath(projectRoot, batchId),
40
+ );
41
+
42
+ state.baseBranchHeadAtStart = baseBranchHeadAtStart;
43
+ state.integrateWorktreePath = integrateWorktreePath;
44
+
45
+ appendJournalEvent(projectRoot, batchId, "batch.base_snapshot", {
46
+ baseBranch,
47
+ baseBranchHeadAtStart,
48
+ integrateWorktreePath,
49
+ });
50
+
51
+ return state;
52
+ }
53
+
54
+ /**
55
+ * @param {string} projectRoot
56
+ * @param {string[]} args
57
+ * @param {{ throwOnError?: boolean }} [options]
58
+ */
59
+ function git(projectRoot, args, { throwOnError = true } = {}) {
60
+ return gitExec(projectRoot, args, { throwOnError, projectRoot });
61
+ }
62
+
63
+ /**
64
+ * @param {string} projectRoot
65
+ * @param {string} batchId
66
+ */
67
+ export function resolveIntegrateWorktreePath(projectRoot, batchId) {
68
+ return path.join(projectRoot, ".spine", "worktrees", `integrate-${batchId}`);
69
+ }
70
+
71
+ /**
72
+ * @param {string} projectRoot
73
+ * @param {string} branch
74
+ */
75
+ export function isBranchCheckedOutInWorktree(projectRoot, branch) {
76
+ const current = git(projectRoot, ["branch", "--show-current"], { throwOnError: false });
77
+ return current === branch;
78
+ }
79
+
80
+ /**
81
+ * @param {string} projectRoot
82
+ * @param {string} worktreePath
83
+ */
84
+ function removeIntegrateWorktree(projectRoot, worktreePath) {
85
+ if (!fs.existsSync(worktreePath)) return;
86
+ try {
87
+ git(projectRoot, ["worktree", "remove", "--force", worktreePath], { throwOnError: false });
88
+ } catch {
89
+ // best-effort cleanup
90
+ }
91
+ try {
92
+ fs.rmSync(worktreePath, { recursive: true, force: true, maxRetries: 3 });
93
+ } catch {
94
+ // admin metadata may already be gone
95
+ }
96
+ }
97
+
98
+ /**
99
+ * @param {string} projectRoot
100
+ * @param {string} worktreePath
101
+ * @param {string} baseBranch
102
+ */
103
+ function provisionIntegrateWorktree(projectRoot, worktreePath, baseBranch) {
104
+ fs.mkdirSync(path.dirname(worktreePath), { recursive: true });
105
+ removeIntegrateWorktree(projectRoot, worktreePath);
106
+ git(projectRoot, ["worktree", "add", worktreePath, baseBranch]);
107
+ }
108
+
109
+ /**
110
+ * @param {string} output
111
+ */
112
+ function mergeTreeOutputHasConflict(output) {
113
+ return /CONFLICT/i.test(output);
114
+ }
115
+
116
+ /**
117
+ * @param {object} params
118
+ * @param {string} params.projectRoot
119
+ * @param {string} params.baseBranch
120
+ * @param {string} params.orchBranch
121
+ * @param {string} params.mergeMessage
122
+ */
123
+ function plumbingMergeOrchIntoBase({ projectRoot, baseBranch, orchBranch, mergeMessage }) {
124
+ const baseSha = git(projectRoot, ["rev-parse", baseBranch]);
125
+ const orchSha = git(projectRoot, ["rev-parse", orchBranch]);
126
+
127
+ let mergeTreeOutput = "";
128
+ let treeSha = "";
129
+ try {
130
+ mergeTreeOutput = execFileSync(
131
+ "git",
132
+ ["merge-tree", "--write-tree", baseBranch, orchBranch],
133
+ {
134
+ cwd: projectRoot,
135
+ encoding: "utf-8",
136
+ stdio: ["ignore", "pipe", "pipe"],
137
+ env: { ...process.env },
138
+ },
139
+ ).trim();
140
+ treeSha = mergeTreeOutput.split("\n").pop()?.trim() ?? "";
141
+ } catch (err) {
142
+ const stdout = err && typeof err === "object" && "stdout" in err ? String(err.stdout ?? "") : "";
143
+ const stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr ?? "") : "";
144
+ mergeTreeOutput = `${stdout}\n${stderr}`.trim();
145
+ if (mergeTreeOutputHasConflict(mergeTreeOutput)) {
146
+ return {
147
+ ok: false,
148
+ failureClass: "MergeConflict",
149
+ error: mergeTreeOutput.split("\n").slice(-3).join(" ") || "merge conflict",
150
+ };
151
+ }
152
+ const message = err instanceof Error ? err.message : String(err);
153
+ return {
154
+ ok: false,
155
+ failureClass: "IntegrateFailed",
156
+ error: message,
157
+ };
158
+ }
159
+
160
+ if (!treeSha || mergeTreeOutputHasConflict(mergeTreeOutput)) {
161
+ return {
162
+ ok: false,
163
+ failureClass: "MergeConflict",
164
+ error: mergeTreeOutput || `merge conflict integrating ${orchBranch} into ${baseBranch}`,
165
+ };
166
+ }
167
+
168
+ const mergeCommit = git(
169
+ projectRoot,
170
+ ["commit-tree", treeSha, "-p", baseSha, "-p", orchSha, "-m", mergeMessage],
171
+ );
172
+ git(projectRoot, ["update-ref", `refs/heads/${baseBranch}`, mergeCommit]);
173
+
174
+ return { ok: true, mergeCommit, mode: "plumbing" };
175
+ }
176
+
177
+ /**
178
+ * @param {unknown} err
179
+ * @returns {boolean}
180
+ */
181
+ function isTimeoutError(err) {
182
+ if (!err || typeof err !== "object") return false;
183
+ return /** @type {any} */ (err).killed === true || /** @type {any} */ (err).code === "ETIMEDOUT";
184
+ }
185
+
186
+ /**
187
+ * Git exec with per-subprocess timeout. Uses execFileSync directly to bypass
188
+ * gitExec which does not support timeout passthrough (#114).
189
+ *
190
+ * @param {string} cwd
191
+ * @param {string[]} args
192
+ * @param {{ timeoutMs?: number }} [options]
193
+ * @returns {string}
194
+ */
195
+ function gitWithTimeout(cwd, args, { timeoutMs } = {}) {
196
+ return execFileSync("git", args, {
197
+ cwd,
198
+ encoding: "utf-8",
199
+ stdio: ["ignore", "pipe", "pipe"],
200
+ timeout: timeoutMs,
201
+ env: { ...process.env, ...resolveGitCommitEnv(cwd) },
202
+ }).trim();
203
+ }
204
+
205
+ /**
206
+ * Materialize paths introduced/changed by a plumbing merge without resetting human edits.
207
+ * Returns a result object so callers can detect timeout and emit integrate.failed.
208
+ *
209
+ * @param {string} projectRoot
210
+ * @param {string} baseSha
211
+ * @param {string} mergeCommit
212
+ * @param {{ timeoutMs?: number }} [options]
213
+ * @returns {{ ok: boolean, timedOut?: boolean, error?: string, processedPaths?: number, totalPaths?: number }}
214
+ */
215
+ export function syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeCommit, { timeoutMs = DEFAULT_SYNC_TIMEOUT_MS } = {}) {
216
+ const envTimeoutMs = process.env.SPINE_SYNC_TIMEOUT_MS
217
+ ? Number(process.env.SPINE_SYNC_TIMEOUT_MS)
218
+ : null;
219
+ const effectiveTimeout = envTimeoutMs != null && envTimeoutMs > 0 ? envTimeoutMs : timeoutMs;
220
+
221
+ let output = "";
222
+ try {
223
+ output = gitWithTimeout(
224
+ projectRoot,
225
+ ["diff-tree", "--no-commit-id", "--name-only", "-r", mergeCommit, baseSha],
226
+ { timeoutMs: effectiveTimeout },
227
+ );
228
+ } catch (err) {
229
+ if (isTimeoutError(err)) {
230
+ return { ok: false, timedOut: true, error: `git diff-tree timed out after ${effectiveTimeout}ms` };
231
+ }
232
+ return { ok: false, timedOut: false, error: err instanceof Error ? err.message : String(err) };
233
+ }
234
+
235
+ const paths = output.split("\n").map((line) => line.trim()).filter(Boolean);
236
+ let processedCount = 0;
237
+
238
+ for (const filePath of paths) {
239
+ let content = null;
240
+ try {
241
+ content = gitWithTimeout(
242
+ projectRoot,
243
+ ["show", `${mergeCommit}:${filePath}`],
244
+ { timeoutMs: effectiveTimeout },
245
+ );
246
+ } catch (err) {
247
+ if (isTimeoutError(err)) {
248
+ return {
249
+ ok: false,
250
+ timedOut: true,
251
+ error: `git show timed out for ${filePath} after ${effectiveTimeout}ms`,
252
+ processedPaths: processedCount,
253
+ totalPaths: paths.length,
254
+ };
255
+ }
256
+ continue;
257
+ }
258
+ if (content == null) {
259
+ continue;
260
+ }
261
+
262
+ const absPath = path.join(projectRoot, filePath);
263
+ fs.mkdirSync(path.dirname(absPath), { recursive: true });
264
+ fs.writeFileSync(absPath, content.endsWith("\n") ? content : `${content}\n`, "utf-8");
265
+
266
+ try {
267
+ gitWithTimeout(projectRoot, ["add", "--", filePath], { timeoutMs: effectiveTimeout });
268
+ } catch (err) {
269
+ if (isTimeoutError(err)) {
270
+ return {
271
+ ok: false,
272
+ timedOut: true,
273
+ error: `git add timed out for ${filePath} after ${effectiveTimeout}ms`,
274
+ processedPaths: processedCount,
275
+ totalPaths: paths.length,
276
+ };
277
+ }
278
+ }
279
+ processedCount++;
280
+ }
281
+
282
+ return { ok: true, processedPaths: processedCount, totalPaths: paths.length };
283
+ }
284
+
285
+ /**
286
+ * @param {object} params
287
+ * @param {string} params.projectRoot
288
+ * @param {string} params.worktreePath
289
+ * @param {string} params.baseBranch
290
+ * @param {string} params.orchBranch
291
+ * @param {string} params.mergeMessage
292
+ */
293
+ function mergeInIntegrateWorktree({ projectRoot, worktreePath, baseBranch, orchBranch, mergeMessage }) {
294
+ try {
295
+ git(worktreePath, ["merge", "--no-ff", orchBranch, "-m", mergeMessage]);
296
+ } catch {
297
+ const autoResolved = tryAutoResolveRulesManifestMergeConflict(worktreePath);
298
+ if (!autoResolved.ok) {
299
+ try {
300
+ execFileSync("git", ["merge", "--abort"], {
301
+ cwd: worktreePath,
302
+ stdio: ["ignore", "pipe", "pipe"],
303
+ });
304
+ } catch {
305
+ // best-effort abort
306
+ }
307
+ return {
308
+ ok: false,
309
+ failureClass: autoResolved.failureClass ?? "MergeConflict",
310
+ error: autoResolved.error ?? "merge conflict",
311
+ };
312
+ }
313
+ git(worktreePath, ["commit", "--no-edit"]);
314
+ }
315
+
316
+ const mergeCommit = git(worktreePath, ["rev-parse", "HEAD"]);
317
+ const baseSha = git(projectRoot, ["rev-parse", baseBranch]);
318
+ if (mergeCommit !== baseSha) {
319
+ git(projectRoot, ["update-ref", `refs/heads/${baseBranch}`, mergeCommit]);
320
+ }
321
+
322
+ return { ok: true, mergeCommit, mode: "worktree" };
323
+ }
324
+
325
+ /**
326
+ * Merge orch → base without checking out baseBranch in projectRoot.
327
+ *
328
+ * @param {object} params
329
+ * @param {string} params.projectRoot
330
+ * @param {string} params.baseBranch
331
+ * @param {string} params.orchBranch
332
+ * @param {string} params.batchId
333
+ */
334
+ export function mergeOrchIntoBaseIsolated({ projectRoot, baseBranch, orchBranch, batchId }) {
335
+ const mergeMessage = `integrate ${orchBranch} into ${baseBranch}`;
336
+ const worktreePath = resolveIntegrateWorktreePath(projectRoot, batchId);
337
+
338
+ if (isBranchCheckedOutInWorktree(projectRoot, baseBranch)) {
339
+ return plumbingMergeOrchIntoBase({ projectRoot, baseBranch, orchBranch, mergeMessage });
340
+ }
341
+
342
+ provisionIntegrateWorktree(projectRoot, worktreePath, baseBranch);
343
+ try {
344
+ return mergeInIntegrateWorktree({
345
+ projectRoot,
346
+ worktreePath,
347
+ baseBranch,
348
+ orchBranch,
349
+ mergeMessage,
350
+ });
351
+ } finally {
352
+ removeIntegrateWorktree(projectRoot, worktreePath);
353
+ }
354
+ }