-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathsolve.mjs
More file actions
executable file
·1450 lines (1354 loc) · 61 KB
/
solve.mjs
File metadata and controls
executable file
·1450 lines (1354 loc) · 61 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 Sentry instrumentation first (must be before other imports)
import './instrument.mjs';
// Early exit paths - handle these before loading all modules to speed up testing
const earlyArgs = process.argv.slice(2);
if (earlyArgs.includes('--version')) {
const { getVersion } = await import('./version.lib.mjs');
try {
const version = await getVersion();
console.log(version);
} catch {
console.error('Error: Unable to determine version');
process.exit(1);
}
process.exit(0);
}
if (earlyArgs.includes('--help') || earlyArgs.includes('-h')) {
// Load minimal modules needed for help
const { use } = eval(await (await fetch('https://unpkg.com/use-m/use.js')).text());
globalThis.use = use;
const config = await import('./solve.config.lib.mjs');
const { initializeConfig, createYargsConfig } = config;
const { yargs, hideBin } = await initializeConfig(use);
const rawArgs = hideBin(process.argv);
// Filter out help flags to avoid duplicate display
const argsWithoutHelp = rawArgs.filter(arg => arg !== '--help' && arg !== '-h');
createYargsConfig(yargs(argsWithoutHelp)).showHelp();
process.exit(0);
}
if (earlyArgs.length === 0) {
console.error('Usage: solve.mjs <issue-url> [options]');
console.error('\nError: Missing required github issue or pull request URL');
console.error('\nRun "solve.mjs --help" for more information');
process.exit(1);
}
// Now load all modules for normal operation
const { use } = eval(await (await fetch('https://unpkg.com/use-m/use.js')).text());
globalThis.use = use;
const { $ } = await use('command-stream');
const config = await import('./solve.config.lib.mjs');
const { initializeConfig, parseArguments } = config;
// Import Sentry integration
const sentryLib = await import('./sentry.lib.mjs');
const { initializeSentry, addBreadcrumb, reportError } = sentryLib;
const { yargs, hideBin } = await initializeConfig(use);
const path = (await use('path')).default;
const fs = (await use('fs')).promises;
const crypto = (await use('crypto')).default;
const memoryCheck = await import('./memory-check.mjs');
const lib = await import('./lib.mjs');
const { log, setLogFile, getLogFile, getAbsoluteLogPath, cleanErrorMessage, formatAligned, getVersionInfo } = lib;
const githubLib = await import('./github.lib.mjs');
const { sanitizeLogContent, attachLogToGitHub } = githubLib;
const validation = await import('./solve.validation.lib.mjs');
const { validateGitHubUrl, showAttachLogsWarning, initializeLogFile, validateUrlRequirement, validateContinueOnlyOnFeedback, performSystemChecks } = validation;
const autoContinue = await import('./solve.auto-continue.lib.mjs');
const { processAutoContinueForIssue } = autoContinue;
const repository = await import('./solve.repository.lib.mjs');
const { setupTempDirectory, cleanupTempDirectory } = repository;
const results = await import('./solve.results.lib.mjs');
const { cleanupClaudeFile, showSessionSummary, verifyResults, buildClaudeResumeCommand } = results;
const claudeLib = await import('./claude.lib.mjs');
const { executeClaude } = claudeLib;
const githubLinking = await import('./github-linking.lib.mjs');
const { extractLinkedIssueNumber } = githubLinking;
const usageLimitLib = await import('./usage-limit.lib.mjs');
const { formatResetTimeWithRelative } = usageLimitLib;
const errorHandlers = await import('./solve.error-handlers.lib.mjs');
const { createUncaughtExceptionHandler, createUnhandledRejectionHandler, handleMainExecutionError } = errorHandlers;
const watchLib = await import('./solve.watch.lib.mjs');
const { startWatchMode } = watchLib;
const autoMergeLib = await import('./solve.auto-merge.lib.mjs');
const { startAutoRestartUntilMergable } = autoMergeLib;
const exitHandler = await import('./exit-handler.lib.mjs');
const { initializeExitHandler, installGlobalExitHandlers, safeExit } = exitHandler;
const getResourceSnapshot = memoryCheck.getResourceSnapshot;
// Import new modular components
const autoPrLib = await import('./solve.auto-pr.lib.mjs');
const { handleAutoPrCreation } = autoPrLib;
const repoSetupLib = await import('./solve.repo-setup.lib.mjs');
const { setupRepositoryAndClone, verifyDefaultBranchAndStatus } = repoSetupLib;
const branchLib = await import('./solve.branch.lib.mjs');
const { createOrCheckoutBranch } = branchLib;
const sessionLib = await import('./solve.session.lib.mjs');
const { startWorkSession, endWorkSession, SESSION_TYPES } = sessionLib;
const preparationLib = await import('./solve.preparation.lib.mjs');
const { prepareFeedbackAndTimestamps, checkUncommittedChanges, checkForkActions } = preparationLib;
// Import model validation library
const modelValidation = await import('./model-validation.lib.mjs');
const { validateAndExitOnInvalidModel } = modelValidation;
// Initialize log file EARLY to capture all output including version and command
// Use default directory (cwd) initially, will be set from argv.logDir after parsing
const logFile = await initializeLogFile(null);
// Log version and raw command IMMEDIATELY after log file initialization
// This ensures they appear in both console and log file, even if argument parsing fails
const versionInfo = await getVersionInfo();
await log('');
await log(`🚀 solve v${versionInfo}`);
const rawCommand = process.argv.join(' ');
await log('🔧 Raw command executed:');
await log(` ${rawCommand}`);
await log('');
let argv;
try {
argv = await parseArguments(yargs, hideBin);
} catch (error) {
// Handle argument parsing errors with helpful messages
await log(`❌ ${error.message}`, { level: 'error' });
await log('', { level: 'error' });
await log('Use /help to see available options', { level: 'error' });
await safeExit(1, 'Invalid command-line arguments');
}
global.verboseMode = argv.verbose;
// If user specified a custom log directory, we would need to move the log file
// However, this adds complexity, so we accept that early logs go to cwd
// The trade-off is: early logs in cwd vs missing version/command in error cases
// Conditionally import tool-specific functions after argv is parsed
let checkForUncommittedChanges;
if (argv.tool === 'opencode') {
const opencodeLib = await import('./opencode.lib.mjs');
checkForUncommittedChanges = opencodeLib.checkForUncommittedChanges;
} else if (argv.tool === 'codex') {
const codexLib = await import('./codex.lib.mjs');
checkForUncommittedChanges = codexLib.checkForUncommittedChanges;
} else if (argv.tool === 'agent') {
const agentLib = await import('./agent.lib.mjs');
checkForUncommittedChanges = agentLib.checkForUncommittedChanges;
} else {
checkForUncommittedChanges = claudeLib.checkForUncommittedChanges;
}
const shouldAttachLogs = argv.attachLogs || argv['attach-logs'];
await showAttachLogsWarning(shouldAttachLogs);
const absoluteLogPath = path.resolve(logFile);
// Initialize Sentry integration (unless disabled)
if (argv.sentry) {
await initializeSentry({
noSentry: !argv.sentry,
debug: argv.verbose,
version: process.env.npm_package_version || '0.12.0',
});
// Add breadcrumb for solve operation
addBreadcrumb({
category: 'solve',
message: 'Started solving issue',
level: 'info',
data: {
model: argv.model,
issueUrl: argv['issue-url'] || argv._?.[0] || 'not-set-yet',
},
});
}
// Create a cleanup wrapper that will be populated with context later
let cleanupContext = { tempDir: null, argv: null, limitReached: false };
const cleanupWrapper = async () => {
if (cleanupContext.tempDir && cleanupContext.argv) {
await cleanupTempDirectory(cleanupContext.tempDir, cleanupContext.argv, cleanupContext.limitReached);
}
};
// Initialize the exit handler with getAbsoluteLogPath function and cleanup wrapper
initializeExitHandler(getAbsoluteLogPath, log, cleanupWrapper);
installGlobalExitHandlers();
// Note: Version and raw command are logged BEFORE parseArguments() (see above)
// This ensures they appear even if strict validation fails
// Strict options validation is now handled by yargs .strict() mode in solve.config.lib.mjs
// This prevents unrecognized options from being silently ignored (issue #453, #482)
// Now handle argument validation that was moved from early checks
let issueUrl = argv['issue-url'] || argv._[0];
if (!issueUrl) {
await log('Usage: solve.mjs <issue-url> [options]', { level: 'error' });
await log('Error: Missing required github issue or pull request URL', { level: 'error' });
await log('Run "solve.mjs --help" for more information', { level: 'error' });
await safeExit(1, 'Missing required GitHub URL');
}
// Validate GitHub URL using validation module (more thorough check)
const urlValidation = validateGitHubUrl(issueUrl);
if (!urlValidation.isValid) {
await safeExit(1, 'Invalid GitHub URL');
}
const { isIssueUrl, isPrUrl, normalizedUrl, owner, repo, number: urlNumber } = urlValidation;
issueUrl = normalizedUrl || issueUrl;
// Store owner and repo globally for error handlers early
global.owner = owner;
global.repo = repo;
// Setup unhandled error handlers to ensure log path is always shown
const errorHandlerOptions = {
log,
cleanErrorMessage,
absoluteLogPath,
shouldAttachLogs,
argv,
global,
owner: null, // Will be set later when parsed
repo: null, // Will be set later when parsed
getLogFile,
attachLogToGitHub,
sanitizeLogContent,
$,
};
process.on('uncaughtException', createUncaughtExceptionHandler(errorHandlerOptions));
process.on('unhandledRejection', createUnhandledRejectionHandler(errorHandlerOptions));
// Validate GitHub URL requirement and options using validation module
if (!(await validateUrlRequirement(issueUrl))) {
await safeExit(1, 'URL requirement validation failed');
}
if (!(await validateContinueOnlyOnFeedback(argv, isPrUrl, isIssueUrl))) {
await safeExit(1, 'Feedback validation failed');
}
// Validate model name EARLY - this always runs regardless of --skip-tool-connection-check
// Model validation is a simple string check and should always be performed
const tool = argv.tool || 'claude';
await validateAndExitOnInvalidModel(argv.model, tool, safeExit);
// Perform all system checks using validation module
// Skip tool CONNECTION validation in dry-run mode or when --skip-tool-connection-check or --no-tool-connection-check is enabled
// Note: This does NOT skip model validation which is performed above
const skipToolConnectionCheck = argv.dryRun || argv.skipToolConnectionCheck || argv.toolConnectionCheck === false;
if (!(await performSystemChecks(argv.minDiskSpace || 2048, skipToolConnectionCheck, argv.model, argv))) {
await safeExit(1, 'System checks failed');
}
// URL validation debug logging
if (argv.verbose) {
await log('📋 URL validation:', { verbose: true });
await log(` Input URL: ${issueUrl}`, { verbose: true });
await log(` Is Issue URL: ${!!isIssueUrl}`, { verbose: true });
await log(` Is PR URL: ${!!isPrUrl}`, { verbose: true });
}
const claudePath = argv.executeToolWithBun ? 'bunx claude' : process.env.CLAUDE_PATH || 'claude';
// Note: owner, repo, and urlNumber are already extracted from validateGitHubUrl() above
// The parseUrlComponents() call was removed as it had a bug with hash fragments (#issuecomment-xyz)
// and the validation result already provides these values correctly parsed
// Handle --auto-fork option: automatically fork public repositories without write access
if (argv.autoFork && !argv.fork) {
const { detectRepositoryVisibility } = githubLib;
// Check if we have write access first
await log('🔍 Checking repository access for auto-fork...');
const permResult = await $`gh api repos/${owner}/${repo} --jq .permissions`;
if (permResult.code === 0) {
const permissions = JSON.parse(permResult.stdout.toString().trim());
const hasWriteAccess = permissions.push === true || permissions.admin === true || permissions.maintain === true;
if (!hasWriteAccess) {
// No write access - check if repository is public before enabling fork mode
const { isPublic } = await detectRepositoryVisibility(owner, repo);
if (!isPublic) {
// Private repository without write access - cannot fork
await log('');
await log("❌ --auto-fork failed: Repository is private and you don't have write access", { level: 'error' });
await log('');
await log(' 🔍 What happened:', { level: 'error' });
await log(` Repository ${owner}/${repo} is private`, { level: 'error' });
await log(" You don't have write access to this repository", { level: 'error' });
await log(' --auto-fork cannot create a fork of a private repository you cannot access', {
level: 'error',
});
await log('');
await log(' 💡 Solution:', { level: 'error' });
await log(' • Request collaborator access from the repository owner', { level: 'error' });
await log(` https://github.com/${owner}/${repo}/settings/access`, { level: 'error' });
await log('');
await safeExit(1, 'Auto-fork failed - private repository without access');
}
// Public repository without write access - automatically enable fork mode
await log('✅ Auto-fork: No write access detected, enabling fork mode');
argv.fork = true;
} else {
// Has write access - work directly on the repo (works for both public and private repos)
const { isPublic } = await detectRepositoryVisibility(owner, repo);
await log(`✅ Auto-fork: Write access detected to ${isPublic ? 'public' : 'private'} repository, working directly on repository`);
}
} else {
// Could not check permissions - assume no access and try to fork if public
const { isPublic } = await detectRepositoryVisibility(owner, repo);
if (!isPublic) {
// Cannot determine permissions for private repo - fail safely
await log('');
await log('❌ --auto-fork failed: Could not verify permissions for private repository', { level: 'error' });
await log('');
await log(' 🔍 What happened:', { level: 'error' });
await log(` Repository ${owner}/${repo} is private`, { level: 'error' });
await log(' Could not check your permissions to this repository', { level: 'error' });
await log('');
await log(' 💡 Solutions:', { level: 'error' });
await log(' • Check your GitHub CLI authentication: gh auth status', { level: 'error' });
await log(" • Request collaborator access if you don't have it yet", { level: 'error' });
await log(` https://github.com/${owner}/${repo}/settings/access`, { level: 'error' });
await log('');
await safeExit(1, 'Auto-fork failed - cannot verify private repository permissions');
}
// Public repository but couldn't check permissions - assume no access and fork
await log('⚠️ Auto-fork: Could not check permissions, enabling fork mode for public repository');
argv.fork = true;
}
}
// Early check: Verify repository write permissions BEFORE doing any work
// This prevents wasting AI tokens when user doesn't have access and --fork is not used
const { checkRepositoryWritePermission } = githubLib;
const hasWriteAccess = await checkRepositoryWritePermission(owner, repo, {
useFork: argv.fork,
issueUrl: issueUrl,
});
if (!hasWriteAccess) {
await log('');
await log('❌ Cannot proceed without repository write access or --fork option', { level: 'error' });
await safeExit(1, 'Permission check failed');
}
// Detect repository visibility and set auto-cleanup default if not explicitly set
if (argv.autoCleanup === undefined) {
const { detectRepositoryVisibility } = githubLib;
const { isPublic } = await detectRepositoryVisibility(owner, repo);
// For public repos: keep temp directories (default false)
// For private repos: clean up temp directories (default true)
argv.autoCleanup = !isPublic;
if (argv.verbose) {
await log(` Auto-cleanup default: ${argv.autoCleanup} (repository is ${isPublic ? 'public' : 'private'})`, {
verbose: true,
});
}
}
// Determine mode and get issue details
let issueNumber;
let prNumber;
let prBranch;
let mergeStateStatus;
let prState;
let forkOwner = null;
let isContinueMode = false;
// Auto-continue logic: check for existing PRs if --auto-continue is enabled
const autoContinueResult = await processAutoContinueForIssue(argv, isIssueUrl, urlNumber, owner, repo);
if (autoContinueResult.isContinueMode) {
isContinueMode = true;
prNumber = autoContinueResult.prNumber;
prBranch = autoContinueResult.prBranch;
issueNumber = autoContinueResult.issueNumber;
// Only check PR details if we have a PR number
if (prNumber) {
// Store PR info globally for error handlers
global.createdPR = { number: prNumber };
// Check if PR is from a fork and get fork owner, merge status, and PR state
if (argv.verbose) {
await log(' Checking if PR is from a fork...', { verbose: true });
}
try {
const prCheckResult = await $`gh pr view ${prNumber} --repo ${owner}/${repo} --json headRepositoryOwner,headRepository,mergeStateStatus,state`;
if (prCheckResult.code === 0) {
const prCheckData = JSON.parse(prCheckResult.stdout.toString());
// Extract merge status and PR state
mergeStateStatus = prCheckData.mergeStateStatus;
prState = prCheckData.state;
if (argv.verbose) {
await log(` PR state: ${prState || 'UNKNOWN'}`, { verbose: true });
await log(` Merge status: ${mergeStateStatus || 'UNKNOWN'}`, { verbose: true });
}
if (prCheckData.headRepositoryOwner && prCheckData.headRepositoryOwner.login !== owner) {
forkOwner = prCheckData.headRepositoryOwner.login;
// Get actual fork repository name (may be prefixed)
const forkRepoName = prCheckData.headRepository && prCheckData.headRepository.name ? prCheckData.headRepository.name : repo;
await log(`🍴 Detected fork PR from ${forkOwner}/${forkRepoName}`);
if (argv.verbose) {
await log(` Fork owner: ${forkOwner}`, { verbose: true });
await log(' Will clone fork repository for continue mode', { verbose: true });
}
// Check if maintainer can push to the fork when --allow-to-push-to-contributors-pull-requests-as-maintainer is enabled
if (argv.allowToPushToContributorsPullRequestsAsMaintainer && argv.autoFork) {
const { checkMaintainerCanModifyPR, requestMaintainerAccess } = githubLib;
const { canModify } = await checkMaintainerCanModifyPR(owner, repo, prNumber);
if (canModify) {
await log('✅ Maintainer can push to fork: Enabled by contributor');
await log(" Will push changes directly to contributor's fork instead of creating own fork");
// Don't disable fork mode, but we'll use the contributor's fork
} else {
await log('⚠️ Maintainer cannot push to fork: "Allow edits by maintainers" is not enabled', {
level: 'warning',
});
await log(' Posting comment to request access...', { level: 'warning' });
await requestMaintainerAccess(owner, repo, prNumber);
await log(' Comment posted. Proceeding with own fork instead.', { level: 'warning' });
}
}
}
}
} catch (forkCheckError) {
if (argv.verbose) {
await log(` Warning: Could not check fork status: ${forkCheckError.message}`, { verbose: true });
}
}
} else {
// We have a branch but no PR - we'll use the existing branch and create a PR later
await log(`🔄 Using existing branch: ${prBranch} (no PR yet - will create one)`);
if (argv.verbose) {
await log(' Branch will be checked out and PR will be created during auto-PR creation phase', {
verbose: true,
});
}
}
} else if (isIssueUrl) {
issueNumber = autoContinueResult.issueNumber || urlNumber;
}
if (isPrUrl) {
isContinueMode = true;
prNumber = urlNumber;
// Store PR info globally for error handlers
global.createdPR = { number: prNumber, url: issueUrl };
await log(`🔄 Continue mode: Working with PR #${prNumber}`);
if (argv.verbose) {
await log(' Continue mode activated: PR URL provided directly', { verbose: true });
await log(` PR Number set to: ${prNumber}`, { verbose: true });
await log(' Will fetch PR details and linked issue', { verbose: true });
}
// Get PR details to find the linked issue and branch
try {
const prResult = await githubLib.ghPrView({
prNumber,
owner,
repo,
jsonFields: 'headRefName,body,number,mergeStateStatus,state,headRepositoryOwner,headRepository',
});
if (prResult.code !== 0 || !prResult.data) {
await log('Error: Failed to get PR details', { level: 'error' });
if (prResult.output.includes('Could not resolve to a PullRequest')) {
await githubLib.handlePRNotFoundError({ prNumber, owner, repo, argv, shouldAttachLogs });
} else {
await log(`Error: ${prResult.stderr || 'Unknown error'}`, { level: 'error' });
}
await safeExit(1, 'Failed to get PR details');
}
const prData = prResult.data;
prBranch = prData.headRefName;
mergeStateStatus = prData.mergeStateStatus;
prState = prData.state;
// Check if this is a fork PR
if (prData.headRepositoryOwner && prData.headRepositoryOwner.login !== owner) {
forkOwner = prData.headRepositoryOwner.login;
// Get actual fork repository name (may be prefixed)
const forkRepoName = prData.headRepository && prData.headRepository.name ? prData.headRepository.name : repo;
await log(`🍴 Detected fork PR from ${forkOwner}/${forkRepoName}`);
if (argv.verbose) {
await log(` Fork owner: ${forkOwner}`, { verbose: true });
await log(' Will clone fork repository for continue mode', { verbose: true });
}
// Check if maintainer can push to the fork when --allow-to-push-to-contributors-pull-requests-as-maintainer is enabled
if (argv.allowToPushToContributorsPullRequestsAsMaintainer && argv.autoFork) {
const { checkMaintainerCanModifyPR, requestMaintainerAccess } = githubLib;
const { canModify } = await checkMaintainerCanModifyPR(owner, repo, prNumber);
if (canModify) {
await log('✅ Maintainer can push to fork: Enabled by contributor');
await log(" Will push changes directly to contributor's fork instead of creating own fork");
// Don't disable fork mode, but we'll use the contributor's fork
} else {
await log('⚠️ Maintainer cannot push to fork: "Allow edits by maintainers" is not enabled', {
level: 'warning',
});
await log(' Posting comment to request access...', { level: 'warning' });
await requestMaintainerAccess(owner, repo, prNumber);
await log(' Comment posted. Proceeding with own fork instead.', { level: 'warning' });
}
}
}
await log(`📝 PR branch: ${prBranch}`);
// Extract issue number from PR body using GitHub linking detection library
// This ensures we only detect actual GitHub-recognized linking keywords
const prBody = prData.body || '';
const extractedIssueNumber = extractLinkedIssueNumber(prBody);
if (extractedIssueNumber) {
issueNumber = extractedIssueNumber;
await log(`🔗 Found linked issue #${issueNumber}`);
} else {
// If no linked issue found, we can still continue but warn
await log('⚠️ Warning: No linked issue found in PR body', { level: 'warning' });
await log(' The PR should contain "Fixes #123" or similar to link an issue', { level: 'warning' });
// Set issueNumber to PR number as fallback
issueNumber = prNumber;
}
} catch (error) {
reportError(error, {
context: 'pr_processing',
prNumber,
operation: 'process_pull_request',
});
await log(`Error: Failed to process PR: ${cleanErrorMessage(error)}`, { level: 'error' });
await safeExit(1, 'Failed to process PR');
}
} else {
// Traditional issue mode
issueNumber = urlNumber;
await log(`📝 Issue mode: Working with issue #${issueNumber}`);
}
// Create or find temporary directory for cloning the repository
// Pass workspace info for --enable-workspaces mode (works with all tools)
const workspaceInfo = argv.enableWorkspaces ? { owner, repo, issueNumber } : null;
const { tempDir, workspaceTmpDir, needsClone } = await setupTempDirectory(argv, workspaceInfo);
// Populate cleanup context for signal handlers
cleanupContext.tempDir = tempDir;
cleanupContext.argv = argv;
// Initialize limitReached variable outside try block for finally clause
let limitReached = false;
try {
// Set up repository and clone using the new module
// If --working-directory points to existing repo, needsClone is false and we skip cloning
const { forkedRepo } = await setupRepositoryAndClone({
argv,
owner,
repo,
forkOwner,
tempDir,
isContinueMode,
issueUrl,
log,
formatAligned,
$,
needsClone,
});
// Verify default branch and status using the new module
// Pass argv, owner, repo, issueUrl for empty repository auto-initialization (--auto-init-repository)
const defaultBranch = await verifyDefaultBranchAndStatus({
tempDir,
log,
formatAligned,
$,
argv,
owner,
repo,
issueUrl,
});
// Create or checkout branch using the new module
const branchName = await createOrCheckoutBranch({
isContinueMode,
prBranch,
issueNumber,
tempDir,
defaultBranch,
argv,
log,
formatAligned,
$,
crypto,
owner,
repo,
prNumber,
});
// Auto-merge default branch to pull request branch if enabled
let autoMergeFeedbackLines = [];
if (isContinueMode && argv['auto-merge-default-branch-to-pull-request-branch']) {
await log(`\n${formatAligned('🔀', 'Auto-merging:', `Merging ${defaultBranch} into ${branchName}`)}`);
try {
const mergeResult = await $({ cwd: tempDir })`git merge ${defaultBranch} --no-edit`;
if (mergeResult.code === 0) {
await log(`${formatAligned('✅', 'Merge successful:', 'Pushing merged branch...')}`);
const pushResult = await $({ cwd: tempDir })`git push origin ${branchName}`;
if (pushResult.code === 0) {
await log(`${formatAligned('✅', 'Push successful:', 'Branch updated with latest changes')}`);
} else {
await log(`${formatAligned('⚠️', 'Push failed:', 'Merge completed but push failed')}`, { level: 'warning' });
await log(` Error: ${pushResult.stderr?.toString() || 'Unknown error'}`, { level: 'warning' });
}
} else {
// Merge failed - likely due to conflicts
await log(`${formatAligned('⚠️', 'Merge failed:', 'Conflicts detected')}`, { level: 'warning' });
autoMergeFeedbackLines.push('');
autoMergeFeedbackLines.push('⚠️ AUTOMATIC MERGE FAILED:');
autoMergeFeedbackLines.push(`git merge ${defaultBranch} was executed but resulted in conflicts that should be resolved first.`);
autoMergeFeedbackLines.push('Please resolve the merge conflicts and commit the changes.');
autoMergeFeedbackLines.push('');
}
} catch (mergeError) {
await log(`${formatAligned('❌', 'Merge error:', mergeError.message)}`, { level: 'error' });
autoMergeFeedbackLines.push('');
autoMergeFeedbackLines.push('⚠️ AUTOMATIC MERGE ERROR:');
autoMergeFeedbackLines.push(`git merge ${defaultBranch} failed with error: ${mergeError.message}`);
autoMergeFeedbackLines.push('Please check the repository state and resolve any issues.');
autoMergeFeedbackLines.push('');
}
}
// Initialize PR variables early
let prUrl = null;
// In continue mode, we already have the PR details
if (isContinueMode) {
prUrl = issueUrl; // The input URL is the PR URL
// prNumber is already set from earlier when we parsed the PR
}
// Don't build the prompt yet - we'll build it after we have all the information
// This includes PR URL (if created) and comment info (if in continue mode)
// Handle auto PR creation using the new module
const autoPrResult = await handleAutoPrCreation({
argv,
tempDir,
branchName,
issueNumber,
owner,
repo,
defaultBranch,
forkedRepo,
isContinueMode,
prNumber,
log,
formatAligned,
$,
reportError,
path,
fs,
});
let claudeCommitHash = null;
if (autoPrResult) {
prUrl = autoPrResult.prUrl;
if (autoPrResult.prNumber) {
prNumber = autoPrResult.prNumber;
}
if (autoPrResult.claudeCommitHash) {
claudeCommitHash = autoPrResult.claudeCommitHash;
}
}
// CRITICAL: Validate that we have a PR number when required
// This prevents continuing without a PR when one was supposed to be created
if ((isContinueMode || argv.autoPullRequestCreation) && !prNumber) {
await log('');
await log(formatAligned('❌', 'FATAL ERROR:', 'No pull request available'), { level: 'error' });
await log('');
await log(' 🔍 What happened:');
if (isContinueMode) {
await log(' Continue mode is active but no PR number is available.');
await log(' This usually means PR creation failed or was skipped incorrectly.');
} else {
await log(' Auto-PR creation is enabled but no PR was created.');
await log(' PR creation may have failed without throwing an error.');
}
await log('');
await log(' 💡 Why this is critical:');
await log(' The solve command requires a PR for:');
await log(' • Tracking work progress');
await log(' • Receiving and processing feedback');
await log(' • Managing code changes');
await log(' • Auto-merging when complete');
await log('');
await log(' 🔧 How to fix:');
await log('');
await log(' Option 1: Create PR manually and use --continue');
await log(` cd ${tempDir}`);
await log(` gh pr create --draft --title "Fix issue #${issueNumber}" --body "Fixes #${issueNumber}"`);
await log(' # Then use the PR URL with solve.mjs');
await log('');
await log(' Option 2: Start fresh without continue mode');
await log(` ./solve.mjs "${issueUrl}" --auto-pull-request-creation`);
await log('');
await log(' Option 3: Disable auto-PR creation (Claude will create it)');
await log(` ./solve.mjs "${issueUrl}" --no-auto-pull-request-creation`);
await log('');
await safeExit(1, 'No PR available');
}
if (isContinueMode) {
await log(`\n${formatAligned('🔄', 'Continue mode:', 'ACTIVE')}`);
await log(formatAligned('', 'Using existing PR:', `#${prNumber}`, 2));
await log(formatAligned('', 'PR URL:', prUrl, 2));
} else if (!argv.autoPullRequestCreation) {
await log(`\n${formatAligned('⏭️', 'Auto PR creation:', 'DISABLED')}`);
await log(formatAligned('', 'Workflow:', 'AI will create the PR', 2));
}
// Don't build the prompt yet - we'll build it after we have all the information
// This includes PR URL (if created) and comment info (if in continue mode)
// Start work session using the new module
// Determine session type based on command line flags
// See: https://github.com/link-assistant/hive-mind/issues/1152
let sessionType = SESSION_TYPES.NEW;
if (argv.sessionType) {
// Session type was explicitly set (e.g., by auto-resume/auto-restart spawning a new process)
sessionType = argv.sessionType;
} else if (isContinueMode) {
// Continue mode is a manual resume via PR URL
sessionType = SESSION_TYPES.RESUME;
}
await startWorkSession({
isContinueMode,
prNumber,
argv,
log,
formatAligned,
$,
sessionType,
});
// Prepare feedback and timestamps using the new module
const { feedbackLines: preparedFeedbackLines, referenceTime } = await prepareFeedbackAndTimestamps({
prNumber,
branchName,
owner,
repo,
issueNumber,
isContinueMode,
mergeStateStatus,
prState,
argv,
log,
formatAligned,
cleanErrorMessage,
$,
});
// Initialize feedback lines
let feedbackLines = null;
// Add auto-merge feedback lines if any
if (autoMergeFeedbackLines && autoMergeFeedbackLines.length > 0) {
if (!feedbackLines) {
feedbackLines = [];
}
feedbackLines.push(...autoMergeFeedbackLines);
}
// Merge feedback lines
if (preparedFeedbackLines && preparedFeedbackLines.length > 0) {
if (!feedbackLines) {
feedbackLines = [];
}
feedbackLines.push(...preparedFeedbackLines);
}
// Check for uncommitted changes and merge with feedback
const uncommittedFeedbackLines = await checkUncommittedChanges({
tempDir,
argv,
log,
$,
});
if (uncommittedFeedbackLines && uncommittedFeedbackLines.length > 0) {
if (!feedbackLines) {
feedbackLines = [];
}
feedbackLines.push(...uncommittedFeedbackLines);
}
// Check for fork actions
const forkActionsUrl = await checkForkActions({
argv,
forkedRepo,
branchName,
log,
formatAligned,
$,
});
// Execute tool command with all prompts and settings
let toolResult;
if (argv.tool === 'opencode') {
const opencodeLib = await import('./opencode.lib.mjs');
const { executeOpenCode } = opencodeLib;
const opencodePath = process.env.OPENCODE_PATH || 'opencode';
toolResult = await executeOpenCode({
issueUrl,
issueNumber,
prNumber,
prUrl,
branchName,
tempDir,
workspaceTmpDir,
isContinueMode,
mergeStateStatus,
forkedRepo,
feedbackLines,
forkActionsUrl,
owner,
repo,
argv,
log,
setLogFile,
getLogFile,
formatAligned,
getResourceSnapshot,
opencodePath,
$,
});
} else if (argv.tool === 'codex') {
const codexLib = await import('./codex.lib.mjs');
const { executeCodex } = codexLib;
const codexPath = process.env.CODEX_PATH || 'codex';
toolResult = await executeCodex({
issueUrl,
issueNumber,
prNumber,
prUrl,
branchName,
tempDir,
workspaceTmpDir,
isContinueMode,
mergeStateStatus,
forkedRepo,
feedbackLines,
forkActionsUrl,
owner,
repo,
argv,
log,
setLogFile,
getLogFile,
formatAligned,
getResourceSnapshot,
codexPath,
$,
});
} else if (argv.tool === 'agent') {
const agentLib = await import('./agent.lib.mjs');
const { executeAgent } = agentLib;
const agentPath = process.env.AGENT_PATH || 'agent';
toolResult = await executeAgent({
issueUrl,
issueNumber,
prNumber,
prUrl,
branchName,
tempDir,
workspaceTmpDir,
isContinueMode,
mergeStateStatus,
forkedRepo,
feedbackLines,
forkActionsUrl,
owner,
repo,
argv,
log,
setLogFile,
getLogFile,
formatAligned,
getResourceSnapshot,
agentPath,
$,
});
} else {
// Default to Claude
// Check for Playwright MCP availability if using Claude tool
if (argv.tool === 'claude' || !argv.tool) {
// If flag is true (default), check if Playwright MCP is actually available
if (argv.promptPlaywrightMcp) {
const { checkPlaywrightMcpAvailability } = claudeLib;
const playwrightMcpAvailable = await checkPlaywrightMcpAvailability();
if (playwrightMcpAvailable) {
await log('🎭 Playwright MCP detected - enabling browser automation hints', { verbose: true });
} else {
await log('ℹ️ Playwright MCP not detected - browser automation hints will be disabled', { verbose: true });
argv.promptPlaywrightMcp = false;
}
} else {
await log('ℹ️ Playwright MCP explicitly disabled via --no-prompt-playwright-mcp', { verbose: true });
}
}
const claudeResult = await executeClaude({
issueUrl,
issueNumber,
prNumber,
prUrl,
branchName,
tempDir,
workspaceTmpDir,
isContinueMode,
mergeStateStatus,
forkedRepo,
feedbackLines,
forkActionsUrl,
owner,
repo,
argv,
log,
setLogFile,
getLogFile,
formatAligned,
getResourceSnapshot,
claudePath,
$,
});
toolResult = claudeResult;
}
const { success } = toolResult;
let sessionId = toolResult.sessionId;
let anthropicTotalCostUSD = toolResult.anthropicTotalCostUSD;
let publicPricingEstimate = toolResult.publicPricingEstimate; // Used by agent tool
let pricingInfo = toolResult.pricingInfo; // Used by agent tool for detailed pricing
let errorDuringExecution = toolResult.errorDuringExecution || false; // Issue #1088: Track error_during_execution
limitReached = toolResult.limitReached;
cleanupContext.limitReached = limitReached;
// Capture limit reset time and timezone globally for downstream handlers (auto-continue, cleanup decisions)
if (toolResult && toolResult.limitResetTime) {
global.limitResetTime = toolResult.limitResetTime;
}
if (toolResult && toolResult.limitTimezone) {
global.limitTimezone = toolResult.limitTimezone;
}
// Handle limit reached scenario
if (limitReached) {
// Check for both auto-resume (maintains context) and auto-restart (fresh start)
// See: https://github.com/link-assistant/hive-mind/issues/1152
const shouldAutoResumeOnReset = argv.autoResumeOnLimitReset;
const shouldAutoRestartOnReset = argv.autoRestartOnLimitReset;
const shouldAutoContinueOnReset = shouldAutoResumeOnReset || shouldAutoRestartOnReset;
// If limit was reached but neither auto-resume nor auto-restart is enabled, fail immediately
if (!shouldAutoContinueOnReset) {
await log('\n❌ USAGE LIMIT REACHED!');
await log(' The AI tool has reached its usage limit.');
// Always show manual resume command in console so users can resume after limit resets
if (sessionId) {
const resetTime = global.limitResetTime;
const timezone = global.limitTimezone || null;
await log('');
await log(`📁 Working directory: ${tempDir}`);
await log(`📌 Session ID: ${sessionId}`);
if (resetTime) {
// Format reset time with relative time and UTC for better user understanding
// See: https://github.com/link-assistant/hive-mind/issues/1152
const formattedResetTime = formatResetTimeWithRelative(resetTime, timezone);
await log(`⏰ Limit resets at: ${formattedResetTime}`);
}
await log('');
// Show claude resume command only for --tool claude (or default)
// Uses the (cd ... && claude --resume ...) pattern for a fully copyable, executable command
const toolForResume = argv.tool || 'claude';
if (toolForResume === 'claude') {
const claudeResumeCmd = buildClaudeResumeCommand({ tempDir, sessionId, model: argv.model });
await log('💡 To continue this session in Claude Code interactive mode:');
await log('');
await log(` ${claudeResumeCmd}`);
await log('');
}
}
// If --attach-logs is enabled and we have a PR, attach logs with usage limit details
if (shouldAttachLogs && sessionId && prNumber) {
await log('\n📄 Attaching logs to Pull Request...');
try {
// Build Claude CLI resume command
const tool = argv.tool || 'claude';
const resumeCommand = tool === 'claude' ? buildClaudeResumeCommand({ tempDir, sessionId, model: argv.model }) : null;
const logUploadSuccess = await attachLogToGitHub({
logFile: getLogFile(),
targetType: 'pr',
targetNumber: prNumber,
owner,
repo,
$,
log,
sanitizeLogContent,
// Mark this as a usage limit case for proper formatting
isUsageLimit: true,
limitResetTime: global.limitResetTime,
toolName: (argv.tool || 'AI tool').toString().toLowerCase() === 'claude' ? 'Claude' : (argv.tool || 'AI tool').toString().toLowerCase() === 'codex' ? 'Codex' : (argv.tool || 'AI tool').toString().toLowerCase() === 'opencode' ? 'OpenCode' : (argv.tool || 'AI tool').toString().toLowerCase() === 'agent' ? 'Agent' : 'AI tool',
resumeCommand,
sessionId,
});
if (logUploadSuccess) {
await log(' ✅ Logs uploaded successfully');
} else {
await log(' ⚠️ Failed to upload logs', { verbose: true });
}
} catch (uploadError) {
await log(` ⚠️ Error uploading logs: ${uploadError.message}`, { verbose: true });
}
} else if (prNumber) {