forked from keithah/multi-provider-code-review
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodex.ts
More file actions
1856 lines (1645 loc) · 60 KB
/
Copy pathcodex.ts
File metadata and controls
1856 lines (1645 loc) · 60 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
import { Provider, ProviderExecutionPolicy } from './base';
import { Finding, ReviewResult } from '../types';
import { logger } from '../utils/logger';
import { spawn, spawnSync } from 'child_process';
import * as fs from 'fs/promises';
import * as fsSync from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as crypto from 'crypto';
import { estimateTokensSimple } from '../utils/token-estimation';
import { buildCliSafeEnv } from './cli-env';
import { prepareCodexCliBeforeAuthRead } from '../codex-oauth/codex-cli';
import {
buildReviewFindingsSchema,
type ParsedReviewOutput,
parseReviewOutputStrict,
parseReviewFindingsStrict,
} from './review-output';
export interface CodexProviderOptions {
agenticContext?: boolean;
eventAudit?: boolean;
modelProvider?: 'openai' | 'openrouter';
providerNamePrefix?: 'codex' | 'codex-openrouter' | 'openrouter';
providerNameModel?: string;
}
type CodexRunOptions = {
healthCheck: boolean;
outputSchema?: unknown;
eventAudit?: boolean;
jsonEvents?: boolean;
cwd?: string;
includeWorkspaceEnv?: boolean;
disableTools?: boolean;
skipGitRepoCheck?: boolean;
acceptReviewOutputOnNonZero?: boolean;
};
type CodexRunResult = {
stdout: string;
stderr: string;
lastMessage: string;
audit?: CodexAgenticAudit;
};
type CodexAgenticAuditMode = 'off' | 'rerun' | 'strict';
const MAX_OPTIONAL_AGENTIC_RETRY_PROMPT_TOKENS = 24_000;
type CodexAgenticAudit = {
commandExecutions: number;
readOnlyExplorationCommands: number;
commands: string[];
};
class CodexCliExitError extends Error {
constructor(
readonly code: number | null,
readonly stdout: string,
readonly stderr: string,
message: string
) {
super(message);
this.name = 'CodexCliExitError';
}
}
export class CodexProvider extends Provider {
private static preparedBinaryPath: string | undefined;
constructor(
private readonly model: string,
private readonly options: CodexProviderOptions = {}
) {
super(
`${options.providerNamePrefix || 'codex'}/${options.providerNameModel || model}`
);
}
// Verify the CLI is available. Model/auth failures are surfaced by the real
// review call; a model-exec health check costs an extra Codex subscription
// request and can exhaust limited OAuth usage before review starts.
async healthCheck(_timeoutMs: number = 5000): Promise<boolean> {
const timeoutMs = Math.max(500, _timeoutMs ?? 5000);
const mode = (process.env.CODEX_HEALTHCHECK_MODE || 'binary').toLowerCase();
if (mode === 'none' || mode === 'binary') {
return true;
}
let timeoutId: NodeJS.Timeout;
let isTimedOut = false;
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => {
isTimedOut = true;
reject(new Error(`Codex health check timed out after ${timeoutMs}ms`));
}, timeoutMs);
});
try {
const binary = await Promise.race([
this.resolveBinary().then((resolved) => {
if (isTimedOut) {
logger.debug(`Codex binary resolved after timeout (${this.name})`);
}
return resolved;
}),
timeoutPromise,
]);
clearTimeout(timeoutId!);
const result = await this.runCliWithStdin(
binary,
'Respond with exactly: codex-health-ok',
timeoutMs,
{ healthCheck: true }
);
const output = result.lastMessage || result.stdout;
if (!output.includes('codex-health-ok')) {
logger.warn(
`Codex health check returned unexpected output for ${this.name}`
);
return false;
}
return true;
} catch (error) {
if (timeoutId!) {
clearTimeout(timeoutId);
}
logger.warn(
`Codex health check failed for ${this.name}: ${(error as Error).message}`
);
return false;
}
}
async review(
prompt: string,
timeoutMs: number,
executionPolicy?: ProviderExecutionPolicy
): Promise<ReviewResult> {
const started = Date.now();
const binary = await this.resolveBinary();
const agenticContext = this.shouldUseAgenticContext();
const promptForCodex = agenticContext
? await this.wrapAgenticReviewPrompt(prompt)
: this.wrapPromptOnlyReviewPrompt(prompt);
const auditMode = agenticContext ? this.agenticAuditMode() : 'off';
const eventAudit = this.shouldUseEventAudit();
logger.info(
`Running Codex CLI safely: codex exec --model ${this.model} --sandbox read-only --ephemeral ...`
);
try {
const initialTimeoutMs =
executionPolicy?.clampTimeoutMs(timeoutMs) ?? timeoutMs;
if (initialTimeoutMs <= 0) {
const deadlineError = new Error(
'Review execution deadline reached before Codex invocation'
);
deadlineError.name = 'TimeoutError';
throw deadlineError;
}
let runResult = await this.runCliWithStdin(
binary,
promptForCodex,
initialTimeoutMs,
{
healthCheck: false,
outputSchema: this.buildFindingsSchema(),
eventAudit,
jsonEvents: auditMode !== 'off',
acceptReviewOutputOnNonZero: true,
}
);
let content = this.sanitizeReviewContent(
(runResult.lastMessage || runResult.stdout).trim()
);
if (runResult.audit) {
this.logAgenticAudit(runResult.audit, false);
}
let parsed = this.parseNonEmptyReviewContent(content, runResult.stderr);
if (
this.shouldRetryForMissingAgenticExploration(
parsed,
runResult.audit,
prompt,
auditMode
) &&
(executionPolicy?.canStartOptionalRetry() ?? true)
) {
logger.warn(
`Codex agentic review completed without read-only exploration; retrying once for ${this.name}`
);
const firstContent = content;
const firstParsed = parsed;
const firstRunResult = runResult;
try {
const retryTimeoutMs =
executionPolicy?.clampTimeoutMs(timeoutMs) ?? timeoutMs;
if (retryTimeoutMs <= 0) {
throw new Error(
'Review execution deadline reached before Codex agentic retry'
);
}
runResult = await this.runCliWithStdin(
binary,
this.buildAgenticRetryPrompt(promptForCodex, runResult.audit),
retryTimeoutMs,
{
healthCheck: false,
outputSchema: this.buildFindingsSchema(),
eventAudit,
jsonEvents: true,
acceptReviewOutputOnNonZero: true,
}
);
content = this.sanitizeReviewContent(
(runResult.lastMessage || runResult.stdout).trim()
);
if (runResult.audit) {
this.logAgenticAudit(runResult.audit, true);
}
parsed = this.parseNonEmptyReviewContent(content, runResult.stderr);
} catch (retryError) {
if (auditMode === 'strict') {
throw retryError;
}
const normalizedRetryError = this.normalizeCodexError(retryError);
logger.warn(
`Codex agentic retry failed for ${this.name}; preserving first-pass findings. ${normalizedRetryError.message}`
);
content = firstContent;
parsed = firstParsed;
runResult = firstRunResult;
}
if (
runResult !== firstRunResult &&
this.isMissingAgenticExploration(parsed, runResult.audit, prompt) &&
firstParsed.findings.length >= parsed.findings.length
) {
logger.warn(
`Codex agentic retry still lacked read-only exploration and did not add findings; preserving first-pass findings for ${this.name}`
);
content = firstContent;
parsed = firstParsed;
runResult = firstRunResult;
}
}
if (
auditMode === 'strict' &&
this.isMissingAgenticExploration(parsed, runResult.audit, prompt)
) {
throw new Error(
'Codex agentic review completed without recorded read-only repository exploration'
);
}
const durationSeconds = (Date.now() - started) / 1000;
logger.info(
`Codex CLI output for ${this.name}: final=${content.length} bytes, stdout=${runResult.stdout.length} bytes, stderr=${runResult.stderr.length} bytes, duration=${durationSeconds.toFixed(1)}s`
);
return {
content,
durationSeconds,
usage: this.estimateUsage(prompt, content),
findings: parsed.findings,
revalidations: parsed.revalidations,
};
} catch (error) {
const normalized = this.normalizeCodexError(error);
logger.error(`Codex provider failed: ${this.name}`, normalized);
throw normalized;
}
}
async runStructuredPrompt(
prompt: string,
outputSchema: unknown,
timeoutMs: number,
options: {
cwd?: string;
eventAudit?: boolean;
includeWorkspaceEnv?: boolean;
skipGitRepoCheck?: boolean;
} = {}
): Promise<string> {
const binary = await this.resolveBinary();
const { stdout, stderr, lastMessage } = await this.runCliWithStdin(
binary,
prompt,
timeoutMs,
{
healthCheck: false,
outputSchema,
eventAudit: options.eventAudit,
cwd: options.cwd,
includeWorkspaceEnv: options.includeWorkspaceEnv,
disableTools: true,
skipGitRepoCheck: options.skipGitRepoCheck,
}
);
const content = this.sanitizeReviewContent((lastMessage || stdout).trim());
if (!content) {
throw new Error(
`Codex CLI returned no output${stderr ? `; stderr: ${stderr.slice(0, 200)}` : ''}`
);
}
return content;
}
private estimateUsage(prompt: string, content: string) {
const promptTokens = estimateTokensSimple(prompt).tokens;
const completionTokens = estimateTokensSimple(content).tokens;
return {
promptTokens,
completionTokens,
totalTokens: promptTokens + completionTokens,
};
}
private buildExecArgs(options: {
healthCheck: boolean;
outputLastMessageFile: string;
outputSchemaFile?: string;
eventAudit?: boolean;
jsonEvents?: boolean;
disableTools?: boolean;
skipGitRepoCheck?: boolean;
}): string[] {
// The top-level `codex` command starts the interactive TUI and fails in CI.
const args = [
'exec',
'--model',
this.model,
'--sandbox',
'read-only',
'--ephemeral',
'--ignore-rules',
'-c',
'approval_policy=never',
'--output-last-message',
options.outputLastMessageFile,
];
if (!this.shouldUseForkSandboxCodexHomeConfig()) {
args.splice(args.indexOf('--ignore-rules'), 0, '--ignore-user-config');
}
if (options.skipGitRepoCheck) {
args.splice(1, 0, '--skip-git-repo-check');
}
if (options.disableTools) {
args.push(
'--disable',
'shell_tool',
'--disable',
'unified_exec',
'--disable',
'browser_use',
'--disable',
'computer_use',
'--disable',
'js_repl',
'--disable',
'tool_search',
'--disable',
'web_search_request',
'--disable',
'plugins'
);
}
if (options.outputSchemaFile) {
args.push('--output-schema', options.outputSchemaFile);
}
if (options.eventAudit || options.jsonEvents) {
args.push('--json');
}
const effort = options.healthCheck
? process.env.CODEX_HEALTHCHECK_REASONING_EFFORT || 'low'
: process.env.CODEX_REASONING_EFFORT;
if (effort) {
const normalized = effort.trim().toLowerCase();
if (/^[a-z]+$/.test(normalized)) {
args.push('-c', `model_reasoning_effort="${normalized}"`);
}
}
if (this.options.modelProvider === 'openrouter') {
args.push(
'-c',
'model_provider="openrouter"',
'-c',
'model_providers.openrouter.name="openrouter"',
'-c',
'model_providers.openrouter.base_url="https://openrouter.ai/api/v1"',
'-c',
'model_providers.openrouter.env_key="OPENROUTER_API_KEY"'
);
}
args.push('-');
return args;
}
private async runCliWithStdin(
bin: string,
stdin: string,
timeoutMs: number,
options: CodexRunOptions
): Promise<CodexRunResult> {
// Write prompt to temporary file to avoid TTY check issues
// Use restrictive permissions (0600) since prompt may contain sensitive PR diffs
const runId = crypto.randomBytes(8).toString('hex');
const tmpFile = path.join(os.tmpdir(), `codex-prompt-${runId}.txt`);
const outputFile = path.join(os.tmpdir(), `codex-output-${runId}.txt`);
const schemaFile = options.outputSchema
? path.join(os.tmpdir(), `codex-schema-${runId}.json`)
: undefined;
let fd: fs.FileHandle | undefined;
try {
await fs.writeFile(tmpFile, stdin, { encoding: 'utf8', mode: 0o600 });
await fs.writeFile(outputFile, '', { encoding: 'utf8', mode: 0o600 });
if (schemaFile) {
await fs.writeFile(schemaFile, JSON.stringify(options.outputSchema), {
encoding: 'utf8',
mode: 0o600,
});
}
const args = this.buildExecArgs({
healthCheck: options.healthCheck,
outputLastMessageFile: outputFile,
outputSchemaFile: schemaFile,
eventAudit: options.eventAudit && !options.healthCheck,
jsonEvents: options.jsonEvents && !options.healthCheck,
disableTools: options.disableTools,
skipGitRepoCheck: options.skipGitRepoCheck,
});
// Use stdin redirection via file descriptor instead of shell
// This avoids both "stdin is not a terminal" error and shell injection
fd = await fs.open(tmpFile, 'r');
const fdNum = fd.fd;
const { stdout, stderr } = await new Promise<{
stdout: string;
stderr: string;
}>((resolve, reject) => {
const proc = spawn(bin, args, {
stdio: [fdNum, 'pipe', 'pipe'],
detached: true,
cwd: options.cwd || process.cwd(),
env: this.buildSafeEnv(options.includeWorkspaceEnv !== false),
});
let stdout = '';
let stderr = '';
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
logger.warn(
`Codex CLI timeout (${timeoutMs}ms), killing process and all children`
);
try {
if (proc.pid) {
process.kill(-proc.pid, 'SIGKILL');
}
} catch {
proc.kill('SIGKILL');
}
reject(new Error(`Codex CLI timed out after ${timeoutMs}ms`));
}, timeoutMs);
proc.stdout?.on('data', (chunk) => {
stdout += chunk.toString();
});
proc.stderr?.on('data', (chunk) => {
stderr += chunk.toString();
});
proc.on('error', (err) => {
if (!timedOut) {
clearTimeout(timer);
reject(err);
}
});
proc.on('close', (code) => {
if (!timedOut) {
clearTimeout(timer);
if (code !== 0) {
const message = `Codex CLI failed with exit code ${code}: ${this.formatCliError(stderr, stdout)}`;
reject(new CodexCliExitError(code, stdout, stderr, message));
} else {
resolve({ stdout, stderr });
}
}
});
}).catch(async (error) => {
const lastMessage = await this.readOptionalFile(outputFile);
if (
options.acceptReviewOutputOnNonZero &&
this.isUsableReviewOutput(lastMessage)
) {
const exitError =
error instanceof CodexCliExitError ? error : undefined;
logger.warn(
`Codex CLI exited non-zero for ${this.name} but produced valid review JSON; using --output-last-message`
);
return {
stdout: exitError?.stdout || '',
stderr: exitError?.stderr || '',
};
}
throw error;
});
const lastMessage = await this.readOptionalFile(outputFile);
if (options.eventAudit && !options.healthCheck) {
this.logEventAudit(stdout);
}
return {
stdout,
stderr,
lastMessage,
audit:
!options.healthCheck && (options.jsonEvents || options.eventAudit)
? this.buildAgenticAudit(stdout)
: undefined,
};
} finally {
// Clean up temp file and file descriptor
try {
if (fd) {
await fd.close();
}
await fs.unlink(tmpFile);
await fs.unlink(outputFile);
if (schemaFile) {
await fs.unlink(schemaFile);
}
} catch {
// Ignore cleanup errors
}
}
}
private shouldUseAgenticContext(): boolean {
if (this.options.agenticContext !== undefined) {
return this.options.agenticContext;
}
return this.parseBooleanEnv(process.env.CODEX_AGENTIC_CONTEXT, true);
}
private shouldUseEventAudit(): boolean {
if (this.options.eventAudit !== undefined) {
return this.options.eventAudit;
}
return this.parseBooleanEnv(process.env.CODEX_EVENT_AUDIT, false);
}
private agenticAuditMode(): CodexAgenticAuditMode {
const raw = process.env.CODEX_AGENTIC_AUDIT?.trim().toLowerCase();
if (!raw) {
return 'rerun';
}
if (['0', 'false', 'no', 'off'].includes(raw)) {
return 'off';
}
if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on') {
return 'rerun';
}
if (raw === 'rerun' || raw === 'strict') {
return raw;
}
logger.warn(
`Unknown CODEX_AGENTIC_AUDIT value "${raw}", falling back to rerun`
);
return 'rerun';
}
private parseNonEmptyReviewContent(
content: string,
stderr: string
): ParsedReviewOutput {
if (!content) {
throw new Error(
`Codex CLI returned no output${stderr ? `; stderr: ${stderr.slice(0, 200)}` : ''}`
);
}
return parseReviewOutputStrict(content, 'Codex CLI');
}
private shouldRetryForMissingAgenticExploration(
parsed: ParsedReviewOutput,
audit: CodexAgenticAudit | undefined,
prompt: string,
mode: CodexAgenticAuditMode
): boolean {
if (
(mode !== 'rerun' && mode !== 'strict') ||
!this.isMissingAgenticExploration(parsed, audit, prompt)
) {
return false;
}
if (mode === 'strict') return true;
const promptTokens = estimateTokensSimple(prompt).tokens;
if (promptTokens > MAX_OPTIONAL_AGENTIC_RETRY_PROMPT_TOKENS) {
logger.info(
`Skipping optional Codex agentic retry for ${this.name}: prompt is approximately ${promptTokens} tokens (limit ${MAX_OPTIONAL_AGENTIC_RETRY_PROMPT_TOKENS})`
);
return false;
}
return true;
}
private isMissingAgenticExploration(
parsed: ParsedReviewOutput,
audit: CodexAgenticAudit | undefined,
prompt: string
): boolean {
if (!this.looksLikePullRequestReviewPrompt(prompt)) return false;
return !audit || audit.readOnlyExplorationCommands === 0;
}
private looksLikePullRequestReviewPrompt(prompt: string): boolean {
return (
prompt.includes('Files changed:') ||
prompt.includes('Diff:') ||
/^diff --git a\//m.test(prompt)
);
}
private buildAgenticRetryPrompt(
prompt: string,
audit?: CodexAgenticAudit
): string {
const commands =
audit && audit.commands.length > 0
? audit.commands.slice(0, 5).join(' | ')
: 'none recorded';
return [
'Your previous Codex review pass completed without enough recorded read-only repository exploration.',
`Recorded commands: ${commands}`,
'',
'Rerun the review from scratch.',
'Before final JSON, inspect changed hunks and at least one related caller, test, schema, config, or helper file when available using read-only commands such as git diff, git show, rg, git grep, sed, cat, ls, find, pwd, nl, head, or tail.',
'Changed helper/API contract regressions are reportable bugs when callers will behave incorrectly, even if the broken behavior is indirect.',
'Specifically check for inverted boolean/filter/ignore semantics, dropped structured fields, broken draft/recovery/delete flows, stale cache/list summaries, workflow routing regressions, auth/config mistakes, and persistence side effects.',
'If exploration proves there is no concrete bug, return exactly {"findings":[],"revalidations":[]}.',
'',
prompt,
].join('\n');
}
private parseBooleanEnv(
value: string | undefined,
defaultValue: boolean
): boolean {
if (value === undefined || value === '') return defaultValue;
return !['0', 'false', 'no', 'off'].includes(value.trim().toLowerCase());
}
private async wrapAgenticReviewPrompt(prompt: string): Promise<string> {
const contextSeed = await this.buildRepositoryContextSeed(prompt);
return [
'You are running as review-router inside GitHub Actions.',
'',
'Use the deterministic PR context below as the source of truth for review scope.',
contextSeed,
contextSeed ? '' : '',
'You may inspect related repository files before producing findings, but only with read-only shell commands such as rg, sed, cat, git diff, git show, git grep, ls, find, and pwd.',
'Before deciding whether findings is empty or non-empty, run read-only exploration commands: inspect changed source files with git diff/sed, then use rg/git grep on imported or changed symbols to find related files.',
'Inspect at least one directly related file when available, such as imports, called modules, schema/config files, tests, or callers.',
'',
'Universal context discovery checklist:',
'- First identify the project ecosystems from changed file extensions plus nearby manifests, lockfiles, workspace files, and build config such as package.json, pnpm-workspace.yaml, tsconfig.json, pubspec.yaml, pubspec.lock, go.mod, Cargo.toml, pyproject.toml, requirements.txt, pom.xml, build.gradle, composer.json, Gemfile, Dockerfile, Makefile, and CI workflow files.',
'- For every changed symbol or behavior, trace the nearest imports/includes/exports, dependency injection registrations, routes/controllers, schema files, generated protocol files, database migrations, ORM models, event names, feature flags, cache keys, permissions, and public API contracts before reporting a finding.',
'- Prefer repo-local evidence: sibling implementations, previous patterns, tests, mocks, fixtures, generated clients, migration history, and direct callers/callees found with rg/git grep.',
'- For dependencies, inspect committed lockfiles and already available read-only package source/cache directories when present. If dependency source is unavailable and repo-local evidence is not enough, treat the issue as insufficiently proven instead of guessing.',
'- For large PRs, prioritize changed files with security, auth, persistence, migrations, concurrency, realtime/eventing, billing, external API, public contract, or data-loss impact before low-risk formatting or generated files.',
'',
'For CRUD, realtime, cache, or repository-state changes, explicitly compare create/update/delete side effects, broadcasts, invalidation, and listener update paths.',
'For destructive operations such as delete/remove/archive/revoke/cancel, distinguish direct caller response handling from global side effects. A local API response that updates only the caller does not prove other open clients, subscribers, caches, workers, or projections are invalidated. If create/update paths broadcast, invalidate, enqueue, or publish but the new destructive path does not, report it when the changed line is the destructive config/call and no framework evidence proves equivalent global propagation.',
'When a changed file uses framework APIs from a dependency, you may inspect read-only language package caches referenced by lockfiles, such as ~/.pub-cache/git, but never inspect secrets or credentials.',
'Do not produce the final JSON until this context exploration is complete.',
'When a finding depends on related context, cite the concrete related file evidence in the message.',
'Use repository-relative paths only. Do not include absolute local filesystem paths in findings.',
'Do not read environment variables, secret files, ~/.codex, git credentials, or GitHub token files.',
'Do not run package installation, tests, builds, formatters, network commands, or commands that write files.',
'Do not return empty findings until you inspected the changed hunks and at least one related caller, test, schema, config, or helper file when available.',
'Only report real bugs on changed lines from the diff: crashes, data loss, security vulnerabilities, clear user-visible functional regressions such as permanent loading, stale UI state, dead-end navigation, hidden required content, or wrong access control state, or changed helper/API contract regressions that will break callers, tests, workflows, persistence, auth, configuration, MCP tools, or public/internal APIs.',
'Changed helper contracts and semantic inversions are reportable even when the failure is indirect, if callers will behave incorrectly.',
'Specifically check for inverted boolean/filter/ignore semantics, dropped non-string structured fields, broken draft/recovery/delete flows, stale cache/list summaries, workflow routing regressions, auth/config mistakes, and persistence side effects.',
'A repeated local repository pattern, adjacent implementation, generated protocol/schema file, or direct dependency source counts as concrete evidence. If there is still no concrete evidence after exploration, return no finding rather than guessing.',
'',
'<deterministic_review_prompt>',
prompt,
'</deterministic_review_prompt>',
'',
'FINAL OUTPUT CONTRACT:',
'Return exactly one JSON object matching this shape: {"findings":[{"file":"path","startLine":null,"line":1,"endLine":null,"severity":"major","title":"short","message":"specific evidence","suggestion":null}],"revalidations":[{"targetId":"rrt_example","fingerprint":"abc","verdict":"resolved","confidence":0.9,"evidence":[{"path":"src/file.ts","startLine":1,"endLine":2,"reason":"why current code fixes it"}],"rationale":"short reason"}]}',
'Return ONLY one valid JSON object.',
'No markdown, no prose, no code fences, comments, trailing commas, or text before/after the JSON.',
'If no findings, return exactly {"findings":[],"revalidations":[]}.',
'The "findings" array may be empty. "severity" must be one of "critical", "major", or "minor".',
'The "revalidations" array may be empty. Include entries only for targetId values listed in the deterministic prompt.',
'When the issue covers a changed block, set "startLine" to the first affected RIGHT-side line and "endLine" to the last affected RIGHT-side line; keep "line" equal to "endLine". For single-line findings, set "startLine" and "endLine" to null.',
'The "suggestion" field is required by schema; use null unless there is an exact safe replacement.',
'Do not return markdown, prose, or a bare JSON array.',
]
.filter((line) => line !== undefined)
.join('\n');
}
private wrapPromptOnlyReviewPrompt(prompt: string): string {
return [
'Use the deterministic PR context below. Do not assume access to extra context.',
'',
'<deterministic_review_prompt>',
prompt,
'</deterministic_review_prompt>',
'',
'FINAL OUTPUT CONTRACT:',
'Return exactly one JSON object matching this shape: {"findings":[{"file":"path","startLine":null,"line":1,"endLine":null,"severity":"major","title":"short","message":"specific evidence","suggestion":null}],"revalidations":[{"targetId":"rrt_example","fingerprint":"abc","verdict":"resolved","confidence":0.9,"evidence":[{"path":"src/file.ts","startLine":1,"endLine":2,"reason":"why current code fixes it"}],"rationale":"short reason"}]}',
'Return ONLY one valid JSON object.',
'No markdown, no prose, no code fences, comments, trailing commas, or text before/after the JSON.',
'If no findings, return exactly {"findings":[],"revalidations":[]}.',
'The "findings" array may be empty. The "suggestion" field is required and may be null.',
'The "revalidations" array may be empty. Include entries only for targetId values listed in the deterministic prompt.',
'When the issue covers a changed block, set "startLine" to the first affected RIGHT-side line and "endLine" to the last affected RIGHT-side line; keep "line" equal to "endLine". For single-line findings, set "startLine" and "endLine" to null.',
'Do not return markdown, prose, or a bare JSON array.',
].join('\n');
}
private buildFindingsSchema(): unknown {
return buildReviewFindingsSchema();
}
private buildSafeEnv(includeWorkspaceEnv = true): NodeJS.ProcessEnv {
return buildCliSafeEnv({
includeWorkspaceEnv:
includeWorkspaceEnv && !this.shouldUseForkSandboxCodexHomeConfig(),
extraAllowedKeys: [
'CODEX_HOME',
'OPENAI_API_KEY',
...(this.options.modelProvider === 'openrouter'
? ['OPENROUTER_API_KEY']
: []),
],
});
}
private shouldUseForkSandboxCodexHomeConfig(): boolean {
return this.parseBooleanEnv(
process.env.REVIEWROUTER_FORK_AGENTIC_SANDBOX,
false
);
}
private sanitizeReviewContent(content: string): string {
const cwd = process.cwd().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return content
.replace(new RegExp(`${cwd}/?`, 'g'), '')
.replace(/\/home\/runner\/work\/[^/\s")]+\/[^/\s")]+\//g, '')
.replace(/\/private\/tmp\/[^/\s")]+\//g, '');
}
private async buildRepositoryContextSeed(prompt: string): Promise<string> {
const changedFiles = this.extractChangedFiles(prompt)
.filter((file) => this.isContextReadableFile(file))
.slice(0, 5);
if (changedFiles.length === 0) {
return '';
}
const snippets: string[] = [];
const relatedFiles = new Set<string>();
for (const file of changedFiles) {
const content = await this.readRepoFileSnippet(file);
if (!content) continue;
snippets.push(this.formatContextSnippet(file, 'changed', content));
for (const related of this.extractRelatedImportFiles(file, content)) {
if (this.isContextReadableFile(related)) {
relatedFiles.add(related);
}
}
}
for (const related of this.findIdentifierRelatedFiles(changedFiles)) {
if (this.isContextReadableFile(related)) {
relatedFiles.add(related);
}
}
for (const file of [...relatedFiles]
.filter((file) => !changedFiles.includes(file))
.slice(0, 8)) {
const content = await this.readRepoFileSnippet(file);
if (content) {
snippets.push(this.formatContextSnippet(file, 'related', content));
}
}
if (snippets.length === 0) {
return '';
}
return [
'DETERMINISTIC REPOSITORY CONTEXT SEED:',
'These snippets were read before Codex agentic exploration. Use them as evidence, but only comment on changed lines.',
...snippets,
'END DETERMINISTIC REPOSITORY CONTEXT SEED',
].join('\n');
}
private extractChangedFiles(prompt: string): string[] {
const files = new Set<string>();
const fileListPattern =
/^- ([^\s]+) \((?:added|modified|removed|renamed|changed)/gm;
let match;
while ((match = fileListPattern.exec(prompt)) !== null) {
files.add(match[1]);
}
const diffPattern = /^diff --git a\/(.+?) b\/(.+?)$/gm;
while ((match = diffPattern.exec(prompt)) !== null) {
files.add(match[2]);
}
return [...files];
}
private isContextReadableFile(file: string): boolean {
const normalized = this.normalizeRepoPath(file);
if (!normalized) return false;
const lower = normalized.toLowerCase();
if (
lower.includes('/.git/') ||
lower.includes('/.codex/') ||
lower.includes('.env') ||
lower.includes('secret') ||
lower.includes('credential') ||
lower.endsWith('.pem') ||
lower.endsWith('.key') ||
lower.endsWith('auth.json')
) {
return false;
}
return /\.(?:[cm]?js|jsx|tsx?|py|go|rs|java|kt|kts|dart|rb|php|cs|cpp|c|h|hpp|swift|scala|json|ya?ml|toml|sql|graphql|proto)$/i.test(
normalized
);
}
private normalizeRepoPath(file: string): string | null {
if (!file || file.includes('\0') || path.isAbsolute(file)) {
return null;
}
const normalized = path.normalize(file).replace(/\\/g, '/');
if (
normalized === '.' ||
normalized.startsWith('../') ||
normalized === '..'
) {
return null;
}
return normalized;
}
private async readRepoFileSnippet(file: string): Promise<string> {
const normalized = this.normalizeRepoPath(file);
if (!normalized) return '';
const repoRoot = process.cwd();
const fullPath = path.resolve(repoRoot, normalized);
if (!fullPath.startsWith(repoRoot + path.sep)) {
return '';
}
try {
const stat = await fs.stat(fullPath);
if (!stat.isFile() || stat.size > 200_000) {
return '';
}
const content = await fs.readFile(fullPath, 'utf8');
return content.split(/\r?\n/).slice(0, 220).join('\n').slice(0, 16_000);
} catch {
return '';
}
}
private extractRelatedImportFiles(
fromFile: string,
content: string
): string[] {
const imports = new Set<string>();
const importPattern =
/(?:import\s+(?:[^'"]+\s+from\s+)?|export\s+[^'"]+\s+from\s+|require\(|import\s+|export\s+)\s*['"]([^'"]+)['"]/g;
let match;
while ((match = importPattern.exec(content)) !== null) {
const specifier = match[1];
const resolved = specifier.startsWith('.')
? this.resolveRelativeImport(fromFile, specifier)
: this.resolvePackageImport(specifier);
if (resolved) imports.add(resolved);
}
return [...imports];
}
private resolveRelativeImport(
fromFile: string,
specifier: string
): string | null {
const base = path.dirname(fromFile);
const raw = this.normalizeRepoPath(path.join(base, specifier));
if (!raw) return null;
const candidates = [
raw,
...['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.json'].map(
(ext) => `${raw}${ext}`
),
...['.ts', '.tsx', '.js', '.jsx', '.json'].map((ext) =>
path.posix.join(raw, `index${ext}`)
),
];
for (const candidate of candidates) {
const normalized = this.normalizeRepoPath(candidate);
if (!normalized || !this.isContextReadableFile(normalized)) continue;
try {
const fullPath = path.resolve(process.cwd(), normalized);
if (fullPath.startsWith(process.cwd() + path.sep)) {
const stat = fsSync.statSync(fullPath);
if (stat.isFile()) return normalized;
}
} catch {
// Try next candidate.
}
}
return null;
}
private resolvePackageImport(specifier: string): string | null {
const match = /^package:([^/]+)\/(.+)$/.exec(specifier);
if (!match) return null;
const [, packageName, packagePath] = match;
const roots = this.getWorkspacePackageRoots();
const root =
roots.get(packageName) || this.getDependencyPackageRoot(packageName);
if (!root) return null;
return this.resolveImportCandidate(path.posix.join(root, packagePath));
}
private getDependencyPackageRoot(packageName: string): string | null {
if (!this.parseBooleanEnv(process.env.CODEX_DEPENDENCY_CONTEXT, true)) {
return null;
}
const dependency = this.findGitDependency(packageName);
if (!dependency) return null;
const safePackage = packageName.replace(/[^a-zA-Z0-9_.-]/g, '_');