Repository navigation
Expand file tree
/
Copy pathpr-worktree-codex.ts
More file actions
1745 lines (1557 loc) · 58.5 KB
/
Copy pathpr-worktree-codex.ts
File metadata and controls
1745 lines (1557 loc) · 58.5 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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { execFile } from "node:child_process";
import type { ChildProcess, ExecFileException, ExecFileOptions } from "node:child_process";
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import process from "node:process";
import {
Codex,
type SandboxMode,
type Thread,
type ThreadEvent,
type ThreadItem,
type ThreadOptions,
type Usage,
type CommandExecutionStatus,
type McpToolCallStatus,
type PatchApplyStatus,
} from "@codex-native/sdk";
type CommandResult = { stdout: string; stderr: string };
type CommandWithOutputResult = { stdout: string; stderr: string; exitCode: number };
type CommandError = ExecFileException & {
stdout?: string;
stderr?: string;
exitCode?: number | null;
};
interface RunCommandWithOutputOptions extends ExecFileOptions {
onStdout?: (chunk: Buffer | string) => void;
onStderr?: (chunk: Buffer | string) => void;
}
interface PushStatus {
success: boolean;
skipped: boolean;
reason: string;
source?: string;
error?: unknown;
}
interface GhChecksResult {
success: boolean;
stdout: string;
stderr: string;
exitCode: number | null;
}
interface RunConfig {
repoRoot: string;
worktreeRoot: string;
concurrency: number;
remote: string;
dryRun: boolean;
repoSlug: string | null;
repoOwner: string | null;
maxFixAttempts: number;
}
type CodexTurnSummary = {
finalResponse: string;
items: ThreadItem[];
usage: Usage | null;
};
type MergeVerification = {
state?: string;
error?: unknown;
};
type RunResult = {
pr: PullRequestInfo;
worktreePath: string;
localBranch?: string;
mergeTurn?: CodexTurnSummary;
fixTurns?: CodexTurnSummary[];
pushAllowed?: boolean;
pushStatuses?: PushStatus[];
ghChecks?: GhChecksResult;
mergePrTurn?: CodexTurnSummary | null;
prMerged?: boolean;
mergeVerification?: MergeVerification | null;
buildFixTurns?: CodexTurnSummary[];
dryRun?: boolean;
error?: unknown;
};
type PushOutcome = PushStatus & { pr: PullRequestInfo };
type CleanupOutcome = {
path: string;
success: boolean;
error?: unknown;
};
type BuildErrorDetails = {
stdout: string;
stderr: string;
exitCode: number | null;
message: string;
};
type ThreadKind = "build" | "merge" | "fix" | "merge_pr";
type ThreadRegistryRecord = Partial<Record<ThreadKind, string>>;
type ThreadRegistryData = Record<string, ThreadRegistryRecord>;
interface PullRequestInfo {
number: number;
title: string;
headRefName: string;
headRepositoryOwnerLogin: string | null;
headRepositoryName: string | null;
url: string;
}
const DEFAULT_REMOTE = "origin";
const DEFAULT_CONCURRENCY = 4;
const DEFAULT_MAX_FIX_ATTEMPTS = 3;
const THREAD_REGISTRY_FILENAME = ".codex-pr-threads.json";
const activeProcesses = new Set<ChildProcess>();
function registerProcess(child: ChildProcess) {
activeProcesses.add(child);
child.on("exit", () => activeProcesses.delete(child));
return child;
}
function cleanupAllProcesses() {
for (const child of activeProcesses) {
try {
child.kill("SIGTERM");
} catch (error) {
// Ignore errors during cleanup
}
}
activeProcesses.clear();
}
function escapeForAppleScriptPath(value: string) {
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}
process.on("SIGINT", () => {
console.log("\nReceived SIGINT, cleaning up...");
cleanupAllProcesses();
process.exit(130);
});
process.on("SIGTERM", () => {
console.log("\nReceived SIGTERM, cleaning up...");
cleanupAllProcesses();
process.exit(143);
});
const THREAD_KIND_VALUES: ThreadKind[] = ["build", "merge", "fix", "merge_pr"];
const THREAD_KIND_LABELS: Record<ThreadKind, string> = {
build: "build remediation",
merge: "merge preparation",
fix: "remediation",
merge_pr: "PR merge",
};
class ThreadRegistry {
private readonly filePath: string;
private data: ThreadRegistryData = {};
private loaded = false;
private loadingPromise: Promise<void> | null = null;
private writeChain: Promise<void> = Promise.resolve();
constructor(filePath: string) {
this.filePath = filePath;
}
async initialize(): Promise<void> {
await this.ensureLoaded();
}
async get(prNumber: number, kind: ThreadKind): Promise<string | null> {
await this.ensureLoaded();
const key = String(prNumber);
return this.data[key]?.[kind] ?? null;
}
async set(prNumber: number, kind: ThreadKind, threadId: string): Promise<void> {
if (!threadId) {
return;
}
await this.runExclusive(async () => {
await this.ensureLoaded();
const key = String(prNumber);
if (!this.data[key]) {
this.data[key] = {};
}
this.data[key]![kind] = threadId;
await this.persist();
});
}
async clear(prNumber: number, kind?: ThreadKind): Promise<void> {
await this.runExclusive(async () => {
await this.ensureLoaded();
const key = String(prNumber);
const record = this.data[key];
if (!record) {
return;
}
if (kind) {
delete record[kind];
if (Object.keys(record).length === 0) {
delete this.data[key];
}
} else {
delete this.data[key];
}
await this.persist();
});
}
private async ensureLoaded(): Promise<void> {
if (this.loaded) {
return;
}
if (this.loadingPromise) {
await this.loadingPromise;
return;
}
this.loadingPromise = (async () => {
try {
const contents = await fs.readFile(this.filePath, "utf8");
this.data = this.normalizeData(JSON.parse(contents));
} catch (error) {
const code = (error as NodeJS.ErrnoException)?.code;
if (code !== "ENOENT") {
console.warn(`Failed to load Codex thread registry at ${this.filePath}: ${error instanceof Error ? error.message : String(error)}`);
}
this.data = {};
}
this.loaded = true;
})();
await this.loadingPromise;
}
private normalizeData(value: unknown): ThreadRegistryData {
if (!value || typeof value !== "object") {
return {};
}
const normalized: ThreadRegistryData = {};
for (const [prNumber, recordValue] of Object.entries(value as Record<string, unknown>)) {
if (!recordValue || typeof recordValue !== "object") {
continue;
}
const record: ThreadRegistryRecord = {};
for (const kind of THREAD_KIND_VALUES) {
const threadId = (recordValue as Record<string, unknown>)[kind];
if (typeof threadId === "string" && threadId.trim()) {
record[kind] = threadId;
}
}
if (Object.keys(record).length > 0) {
normalized[prNumber] = record;
}
}
return normalized;
}
private async persist(): Promise<void> {
await fs.mkdir(path.dirname(this.filePath), { recursive: true });
await fs.writeFile(this.filePath, `${JSON.stringify(this.data, null, 2)}\n`);
}
private runExclusive<T>(fn: () => Promise<T> | T): Promise<T> {
const next = this.writeChain.then(() => fn());
this.writeChain = next.then(
() => undefined,
() => undefined,
);
return next;
}
}
type ThreadAcquisitionParams = {
codex: Codex;
registry: ThreadRegistry;
prNumber: number;
kind: ThreadKind;
prefix: string;
makeThreadOptions: () => ThreadOptions;
};
async function acquireThreadForKind(params: ThreadAcquisitionParams): Promise<Thread> {
const { codex, registry, prNumber, kind, makeThreadOptions } = params;
const existingId = await registry.get(prNumber, kind);
if (existingId) {
try {
console.log(`🔄 [PR ${prNumber}] Resuming ${THREAD_KIND_LABELS[kind]} thread`);
return codex.resumeThread(existingId, makeThreadOptions());
} catch (error) {
console.log(`⚠️ [PR ${prNumber}] Failed to resume thread, starting new one`);
await clearThreadIdWithWarning(registry, prNumber, kind);
}
}
console.log(`🆕 [PR ${prNumber}] Starting new ${THREAD_KIND_LABELS[kind]} thread`);
return codex.startThread(makeThreadOptions());
}
async function persistThreadIdWithWarning(
registry: ThreadRegistry,
prNumber: number,
kind: ThreadKind,
threadId: string | null,
): Promise<void> {
if (!threadId) {
return;
}
try {
await registry.set(prNumber, kind, threadId);
} catch (error) {
console.log(`⚠️ [PR ${prNumber}] Warning: failed to persist thread id: ${formatErrorMessage(error)}`);
}
}
async function clearThreadIdWithWarning(
registry: ThreadRegistry,
prNumber: number,
kind: ThreadKind,
): Promise<void> {
try {
await registry.clear(prNumber, kind);
} catch (error) {
console.log(`⚠️ [PR ${prNumber}] Warning: failed to clear thread id: ${formatErrorMessage(error)}`);
}
}
function formatErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
return String(error);
}
async function main() {
const config = await buildConfig();
await ensureBinaryAvailable("git");
await ensureBinaryAvailable("gh");
await ensureBinaryAvailable("pnpm");
await fs.mkdir(config.worktreeRoot, { recursive: true });
const threadRegistryPath = path.join(config.repoRoot, THREAD_REGISTRY_FILENAME);
const threadRegistry = new ThreadRegistry(threadRegistryPath);
await threadRegistry.initialize();
const prs = await listOpenPullRequests(config);
if (prs.length === 0) {
console.log("🎉 No open pull requests detected. Nothing to do.");
return;
}
console.log(`🔍 Processing ${prs.length} open pull request${prs.length === 1 ? "" : "s"} with concurrency ${config.concurrency}`);
const existingWorktrees = await getExistingWorktreePaths(config.repoRoot);
const createdWorktrees = new Set<string>();
const gitMutex = createMutex();
const installMutex = createMutex();
const results = await runWithConcurrency<PullRequestInfo, RunResult>(prs, config.concurrency, async (pr) => {
const safeSlug = slugifyRef(pr.headRefName) || `head-${pr.number}`;
const worktreeDir = `pr-${pr.number}-${safeSlug}`;
const worktreePath = path.join(config.worktreeRoot, worktreeDir);
const fetchRef = `pull/${pr.number}/head`;
const localBranch = pr.headRefName;
let createdWorktree = false;
const basePrefix = formatPrefix(pr);
const pushAllowed = isPushAllowed(pr, config);
const pushStatuses: PushStatus[] = pushAllowed
? []
: [{ success: false, skipped: true, reason: "push-not-allowed", source: "pre" }];
const buildFixTurns: CodexTurnSummary[] = [];
try {
await gitMutex.run(async () => {
await runCommand("git", [
"fetch",
"--force",
config.remote,
`+${fetchRef}:refs/remotes/${config.remote}/${pr.headRefName}`,
], { cwd: config.repoRoot });
const knownWorktree = existingWorktrees.has(worktreePath);
const pathAlreadyExists = await pathExists(worktreePath);
if (!knownWorktree && pathAlreadyExists) {
// Remove stale directory so worktree add succeeds.
await fs.rm(worktreePath, { recursive: true, force: true });
}
if (!knownWorktree) {
await runCommand("git", [
"worktree",
"add",
"--force",
"-B",
localBranch,
worktreePath,
`refs/remotes/${config.remote}/${pr.headRefName}`,
], { cwd: config.repoRoot });
existingWorktrees.add(worktreePath);
createdWorktrees.add(worktreePath);
console.log(`✓ [PR ${pr.number}] Created worktree`);
createdWorktree = true;
} else {
await runCommand("git", ["reset", "--hard", `refs/remotes/${config.remote}/${pr.headRefName}`], { cwd: worktreePath });
await runCommand("git", ["clean", "-fdx"], { cwd: worktreePath });
console.log(`✓ [PR ${pr.number}] Refreshed worktree`);
}
await runCommand("git", ["branch", `--set-upstream-to=${config.remote}/${pr.headRefName}`, localBranch], { cwd: worktreePath });
});
} catch (error) {
console.error(`[PR ${pr.number}] Failed to prepare worktree:`, error);
return { pr, worktreePath, error };
}
try {
await runCommand("git", ["fetch", config.remote, "main"], { cwd: worktreePath });
} catch (error) {
console.warn(`[PR ${pr.number}] Warning: failed to fetch ${config.remote}/main: ${formatCommandError(error)}`);
}
const needsInstall = createdWorktree || !(await pathExists(path.join(worktreePath, "node_modules")));
let codexInstance: Codex | null = null;
const ensureCodexInstance = () => {
if (!codexInstance) {
codexInstance = new Codex();
}
return codexInstance;
};
if (needsInstall) {
try {
console.log(`📦 [PR ${pr.number}] Running pnpm install...`);
await installMutex.run(async () => {
await runCommand("pnpm", ["install"], { cwd: worktreePath });
});
console.log(`✓ [PR ${pr.number}] Installation complete`);
} catch (error) {
console.error(`❌ [PR ${pr.number}] pnpm install failed:`, error);
return { pr, worktreePath, error };
}
}
const runBuildAll = async (): Promise<BuildErrorDetails | null> => {
console.log(`🔨 [PR ${pr.number}] Building sdk...`);
try {
await runCommand("pnpm", ["run", "sdk:build"], { cwd: worktreePath });
console.log(`✓ [PR ${pr.number}] Build completed successfully`);
return null;
} catch (error) {
const commandError = error as Partial<CommandError> & { code?: number };
const stdout = normalizeCommandOutput(commandError.stdout);
const stderr = normalizeCommandOutput(commandError.stderr);
const exitCode = typeof commandError.exitCode === "number"
? commandError.exitCode
: commandError.code ?? null;
const message = commandError.message ?? (error instanceof Error ? error.message : String(error));
console.log(`❌ [PR ${pr.number}] Build failed (exit ${exitCode ?? "unknown"})`);
return { stdout, stderr, exitCode, message };
}
};
let buildError = await runBuildAll();
let buildAttempts = 0;
while (buildError && !config.dryRun && buildAttempts < config.maxFixAttempts) {
buildAttempts += 1;
const codex = ensureCodexInstance();
const sandboxMode: SandboxMode = "danger-full-access";
const makeThreadOptions = (): ThreadOptions => ({
workingDirectory: worktreePath,
sandboxMode,
skipGitRepoCheck: true,
});
const buildPrefix = `${basePrefix} [build#${buildAttempts}]`;
const buildThread = await acquireThreadForKind({
codex,
registry: threadRegistry,
prNumber: pr.number,
kind: "build",
prefix: buildPrefix,
makeThreadOptions,
});
const buildPrompt = buildBuildFailurePrompt(pr, worktreePath, buildError, buildAttempts);
console.log(`\n🛠️ [PR ${pr.number}] Build remediation attempt #${buildAttempts}`);
console.log(`────────────────────────────────────────────────────────────────────────────────`);
let buildFixTurn: CodexTurnSummary;
try {
buildFixTurn = await runCodexTurnWithLogging(buildThread, buildPrompt, buildPrefix);
} finally {
await persistThreadIdWithWarning(threadRegistry, pr.number, "build", buildThread.id);
}
buildFixTurns.push(buildFixTurn);
console.log(`\n📝 Build remediation summary:`);
console.log(buildFixTurn.finalResponse.trim());
logTurnHighlights(buildPrefix, buildFixTurn.items);
if (pushAllowed) {
try {
await ensurePushed(pr, worktreePath, config.remote, localBranch);
pushStatuses.push({ success: true, skipped: false, reason: `post-build-${buildAttempts}`, source: "build" });
console.log(`🚀 [PR ${pr.number}] Pushed build fixes`);
} catch (pushError) {
pushStatuses.push({ success: false, skipped: false, reason: `post-build-${buildAttempts}-failed`, source: "build", error: pushError });
console.log(`❌ [PR ${pr.number}] Push failed: ${formatCommandError(pushError)}`);
}
} else {
console.log(`⚠️ [PR ${pr.number}] Push unavailable (external fork)`);
}
buildError = await runBuildAll();
}
if (buildError) {
console.log(`⚠️ [PR ${pr.number}] Build still failing after ${buildAttempts} attempt(s)`);
}
if (config.dryRun) {
console.log(`🏃 [PR ${pr.number}] Dry run mode; skipping automation`);
return { pr, worktreePath, dryRun: true };
}
try {
const codex = ensureCodexInstance();
const sandboxMode: SandboxMode = "danger-full-access";
const makeThreadOptions = (): ThreadOptions => ({
workingDirectory: worktreePath,
sandboxMode,
skipGitRepoCheck: true,
});
const mergePrefix = `${basePrefix} [merge]`;
const mergeThread = await acquireThreadForKind({
codex,
registry: threadRegistry,
prNumber: pr.number,
kind: "merge",
prefix: mergePrefix,
makeThreadOptions,
});
const mergePrompt = buildMergePrompt(pr, worktreePath);
console.log(`\n🔀 [PR ${pr.number}] Merging main branch`);
console.log(`────────────────────────────────────────────────────────────────────────────────`);
let mergeTurn: CodexTurnSummary;
try {
mergeTurn = await runCodexTurnWithLogging(mergeThread, mergePrompt, mergePrefix);
} finally {
await persistThreadIdWithWarning(threadRegistry, pr.number, "merge", mergeThread.id);
}
console.log(`\n📝 Merge summary:`);
console.log(mergeTurn.finalResponse.trim());
logTurnHighlights(mergePrefix, mergeTurn.items);
const newExamples = await detectNewExamples(worktreePath, config.remote);
let ghChecksResult = await runGhPrChecks(pr, worktreePath, basePrefix);
const fixTurns: CodexTurnSummary[] = [];
let mergePrTurn: CodexTurnSummary | null = null;
let prMerged = false;
let mergeVerification: MergeVerification | null = null;
if (pushAllowed) {
try {
await ensurePushed(pr, worktreePath, config.remote, localBranch);
pushStatuses.push({ success: true, skipped: false, reason: "post-merge", source: "merge" });
console.log(`🚀 [PR ${pr.number}] Pushed merge changes`);
} catch (pushError) {
pushStatuses.push({ success: false, skipped: false, reason: "post-merge-failed", source: "merge", error: pushError });
console.log(`❌ [PR ${pr.number}] Push failed: ${formatCommandError(pushError)}`);
throw pushError;
}
} else {
console.log(`⚠️ [PR ${pr.number}] Push unavailable (external fork)`);
}
let attempts = 0;
while (!ghChecksResult.success && attempts < config.maxFixAttempts) {
attempts += 1;
const fixPrefix = `${basePrefix} [checks#${attempts}]`;
const fixThread = await acquireThreadForKind({
codex,
registry: threadRegistry,
prNumber: pr.number,
kind: "fix",
prefix: fixPrefix,
makeThreadOptions,
});
const fixPrompt = buildFixPrompt(pr, worktreePath, newExamples, ghChecksResult, attempts);
console.log(`\n🛠️ [PR ${pr.number}] CI remediation attempt #${attempts}`);
console.log(`────────────────────────────────────────────────────────────────────────────────`);
let fixTurn: CodexTurnSummary;
try {
fixTurn = await runCodexTurnWithLogging(fixThread, fixPrompt, fixPrefix);
} finally {
await persistThreadIdWithWarning(threadRegistry, pr.number, "fix", fixThread.id);
}
fixTurns.push(fixTurn);
console.log(`\n📝 Remediation summary:`);
console.log(fixTurn.finalResponse.trim());
logTurnHighlights(fixPrefix, fixTurn.items);
if (pushAllowed) {
try {
await ensurePushed(pr, worktreePath, config.remote, localBranch);
pushStatuses.push({ success: true, skipped: false, reason: `post-fix-${attempts}`, source: "fix" });
console.log(`🚀 [PR ${pr.number}] Pushed CI fixes`);
} catch (pushError) {
pushStatuses.push({ success: false, skipped: false, reason: `post-fix-${attempts}-failed`, source: "fix", error: pushError });
console.log(`❌ [PR ${pr.number}] Push failed: ${formatCommandError(pushError)}`);
throw pushError;
}
} else {
console.log(`⚠️ [PR ${pr.number}] Push unavailable (external fork)`);
}
ghChecksResult = await runGhPrChecks(pr, worktreePath, basePrefix);
}
if (!ghChecksResult.success) {
console.log(`⚠️ [PR ${pr.number}] CI checks still failing after ${attempts} attempt(s)`);
} else if (!pushAllowed) {
console.log(`✅ [PR ${pr.number}] CI checks passed (manual merge required for external fork)`);
} else {
console.log(`✅ [PR ${pr.number}] CI checks passed; preparing to merge`);
const mergePrPrefix = `${basePrefix} [pr-merge]`;
const mergePrThread = await acquireThreadForKind({
codex,
registry: threadRegistry,
prNumber: pr.number,
kind: "merge_pr",
prefix: mergePrPrefix,
makeThreadOptions,
});
const mergePrPrompt = buildPrMergePrompt(pr, worktreePath);
console.log(`\n🎯 [PR ${pr.number}] Merging pull request`);
console.log(`────────────────────────────────────────────────────────────────────────────────`);
try {
mergePrTurn = await runCodexTurnWithLogging(mergePrThread, mergePrPrompt, mergePrPrefix);
} finally {
await persistThreadIdWithWarning(threadRegistry, pr.number, "merge_pr", mergePrThread.id);
}
console.log(`\n📝 PR merge summary:`);
console.log(mergePrTurn.finalResponse.trim());
logTurnHighlights(mergePrPrefix, mergePrTurn.items);
try {
const { stdout } = await runCommand("gh", [
"pr",
"view",
String(pr.number),
"--json",
"state",
"--jq",
".state",
], { cwd: worktreePath });
const state = stdout.trim();
mergeVerification = { state };
if (state && state.toUpperCase() === "MERGED") {
prMerged = true;
console.log(`🎉 [PR ${pr.number}] Successfully merged!`);
} else {
console.log(`⚠️ [PR ${pr.number}] Post-merge state: ${state || "unknown"}`);
}
} catch (verifyError) {
mergeVerification = { error: verifyError };
console.log(`❌ [PR ${pr.number}] Failed to verify merge: ${formatCommandError(verifyError)}`);
}
}
return {
pr,
worktreePath,
localBranch,
mergeTurn,
fixTurns,
pushAllowed,
pushStatuses,
ghChecks: ghChecksResult,
mergePrTurn,
prMerged,
mergeVerification,
buildFixTurns,
};
} catch (error) {
console.error(`[PR ${pr.number}] Codex automation failed:`, error);
return { pr, worktreePath, error, buildFixTurns };
}
});
const pushOutcomes: PushOutcome[] = [];
for (const result of results) {
if (!result || result.error || result.dryRun) {
continue;
}
if (Array.isArray(result.pushStatuses) && result.pushStatuses.length > 0) {
for (const status of result.pushStatuses) {
if (status.reason === "push-not-allowed") {
console.log(`[PR ${result.pr.number}] Push skipped (head repository owner differs from ${config.repoOwner ?? "origin owner"}).`);
}
pushOutcomes.push({ pr: result.pr, ...status });
}
continue;
}
if (!result.pushAllowed) {
console.log(`[PR ${result.pr.number}] Push skipped (head repository owner differs from ${config.repoOwner ?? "origin owner"}).`);
pushOutcomes.push({ pr: result.pr, success: false, skipped: true, reason: "push-not-allowed" });
continue;
}
try {
const localBranch = result.localBranch ?? result.pr.headRefName;
await ensurePushed(result.pr, result.worktreePath, config.remote, localBranch);
pushOutcomes.push({ pr: result.pr, success: true, skipped: false, reason: "post-run", source: "post" });
} catch (error) {
pushOutcomes.push({ pr: result.pr, success: false, skipped: false, reason: "post-run-failed", source: "post", error });
console.error(`[PR ${result.pr.number}] Post-run push failed:`, error);
}
}
const cleanupOutcomes: CleanupOutcome[] = [];
for (const worktreePath of createdWorktrees) {
try {
if (process.platform === "darwin") {
const escapedPath = escapeForAppleScriptPath(worktreePath);
await runCommand("osascript", [
"-e",
`tell application "Finder" to delete POSIX file "${escapedPath}"`,
]);
} else {
const trashPath = path.join(os.tmpdir(), `codex-worktree-trash-${Date.now()}-${Math.random().toString(36).slice(2)}`);
await fs.rename(worktreePath, trashPath);
fs.rm(trashPath, { recursive: true, force: true }).catch(() => {});
}
await runCommand("git", ["worktree", "prune"], { cwd: config.repoRoot });
cleanupOutcomes.push({ path: worktreePath, success: true });
} catch (error) {
cleanupOutcomes.push({ path: worktreePath, success: false, error });
console.error(`Failed to clean worktree ${worktreePath}:`, error);
}
}
summarizeResults(results, pushOutcomes, cleanupOutcomes);
}
async function buildConfig(): Promise<RunConfig> {
const args = process.argv.slice(2);
let repoRoot = process.cwd();
let worktreeRoot = path.resolve(repoRoot, "..", "codex-pr-worktrees");
let concurrency = DEFAULT_CONCURRENCY;
let remote = DEFAULT_REMOTE;
let dryRun = false;
for (let i = 0; i < args.length; i += 1) {
const arg = args[i];
switch (arg) {
case "--repo": {
const value = args[i + 1];
if (!value) {
throw new Error("--repo flag requires a path argument");
}
repoRoot = path.resolve(value);
i += 1;
break;
}
case "--worktree-root": {
const value = args[i + 1];
if (!value) {
throw new Error("--worktree-root flag requires a path argument");
}
worktreeRoot = path.resolve(value);
i += 1;
break;
}
case "--concurrency": {
const value = Number(args[i + 1]);
if (!Number.isFinite(value) || value <= 0) {
throw new Error("--concurrency flag requires a positive integer");
}
concurrency = Math.floor(value);
i += 1;
break;
}
case "--remote": {
const value = args[i + 1];
if (!value) {
throw new Error("--remote flag requires a remote name");
}
remote = value;
i += 1;
break;
}
case "--dry-run":
dryRun = true;
break;
case "--help":
case "-h":
printUsage();
process.exit(0);
break;
default:
if (arg.startsWith("-")) {
console.warn(`Unknown option ${arg} (ignored).`);
}
break;
}
}
const repoSlug = await resolveRepoSlug(repoRoot, remote);
const repoOwner = repoSlug ? repoSlug.split("/")[0] : null;
const maxFixAttemptsEnv = process.env.CODEX_PR_WORKTREE_MAX_FIX_ATTEMPTS;
const maxFixAttempts = maxFixAttemptsEnv ? Number(maxFixAttemptsEnv) : DEFAULT_MAX_FIX_ATTEMPTS;
const resolvedMaxFixAttempts = Number.isFinite(maxFixAttempts) && maxFixAttempts > 0
? Math.floor(maxFixAttempts)
: DEFAULT_MAX_FIX_ATTEMPTS;
return { repoRoot, worktreeRoot, concurrency, remote, dryRun, repoSlug, repoOwner, maxFixAttempts: resolvedMaxFixAttempts };
}
function printUsage() {
console.log(`Usage:
pnpm pr [options]
pnpm dlx tsx pr-worktree-codex.ts [options]
Options:
--repo <path> Override repository root (default: current directory)
--worktree-root <path> Directory to place PR worktrees (default: ../codex-pr-worktrees)
--remote <name> Remote to fetch pull requests from (default: origin)
--concurrency <n> Maximum concurrent Codex runs (default: cpu count - 1)
--dry-run Prepare worktrees without invoking Codex
--help Show this message
`);
}
async function ensureBinaryAvailable(binary: string) {
try {
await runCommand(binary, ["--version"]);
} catch (error) {
throw new Error(`Required binary '${binary}' is not available in PATH`);
}
}
async function listOpenPullRequests(config: RunConfig): Promise<PullRequestInfo[]> {
const jsonFields = [
"number",
"title",
"headRefName",
"headRepository",
"headRepositoryOwner",
"url",
];
const args = [
"pr",
"list",
"--state",
"open",
"--limit",
"200",
"--json",
jsonFields.join(","),
];
const { stdout } = await runCommand("gh", args, { cwd: config.repoRoot });
const parsed = JSON.parse(stdout);
return parsed.map((entry: any) => ({
number: entry.number,
title: entry.title,
headRefName: entry.headRefName,
headRepositoryOwnerLogin: entry.headRepositoryOwner?.login ?? null,
headRepositoryName: entry.headRepository?.name ?? null,
url: entry.url,
}));
}
async function getExistingWorktreePaths(repoRoot: string): Promise<Set<string>> {
const { stdout } = await runCommand("git", ["worktree", "list", "--porcelain"], { cwd: repoRoot });
const blocks = stdout.split(/\n(?=worktree )/).map((block) => block.trim()).filter(Boolean);
const paths = new Set<string>();
for (const block of blocks) {
for (const line of block.split("\n")) {
if (line.startsWith("worktree ")) {
const worktreePath = line.substring("worktree ".length).trim();
paths.add(path.resolve(worktreePath));
}
}
}
return paths;
}
function createMutex() {
let chain: Promise<void> = Promise.resolve();
return {
run<T>(fn: () => Promise<T> | T): Promise<T> {
const next = chain.then(() => fn());
chain = next.then(
() => undefined,
() => undefined,
);
return next;
},
};
}
async function runWithConcurrency<T, R>(items: T[], concurrency: number, handler: (item: T, index: number) => Promise<R>): Promise<R[]> {
if (items.length === 0) {
return [];
}
const effectiveConcurrency = Math.max(1, Math.min(concurrency, items.length));
const results: R[] = new Array(items.length);
let index = 0;
async function worker() {
while (true) {
const currentIndex = index;
index += 1;
if (currentIndex >= items.length) {
break;
}
results[currentIndex] = await handler(items[currentIndex], currentIndex);
}
}
const workers = Array.from({ length: effectiveConcurrency }, () => worker());
await Promise.all(workers);
return results;
}
function slugifyRef(ref: string): string {
return ref.replace(/[^a-zA-Z0-9._-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
}
function buildMergePrompt(pr: PullRequestInfo, worktreePath: string): string {
return [
`You are a Codex automation agent working inside ${worktreePath}.`,
"First, ensure the branch is fully up to date with the latest main branch.",
"Steps:",
"1. Run 'git status' to confirm the working tree is clean (resolve or stash anything unexpected).",
"2. Fetch the latest main branch with 'git fetch origin main'.",
"3. Merge main into this branch with 'git merge origin/main'. If conflicts arise, resolve them yourself: open the conflicting files, remove conflict markers, preserve both sides as appropriate, re-run 'git status' to verify all conflicts are cleared, and use 'git add' plus 'git merge --continue' to complete the merge.",
"4. After resolving conflicts, run appropriate builds/tests if necessary to ensure the merged result is healthy.",
"5. Commit the merge (or conflict resolutions) with a clear message if new commits are created.",
"6. Review 'git status' for any staged or unstaged files (even if they pre-existed the merge work); commit everything that should live on the branch so the tree is clean.",
"7. Push the branch back to its remote (git push) so that CI sees the latest work.",
"8. Provide a brief summary of the merge result, calling out any conflicts you resolved and tests you ran.",
].join("\n");
}
function buildFixPrompt(
pr: PullRequestInfo,
worktreePath: string,
examplePaths: string[] = [],
ghChecksResult: GhChecksResult | null = null,
attemptNumber = 1,
): string {
const instructions = [
`You are an automated Codex maintainer responsible for validating pull request #${pr.number}.`,
`The worktree directory is ${worktreePath}.`,
`Tasks:`,
`Remediation attempt #${attemptNumber}: address any failing CI checks thoroughly.`,
"1. Run 'gh pr checks --watch " + pr.number + "' from the repository root to monitor CI failures until they are resolved.",
"2. Investigate failing checks, apply fixes, and commit the necessary changes with clear messages.",
"3. Push your commits back to the PR branch (" + pr.headRefName + ") once checks succeed.",
"4. Provide a final summary including CI status, tests executed, and any remaining manual actions.",
"Use shell commands responsibly and ensure no failing checks remain before finishing.",
"If any 'package-lock.json' files (or other lockfiles from npm/yarn) are present, delete them so that pnpm stays the sole package manager.",
];
if (examplePaths.length > 0) {
instructions.push("Detected new example files:");