-
Notifications
You must be signed in to change notification settings - Fork 356
Expand file tree
/
Copy pathparallel.ts
More file actions
819 lines (737 loc) · 23.9 KB
/
parallel.ts
File metadata and controls
819 lines (737 loc) · 23.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
import { copyFileSync, cpSync, existsSync, mkdirSync } from "node:fs";
import { basename, join } from "node:path";
import simpleGit from "simple-git";
import { PROGRESS_FILE, RALPHY_DIR } from "../config/loader.ts";
import { logTaskProgress } from "../config/writer.ts";
import type { AIEngine, AIResult } from "../engines/types.ts";
import { getCurrentBranch, returnToBaseBranch } from "../git/branch.ts";
import { syncPrdToIssue } from "../git/issue-sync.ts";
import {
abortMerge,
analyzePreMerge,
deleteLocalBranch,
mergeAgentBranch,
sortByConflictLikelihood,
} from "../git/merge.ts";
import {
canUseWorktrees,
cleanupAgentWorktree,
createAgentWorktree,
getWorktreeBase,
} from "../git/worktree.ts";
import type { Task, TaskSource } from "../tasks/types.ts";
import { formatDuration, logDebug, logError, logInfo, logSuccess, logWarn } from "../ui/logger.ts";
import { notifyTaskComplete, notifyTaskFailed } from "../ui/notify.ts";
import { resolveConflictsWithAI } from "./conflict-resolution.ts";
import { clearDeferredTask, recordDeferredTask } from "./deferred.ts";
import { buildParallelPrompt } from "./prompt.ts";
import { isRetryableError, withRetry } from "./retry.ts";
import { commitSandboxChanges } from "./sandbox-git.ts";
import {
cleanupSandbox,
createSandbox,
DEFAULT_IGNORED,
getModifiedFiles,
getSandboxBase,
isIgnored,
matchesPattern,
} from "./sandbox.ts";
import type { ExecutionOptions, ExecutionResult } from "./sequential.ts";
interface ParallelAgentResult {
task: Task;
agentNum: number;
worktreeDir: string;
branchName: string;
result: AIResult | null;
error?: string;
/** Whether this agent used sandbox mode */
usedSandbox?: boolean;
}
/**
* Run a single agent in a worktree
*/
async function runAgentInWorktree(
engine: AIEngine,
task: Task,
agentNum: number,
baseBranch: string,
worktreeBase: string,
originalDir: string,
prdSource: string,
prdFile: string,
prdIsFolder: boolean,
maxRetries: number,
retryDelay: number,
skipTests: boolean,
skipLint: boolean,
browserEnabled: "auto" | "true" | "false",
modelOverride?: string,
engineArgs?: string[],
): Promise<ParallelAgentResult> {
let worktreeDir = "";
let branchName = "";
try {
// Create worktree
const worktree = await createAgentWorktree(
task.title,
agentNum,
baseBranch,
worktreeBase,
originalDir,
);
worktreeDir = worktree.worktreeDir;
branchName = worktree.branchName;
logDebug(`Agent ${agentNum}: Created worktree at ${worktreeDir}`);
// Copy PRD file or folder to worktree
if (prdSource === "markdown" || prdSource === "yaml" || prdSource === "json") {
const srcPath = join(originalDir, prdFile);
const destPath = join(worktreeDir, prdFile);
if (existsSync(srcPath)) {
copyFileSync(srcPath, destPath);
}
} else if (prdSource === "markdown-folder" && prdIsFolder) {
const srcPath = join(originalDir, prdFile);
const destPath = join(worktreeDir, prdFile);
if (existsSync(srcPath)) {
cpSync(srcPath, destPath, { recursive: true });
}
}
// Ensure .ralphy/ exists in worktree
const ralphyDir = join(worktreeDir, RALPHY_DIR);
if (!existsSync(ralphyDir)) {
mkdirSync(ralphyDir, { recursive: true });
}
// Build prompt
const prompt = buildParallelPrompt({
task: task.title,
progressFile: PROGRESS_FILE,
prdFile,
skipTests,
skipLint,
browserEnabled,
});
// Execute with retry
const engineOptions = {
...(modelOverride && { modelOverride }),
...(engineArgs && engineArgs.length > 0 && { engineArgs }),
};
const result = await withRetry(
async () => {
const res = await engine.execute(prompt, worktreeDir, engineOptions);
if (!res.success && res.error && isRetryableError(res.error)) {
throw new Error(res.error);
}
return res;
},
{ maxRetries, retryDelay },
);
return { task, agentNum, worktreeDir, branchName, result };
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
return { task, agentNum, worktreeDir, branchName, result: null, error: errorMsg };
}
}
/**
* Run a single agent in a lightweight sandbox.
*
* Sandboxes use symlinks for read-only dependencies (node_modules, .git, etc.)
* and copy source files. This is much faster than git worktrees for large repos.
*/
async function runAgentInSandbox(
engine: AIEngine,
task: Task,
agentNum: number,
sandboxBase: string,
originalDir: string,
prdSource: string,
prdFile: string,
prdIsFolder: boolean,
maxRetries: number,
retryDelay: number,
skipTests: boolean,
skipLint: boolean,
browserEnabled: "auto" | "true" | "false",
modelOverride?: string,
engineArgs?: string[],
): Promise<ParallelAgentResult> {
const uniqueSuffix = Math.random().toString(36).substring(2, 8);
const sandboxDir = join(sandboxBase, `agent-${agentNum}-${uniqueSuffix}`);
const branchName = "";
try {
// Create sandbox
const sandboxResult = await createSandbox({
originalDir,
sandboxDir,
agentNum,
});
logDebug(
`Agent ${agentNum}: Created sandbox (${sandboxResult.symlinksCreated} symlinks, ${sandboxResult.filesCopied} copies)`,
);
// Copy PRD file or folder to sandbox (same as worktree mode)
if (prdSource === "markdown" || prdSource === "yaml" || prdSource === "json") {
const srcPath = join(originalDir, prdFile);
const destPath = join(sandboxDir, prdFile);
if (existsSync(srcPath)) {
copyFileSync(srcPath, destPath);
}
} else if (prdSource === "markdown-folder" && prdIsFolder) {
const srcPath = join(originalDir, prdFile);
const destPath = join(sandboxDir, prdFile);
if (existsSync(srcPath)) {
cpSync(srcPath, destPath, { recursive: true });
}
}
// Ensure .ralphy/ exists in sandbox
const ralphyDir = join(sandboxDir, RALPHY_DIR);
if (!existsSync(ralphyDir)) {
mkdirSync(ralphyDir, { recursive: true });
}
// Build prompt
const prompt = buildParallelPrompt({
task: task.title,
progressFile: PROGRESS_FILE,
prdFile,
skipTests,
skipLint,
browserEnabled,
allowCommit: false,
});
// Execute with retry
const engineOptions = {
...(modelOverride && { modelOverride }),
...(engineArgs && engineArgs.length > 0 && { engineArgs }),
};
const result = await withRetry(
async () => {
const res = await engine.execute(prompt, sandboxDir, engineOptions);
if (!res.success && res.error && isRetryableError(res.error)) {
throw new Error(res.error);
}
return res;
},
{ maxRetries, retryDelay },
);
return { task, agentNum, worktreeDir: sandboxDir, branchName, result, usedSandbox: true };
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
return {
task,
agentNum,
worktreeDir: sandboxDir,
branchName,
result: null,
error: errorMsg,
usedSandbox: true,
};
}
}
/**
* Run tasks in parallel using worktrees or sandboxes
*/
export async function runParallel(
options: ExecutionOptions & {
maxParallel: number;
prdSource: string;
prdFile: string;
prdIsFolder?: boolean;
},
): Promise<ExecutionResult> {
const {
engine,
taskSource,
workDir,
skipTests,
skipLint,
dryRun,
maxIterations,
maxRetries,
retryDelay,
baseBranch,
maxParallel,
prdSource,
prdFile,
prdIsFolder = false,
browserEnabled,
modelOverride,
skipMerge,
useSandbox = false,
engineArgs,
syncIssue,
} = options;
const shouldFallbackToSandbox = (error: string | undefined): boolean => {
if (!error) return false;
return error.includes(".git/worktrees") || error.toLowerCase().includes("invalid path");
};
const result: ExecutionResult = {
tasksCompleted: 0,
tasksFailed: 0,
totalInputTokens: 0,
totalOutputTokens: 0,
};
// Determine isolation mode (worktree vs sandbox)
let effectiveUseSandbox = useSandbox;
if (!effectiveUseSandbox && !canUseWorktrees(workDir)) {
logWarn("Worktrees unavailable in this repo; falling back to sandbox mode.");
effectiveUseSandbox = true;
}
const isolationBase = effectiveUseSandbox ? getSandboxBase(workDir) : getWorktreeBase(workDir);
logDebug(`${effectiveUseSandbox ? "Sandbox" : "Worktree"} base: ${isolationBase}`);
if (effectiveUseSandbox) {
logInfo("Using lightweight sandbox mode (faster for large repos)");
}
// Save starting branch to restore after merge phase
const startingBranch = await getCurrentBranch(workDir);
// Save original base branch for merge phase
const originalBaseBranch = baseBranch || startingBranch;
// Track completed branches for merge phase
const completedBranches: string[] = [];
// Global agent counter to ensure unique numbering across batches
let globalAgentNum = 0;
// Track processed tasks in dry-run mode (since we don't modify the source file)
const dryRunProcessedIds = new Set<string>();
// Process tasks in batches
let iteration = 0;
while (true) {
// Check iteration limit
if (maxIterations > 0 && iteration >= maxIterations) {
logInfo(`Reached max iterations (${maxIterations})`);
break;
}
// Get tasks for this batch
let tasks: Task[] = [];
const taskSourceWithGroups = taskSource as TaskSource & {
getParallelGroup?: (title: string) => Promise<number>;
getTasksInGroup?: (group: number) => Promise<Task[]>;
};
if (taskSourceWithGroups.getParallelGroup && taskSourceWithGroups.getTasksInGroup) {
let nextTask = await taskSource.getNextTask();
if (dryRun && nextTask && dryRunProcessedIds.has(nextTask.id)) {
const allTasks = await taskSource.getAllTasks();
nextTask = allTasks.find((task) => !dryRunProcessedIds.has(task.id)) || null;
}
if (!nextTask) break;
const group = await taskSourceWithGroups.getParallelGroup(nextTask.title);
if (group > 0) {
tasks = await taskSourceWithGroups.getTasksInGroup(group);
if (dryRun) {
tasks = tasks.filter((task) => !dryRunProcessedIds.has(task.id));
}
} else {
tasks = [nextTask];
}
} else {
tasks = await taskSource.getAllTasks();
if (dryRun) {
tasks = tasks.filter((task) => !dryRunProcessedIds.has(task.id));
}
}
if (tasks.length === 0) {
logSuccess("All tasks completed!");
break;
}
// Limit to maxParallel
const batch = tasks.slice(0, maxParallel);
iteration++;
const batchStartTime = Date.now();
logInfo(`Batch ${iteration}: ${batch.length} tasks in parallel`);
if (dryRun) {
logInfo("(dry run) Skipping batch");
// Track processed tasks to avoid infinite loop
for (const task of batch) {
dryRunProcessedIds.add(task.id);
}
continue;
}
// Log task names being processed
for (const task of batch) {
logInfo(` -> ${task.title}`);
}
// Run agents in parallel (using sandbox or worktree mode)
const promises = batch.map((task) => {
globalAgentNum++;
const runInSandbox = () =>
runAgentInSandbox(
engine,
task,
globalAgentNum,
getSandboxBase(workDir),
workDir,
prdSource,
prdFile,
prdIsFolder,
maxRetries,
retryDelay,
skipTests,
skipLint,
browserEnabled,
modelOverride,
engineArgs,
);
if (effectiveUseSandbox) {
return runInSandbox();
}
return runAgentInWorktree(
engine,
task,
globalAgentNum,
baseBranch,
isolationBase,
workDir,
prdSource,
prdFile,
prdIsFolder,
maxRetries,
retryDelay,
skipTests,
skipLint,
browserEnabled,
modelOverride,
engineArgs,
).then((res) => {
if (shouldFallbackToSandbox(res.error)) {
logWarn(`Agent ${globalAgentNum}: Worktree unavailable, retrying in sandbox mode.`);
if (res.worktreeDir) {
cleanupAgentWorktree(res.worktreeDir, res.branchName, workDir).catch(() => {
// Ignore cleanup failures during fallback
});
}
return runInSandbox();
}
return res;
});
});
const results = await Promise.all(promises);
// Process results and collect worktrees for parallel cleanup
let sawRetryableFailure = false;
const worktreesToCleanup: Array<{ worktreeDir: string; branchName: string }> = [];
for (const agentResult of results) {
const {
task,
agentNum,
worktreeDir,
result: aiResult,
error,
usedSandbox: agentUsedSandbox,
} = agentResult;
let branchName = agentResult.branchName;
let failureReason: string | undefined = error;
let retryableFailure = false;
let preserveSandbox = false;
if (!failureReason && aiResult?.success && agentUsedSandbox && worktreeDir) {
try {
const modifiedFiles = await getModifiedFiles(worktreeDir, workDir);
const filteredFiles = modifiedFiles.filter((f) => {
if (f.trim() === "") {
return false;
}
const normalized = f.replace(/\\/g, "/");
// Check against all default ignore patterns
for (const pattern of DEFAULT_IGNORED) {
if (pattern.endsWith("/")) {
const dir = pattern.slice(0, -1);
// Directory Patterns (e.g. ".ralphy/")
// Check for exact directory match or paths strictly inside it.
// We append "/" to the prefix check to ensure strict boundary matching,
// preventing false positives for lookalike directories (e.g. ".ralphy-config").
if (normalized === dir || normalized.startsWith(dir + "/")) {
logDebug(`Agent ${agentNum}: Filtered infrastructure file: ${f}`);
return false;
}
} else {
// File/Glob Patterns (e.g. "nul", "*.log")
// We pass the basename to matchesPattern() to support recursive filtering.
// This ensures patterns like "*.log" match "src/debug.log" anywhere in the tree,
// mimicking standard gitignore behavior for patterns without slashes.
// Note: Per git docs, patterns WITHOUT a leading slash match at ANY level.
// Only patterns WITH a slash (e.g. "/nul") would be root-anchored.
const baseName = normalized.split("/").pop() || "";
if (matchesPattern(baseName, pattern, false)) {
logDebug(`Agent ${agentNum}: Filtered ignored file: ${f}`);
return false;
}
}
}
return true;
});
if (filteredFiles.length > 0) {
const commitResult = await commitSandboxChanges(
workDir,
filteredFiles,
worktreeDir,
task.title,
agentNum,
originalBaseBranch,
);
if (commitResult.success) {
branchName = commitResult.branchName;
logDebug(
`Agent ${agentNum}: Committed ${commitResult.filesCommitted} files to ${branchName}`,
);
} else {
failureReason = commitResult.error || "Failed to commit sandbox changes";
preserveSandbox = true; // Preserve work for manual recovery
}
}
} catch (commitErr) {
failureReason = commitErr instanceof Error ? commitErr.message : String(commitErr);
preserveSandbox = true; // Preserve work for manual recovery
}
}
if (failureReason) {
retryableFailure = isRetryableError(failureReason);
if (retryableFailure) {
const deferrals = recordDeferredTask(taskSource.type, task, workDir, prdFile);
if (deferrals >= maxRetries) {
logError(`Task "${task.title}" failed after ${deferrals} deferrals: ${failureReason}`);
logTaskProgress(task.title, "failed", workDir);
result.tasksFailed++;
notifyTaskFailed(task.title, failureReason);
await taskSource.markComplete(task.id);
clearDeferredTask(taskSource.type, task, workDir, prdFile);
retryableFailure = false;
} else {
logWarn(`Task "${task.title}" deferred (${deferrals}/${maxRetries}): ${failureReason}`);
result.tasksFailed++;
}
} else {
logError(`Task "${task.title}" failed: ${failureReason}`);
logTaskProgress(task.title, "failed", workDir);
result.tasksFailed++;
notifyTaskFailed(task.title, failureReason);
// Mark failed task as complete to remove it from the queue
// This prevents infinite retry loops - the task has already been retried maxRetries times
await taskSource.markComplete(task.id);
clearDeferredTask(taskSource.type, task, workDir, prdFile);
}
} else if (aiResult?.success) {
logSuccess(`Task "${task.title}" completed`);
result.totalInputTokens += aiResult.inputTokens;
result.totalOutputTokens += aiResult.outputTokens;
await taskSource.markComplete(task.id);
logTaskProgress(task.title, "completed", workDir);
result.tasksCompleted++;
notifyTaskComplete(task.title);
clearDeferredTask(taskSource.type, task, workDir, prdFile);
// Track successful branch for merge phase
if (branchName) {
completedBranches.push(branchName);
}
} else {
const errMsg = aiResult?.error || "Unknown error";
retryableFailure = isRetryableError(errMsg);
if (retryableFailure) {
const deferrals = recordDeferredTask(taskSource.type, task, workDir, prdFile);
if (deferrals >= maxRetries) {
logError(`Task "${task.title}" failed after ${deferrals} deferrals: ${errMsg}`);
logTaskProgress(task.title, "failed", workDir);
result.tasksFailed++;
notifyTaskFailed(task.title, errMsg);
failureReason = errMsg;
await taskSource.markComplete(task.id);
clearDeferredTask(taskSource.type, task, workDir, prdFile);
retryableFailure = false;
} else {
logWarn(`Task "${task.title}" deferred (${deferrals}/${maxRetries}): ${errMsg}`);
result.tasksFailed++;
failureReason = errMsg;
}
} else {
logError(`Task "${task.title}" failed: ${errMsg}`);
logTaskProgress(task.title, "failed", workDir);
result.tasksFailed++;
notifyTaskFailed(task.title, errMsg);
failureReason = errMsg;
// Mark failed task as complete to remove it from the queue
// This prevents infinite retry loops - the task has already been retried maxRetries times
await taskSource.markComplete(task.id);
clearDeferredTask(taskSource.type, task, workDir, prdFile);
}
}
// Cleanup sandbox inline or collect worktree for parallel cleanup
if (worktreeDir) {
if (agentUsedSandbox) {
if (failureReason || preserveSandbox) {
logWarn(`Sandbox preserved for manual review: ${worktreeDir}`);
} else {
// Sandbox cleanup is simpler - just delete the directory
await cleanupSandbox(worktreeDir);
logDebug(`Cleaned up sandbox: ${worktreeDir}`);
}
} else {
// Collect worktree for parallel cleanup below
worktreesToCleanup.push({ worktreeDir, branchName });
}
}
if (retryableFailure) {
sawRetryableFailure = true;
}
}
// Cleanup all worktrees in parallel
if (worktreesToCleanup.length > 0) {
const cleanupResults = await Promise.all(
worktreesToCleanup.map(({ worktreeDir, branchName }) =>
cleanupAgentWorktree(worktreeDir, branchName, workDir).then((cleanup) => ({
worktreeDir,
leftInPlace: cleanup.leftInPlace,
})),
),
);
// Log any worktrees left in place
for (const { worktreeDir, leftInPlace } of cleanupResults) {
if (leftInPlace) {
logInfo(`Worktree left in place (uncommitted changes): ${worktreeDir}`);
}
}
}
// Sync PRD to GitHub issue once per batch (after all tasks processed)
// This prevents multiple concurrent syncs and reduces API calls
if (syncIssue && prdFile && result.tasksCompleted > 0) {
await syncPrdToIssue(prdFile, syncIssue, workDir);
}
// Log batch completion time
const batchDuration = formatDuration(Date.now() - batchStartTime);
logInfo(`Batch ${iteration} completed in ${batchDuration}`);
// If any retryable failure occurred, stop the run to allow retry later
if (sawRetryableFailure) {
logWarn("Stopping early due to retryable errors. Try again later.");
break;
}
}
// Merge phase: merge completed branches back to base branch
if (!skipMerge && !dryRun && completedBranches.length > 0) {
const git = simpleGit(workDir);
let stashed = false;
try {
const status = await git.status();
const hasChanges = status.files.length > 0 || status.not_added.length > 0;
if (hasChanges) {
await git.stash(["push", "-u", "-m", "ralphy-merge-stash"]);
stashed = true;
logDebug("Stashed local changes before merge phase");
}
} catch (stashErr) {
logWarn(`Failed to stash local changes: ${stashErr}`);
}
try {
await mergeCompletedBranches(
completedBranches,
originalBaseBranch,
engine,
workDir,
modelOverride,
engineArgs,
);
// Restore starting branch if we're not already on it
const currentBranch = await getCurrentBranch(workDir);
if (currentBranch !== startingBranch) {
logDebug(`Restoring starting branch: ${startingBranch}`);
await returnToBaseBranch(startingBranch, workDir);
}
} finally {
if (stashed) {
try {
await git.stash(["pop"]);
logDebug("Restored stashed changes after merge phase");
} catch (stashErr) {
logWarn(`Failed to restore stashed changes: ${stashErr}`);
}
}
}
}
return result;
}
/**
* Merge completed branches back to the base branch.
*
* Optimized merge phase:
* 1. Parallel pre-merge analysis (git diff doesn't require locks)
* 2. Sort branches by conflict likelihood (merge clean ones first)
* 3. Sequential merges (git locking requirement)
* 4. Parallel branch deletion
*/
async function mergeCompletedBranches(
branches: string[],
targetBranch: string,
engine: AIEngine,
workDir: string,
modelOverride?: string,
engineArgs?: string[],
): Promise<void> {
if (branches.length === 0) {
return;
}
const mergeStartTime = Date.now();
logInfo(`\nMerge phase: merging ${branches.length} branch(es) into ${targetBranch}`);
// Stage 1: Parallel pre-merge analysis
// Run git diff for all branches in parallel (doesn't require locks)
logDebug("Analyzing branches for potential conflicts...");
const analyses = await Promise.all(
branches.map((branch) => analyzePreMerge(branch, targetBranch, workDir)),
);
// Stage 2: Sort by conflict likelihood (merge clean ones first)
// This reduces the chance of early conflicts blocking later clean merges
const sortedAnalyses = sortByConflictLikelihood(analyses);
const sortedBranches = sortedAnalyses.map((a) => a.branch);
if (sortedBranches[0] !== branches[0]) {
logDebug("Reordered branches to minimize conflicts");
}
// Stage 3: Sequential merges (git operations require this)
const merged: string[] = [];
const failed: string[] = [];
for (const branch of sortedBranches) {
const analysis = analyses.find((a) => a.branch === branch);
const fileCount = analysis?.fileCount ?? 0;
logInfo(`Merging ${branch}... (${fileCount} file${fileCount === 1 ? "" : "s"} changed)`);
const mergeResult = await mergeAgentBranch(branch, targetBranch, workDir);
if (mergeResult.success) {
logSuccess(`Merged ${branch}`);
merged.push(branch);
} else if (mergeResult.hasConflicts && mergeResult.conflictedFiles) {
// Try AI-assisted conflict resolution
logWarn(`Merge conflict in ${branch}, attempting AI resolution...`);
const resolved = await resolveConflictsWithAI(
engine,
mergeResult.conflictedFiles,
branch,
workDir,
modelOverride,
engineArgs,
);
if (resolved) {
logSuccess(`Resolved conflicts and merged ${branch}`);
merged.push(branch);
} else {
logError(`Failed to resolve conflicts for ${branch}`);
await abortMerge(workDir);
failed.push(branch);
}
} else {
logError(`Failed to merge ${branch}: ${mergeResult.error || "Unknown error"}`);
failed.push(branch);
}
}
// Stage 4: Parallel branch deletion
// Delete all successfully merged branches in parallel
if (merged.length > 0) {
const deleteResults = await Promise.all(
merged.map(async (branch) => {
const deleted = await deleteLocalBranch(branch, workDir, true);
return { branch, deleted };
}),
);
for (const { branch, deleted } of deleteResults) {
if (deleted) {
logDebug(`Deleted merged branch: ${branch}`);
}
}
}
// Summary
const mergeDuration = formatDuration(Date.now() - mergeStartTime);
if (merged.length > 0) {
logSuccess(`Successfully merged ${merged.length} branch(es) in ${mergeDuration}`);
}
if (failed.length > 0) {
logWarn(`Failed to merge ${failed.length} branch(es): ${failed.join(", ")}`);
logInfo("These branches have been preserved for manual review.");
}
}