forked from keithah/multi-provider-code-review
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodex-provider.test.ts
More file actions
1393 lines (1241 loc) · 45.6 KB
/
Copy pathcodex-provider.test.ts
File metadata and controls
1393 lines (1241 loc) · 45.6 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 { EventEmitter } from 'events';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { spawn, spawnSync } from 'child_process';
import { CodexProvider } from '../../../src/providers/codex';
jest.mock('child_process', () => ({
spawn: jest.fn(),
spawnSync: jest.fn(),
}));
const spawnMock = spawn as unknown as jest.Mock;
const spawnSyncMock = spawnSync as unknown as jest.Mock;
function createMockProcess(onStart?: (proc: any) => void, closeCode = 0): any {
const proc = new EventEmitter() as any;
proc.stdout = new EventEmitter();
proc.stderr = new EventEmitter();
proc.kill = jest.fn();
proc.pid = 12345;
process.nextTick(() => {
onStart?.(proc);
proc.emit('close', closeCode);
});
return proc;
}
describe('CodexProvider', () => {
const originalEnv = process.env;
beforeEach(() => {
jest.clearAllMocks();
process.env = { ...originalEnv };
spawnSyncMock.mockReturnValue({ status: 0, stdout: '', stderr: '' });
});
afterAll(() => {
process.env = originalEnv;
});
it('builds read-only agentic exec args without dangerous sandbox bypass', () => {
const provider = new CodexProvider('gpt-5.4-mini');
const args = (provider as any).buildExecArgs({
healthCheck: false,
outputLastMessageFile: '/tmp/codex-output.txt',
outputSchemaFile: '/tmp/codex-schema.json',
eventAudit: true,
});
expect(args).toContain('exec');
expect(args).toContain('--sandbox');
expect(args).toContain('read-only');
expect(args).toContain('--ephemeral');
expect(args).toContain('--ignore-user-config');
expect(args).toContain('--ignore-rules');
expect(args).toContain('--output-schema');
expect(args).toContain('/tmp/codex-schema.json');
expect(args).toContain('--output-last-message');
expect(args).toContain('/tmp/codex-output.txt');
expect(args).toContain('--json');
expect(args).not.toContain('--dangerously-bypass-approvals-and-sandbox');
});
it('allows generated CODEX_HOME config in fork agentic sandbox mode', () => {
process.env.REVIEWROUTER_FORK_AGENTIC_SANDBOX = 'true';
const provider = new CodexProvider('gpt-5.5');
const args = (provider as any).buildExecArgs({
healthCheck: false,
outputLastMessageFile: '/tmp/codex-output.txt',
outputSchemaFile: '/tmp/codex-schema.json',
eventAudit: true,
});
expect(args).not.toContain('--ignore-user-config');
expect(args).toContain('--ignore-rules');
expect(args).toContain('--sandbox');
expect(args).toContain('read-only');
});
it('can request JSON events for agentic audit without enabling verbose event audit', () => {
const provider = new CodexProvider('gpt-5.4-mini');
const args = (provider as any).buildExecArgs({
healthCheck: false,
outputLastMessageFile: '/tmp/codex-output.txt',
jsonEvents: true,
eventAudit: false,
});
expect(args).toContain('--json');
});
it('can route Codex CLI through OpenRouter without user config', () => {
const provider = new CodexProvider('openai/gpt-5.3-codex', {
modelProvider: 'openrouter',
providerNamePrefix: 'codex-openrouter',
});
const args = (provider as any).buildExecArgs({
healthCheck: false,
outputLastMessageFile: '/tmp/codex-output.txt',
outputSchemaFile: '/tmp/codex-schema.json',
});
expect(provider.name).toBe('codex-openrouter/openai/gpt-5.3-codex');
expect(args).toEqual(
expect.arrayContaining([
'-c',
'model_provider="openrouter"',
'model_providers.openrouter.name="openrouter"',
'model_providers.openrouter.base_url="https://openrouter.ai/api/v1"',
'model_providers.openrouter.env_key="OPENROUTER_API_KEY"',
])
);
expect(args).toContain('--ignore-user-config');
});
it('can keep public OpenRouter provider identity while stripping instance suffix from Codex model', () => {
const provider = new CodexProvider('openai/gpt-oss-120b:free', {
modelProvider: 'openrouter',
providerNamePrefix: 'openrouter',
providerNameModel: 'openai/gpt-oss-120b:free#8',
});
const args = (provider as any).buildExecArgs({
healthCheck: false,
outputLastMessageFile: '/tmp/codex-output.txt',
});
expect(provider.name).toBe('openrouter/openai/gpt-oss-120b:free#8');
expect(args).toContain('openai/gpt-oss-120b:free');
expect(args).not.toContain('openai/gpt-oss-120b:free#8');
});
it('uses lightweight health checks by default to avoid consuming Codex usage', async () => {
spawnMock.mockImplementation((_cmd: string, _args: string[]) =>
createMockProcess()
);
const provider = new CodexProvider('gpt-5.4-mini');
await expect(provider.healthCheck(1000)).resolves.toBe(true);
expect(spawnMock).not.toHaveBeenCalled();
});
it('supports explicit exec health checks when requested', async () => {
process.env.CODEX_HEALTHCHECK_MODE = 'exec';
spawnMock.mockImplementation((_cmd: string, args: string[]) => {
if (args.includes('--version')) {
return createMockProcess();
}
return createMockProcess(() => {
const outputIndex = args.indexOf('--output-last-message');
fs.writeFileSync(args[outputIndex + 1], 'codex-health-ok');
});
});
const provider = new CodexProvider('gpt-5.4-mini');
await expect(provider.healthCheck(1000)).resolves.toBe(true);
const execCall = spawnMock.mock.calls.find(
(call) => Array.isArray(call[1]) && call[1][0] === 'exec'
);
expect(execCall).toBeTruthy();
expect(execCall?.[1]).toContain('gpt-5.4-mini');
});
it('can disable interactive/tool features for isolated discussion prompts', () => {
const provider = new CodexProvider('gpt-5.4-mini');
const args = (provider as any).buildExecArgs({
healthCheck: false,
outputLastMessageFile: '/tmp/codex-output.txt',
outputSchemaFile: '/tmp/codex-schema.json',
disableTools: true,
skipGitRepoCheck: true,
});
expect(args).toEqual(
expect.arrayContaining([
'--skip-git-repo-check',
'--disable',
'shell_tool',
'unified_exec',
'browser_use',
'computer_use',
'plugins',
])
);
expect(args.indexOf('--skip-git-repo-check')).toBe(1);
});
it('sanitizes spawned Codex environment', () => {
process.env.PATH = '/usr/bin';
process.env.HOME = '/home/runner';
process.env.CODEX_HOME = '/tmp/codex';
process.env.OPENAI_API_KEY = 'sk-test';
process.env.GITHUB_TOKEN = 'gh-token';
process.env.INPUT_GITHUB_TOKEN = 'input-token';
process.env.OPENROUTER_API_KEY = 'or-key';
const provider = new CodexProvider('gpt-5.4-mini');
const env = (provider as any).buildSafeEnv();
expect(env.PATH).toBe('/usr/bin');
expect(env.HOME).toBe('/home/runner');
expect(env.CODEX_HOME).toBe('/tmp/codex');
expect(env.OPENAI_API_KEY).toBe('sk-test');
expect(env.GITHUB_TOKEN).toBeUndefined();
expect(env.INPUT_GITHUB_TOKEN).toBeUndefined();
expect(env.OPENROUTER_API_KEY).toBeUndefined();
});
it('allows OpenRouter API key only for OpenRouter-backed Codex runs', () => {
process.env.PATH = '/usr/bin';
process.env.HOME = '/home/runner';
process.env.OPENROUTER_API_KEY = 'or-key';
const provider = new CodexProvider('openai/gpt-5.3-codex', {
modelProvider: 'openrouter',
providerNamePrefix: 'codex-openrouter',
});
const env = (provider as any).buildSafeEnv();
expect(env.OPENROUTER_API_KEY).toBe('or-key');
});
it('uses REVIEWROUTER_CODEX_BINARY when provided', async () => {
process.env.REVIEWROUTER_CODEX_BINARY = '/tmp/reviewrouter-codex';
spawnMock.mockReturnValue(createMockProcess());
const provider = new CodexProvider('gpt-5.4-mini');
const binary = await (provider as any).resolveBinary();
expect(binary).toBe('/tmp/reviewrouter-codex');
expect(spawnMock).toHaveBeenCalledWith(
'/tmp/reviewrouter-codex',
['--version'],
expect.objectContaining({
cwd: os.tmpdir(),
env: expect.objectContaining({
GIT_CONFIG_GLOBAL: '/dev/null',
GIT_CONFIG_NOSYSTEM: '1',
}),
stdio: 'ignore',
})
);
});
it('treats binary health check mode as a lightweight readiness check', async () => {
process.env.CODEX_HEALTHCHECK_MODE = 'binary';
const provider = new CodexProvider('gpt-5.4-mini');
const healthy = await provider.healthCheck(30_000);
expect(healthy).toBe(true);
expect(spawnMock).not.toHaveBeenCalled();
});
it('falls back to the prepared rotating Codex CLI install root', async () => {
const installRoot = fs.mkdtempSync(
path.join(os.tmpdir(), 'reviewrouter-codex-cli-')
);
const binDir = path.join(installRoot, 'node_modules', '.bin');
fs.mkdirSync(binDir, { recursive: true });
const codexBinary = path.join(binDir, 'codex');
fs.writeFileSync(codexBinary, '#!/usr/bin/env node\n');
fs.chmodSync(codexBinary, 0o755);
spawnMock.mockImplementation((cmd: string) => {
if (cmd === 'codex' || cmd === 'codex-cli') {
return createMockProcess(undefined, 1);
}
return createMockProcess();
});
try {
const provider = new CodexProvider('gpt-5.4-mini');
const binary = await (provider as any).resolveBinary();
expect(binary).toBe(codexBinary);
} finally {
fs.rmSync(installRoot, { recursive: true, force: true });
}
});
it('trusts the pinned Codex CLI prepared by the bootstrap resolver', async () => {
(CodexProvider as any).preparedBinaryPath = undefined;
const failedCommands = new Set(['codex', 'codex-cli']);
spawnMock.mockImplementation((cmd: string) => {
if (failedCommands.has(cmd)) {
return createMockProcess(undefined, 1);
}
return createMockProcess();
});
const provider = new CodexProvider('gpt-5.4-mini');
const binary = await (provider as any).resolveBinary();
expect(binary).toContain('reviewrouter-codex-cli-');
expect(binary).toContain(path.join('node_modules', '.bin', 'codex'));
});
it('allows agentic review findings for concrete user-visible regressions', async () => {
const provider = new CodexProvider('gpt-5.4-mini');
const prompt = await (provider as any).wrapAgenticReviewPrompt(
'review prompt'
);
expect(prompt).toContain('user-visible functional regressions');
expect(prompt).toContain('permanent loading');
expect(prompt).toContain('stale UI state');
expect(prompt).toContain('create/update/delete side effects');
expect(prompt).toContain('dead-end navigation');
expect(prompt).toContain('wrong access control state');
expect(prompt).toContain('changed helper/API contract regressions');
expect(prompt).toContain('inverted boolean/filter/ignore semantics');
expect(prompt).toContain('dropped non-string structured fields');
expect(prompt).toContain('broken draft/recovery/delete flows');
expect(prompt).toContain('Universal context discovery checklist');
expect(prompt).toContain('package.json');
expect(prompt).toContain('pubspec.lock');
expect(prompt).toContain('go.mod');
expect(prompt).toContain('pyproject.toml');
expect(prompt).toContain('Cargo.toml');
expect(prompt).toContain('trace the nearest imports/includes/exports');
expect(prompt).toContain('treat the issue as insufficiently proven');
expect(prompt).toContain('distinguish direct caller response handling');
expect(prompt).toContain('does not prove other open clients');
expect(prompt).toContain(
'no framework evidence proves equivalent global propagation'
);
});
it('adds a strict JSON-only output contract to agentic prompts', async () => {
const provider = new CodexProvider('gpt-5.4-mini');
const prompt = await (provider as any).wrapAgenticReviewPrompt(
'review prompt'
);
expect(prompt).toContain('Return ONLY one valid JSON object');
expect(prompt).toContain('No markdown, no prose, no code fences');
expect(prompt).toContain('comments, trailing commas');
expect(prompt).toContain('{"findings":[],"revalidations":[]}');
});
it('adds a strict JSON-only output contract to prompt-only prompts', () => {
const provider = new CodexProvider('gpt-5.4-mini');
const prompt = (provider as any).wrapPromptOnlyReviewPrompt(
'review prompt'
);
expect(prompt).toContain('Return ONLY one valid JSON object');
expect(prompt).toContain('No markdown, no prose, no code fences');
expect(prompt).toContain('comments, trailing commas');
expect(prompt).toContain('{"findings":[],"revalidations":[]}');
});
it('parses strict schema findings with nullable suggestion', () => {
const provider = new CodexProvider('gpt-5.4-mini');
const findings = (provider as any).extractFindings(
JSON.stringify({
findings: [
{
file: 'src/app.ts',
line: 42,
severity: 'major',
title: 'Crash',
message: 'This can crash.',
suggestion: null,
},
],
})
);
expect(findings).toHaveLength(1);
expect(findings[0]).toMatchObject({
file: 'src/app.ts',
line: 42,
severity: 'major',
});
expect(findings[0].suggestion).toBeUndefined();
});
it('parses strict schema findings with multi-line ranges', () => {
const provider = new CodexProvider('gpt-5.4-mini');
const findings = (provider as any).extractFindings(
JSON.stringify({
findings: [
{
file: 'src/app.ts',
startLine: 40,
line: 42,
endLine: 42,
severity: 'major',
title: 'Crash',
message: 'This changed block can crash.',
suggestion: null,
},
],
})
);
expect(findings).toHaveLength(1);
expect(findings[0]).toMatchObject({
file: 'src/app.ts',
startLine: 40,
line: 42,
endLine: 42,
severity: 'major',
});
});
it('reads final review content from --output-last-message instead of stdout', async () => {
spawnMock.mockImplementation((_cmd: string, args: string[]) => {
if (args.includes('--version')) {
return createMockProcess();
}
return createMockProcess(() => {
const outputIndex = args.indexOf('--output-last-message');
const outputFile = args[outputIndex + 1];
fs.writeFileSync(outputFile, '{"findings":[]}');
});
});
const provider = new CodexProvider('gpt-5.4-mini', {
agenticContext: true,
eventAudit: false,
});
const result = await provider.review('review prompt', 1000);
const execCall = spawnMock.mock.calls.find(
(call) => Array.isArray(call[1]) && call[1][0] === 'exec'
);
expect(result.content).toBe('{"findings":[]}');
expect(result.findings).toEqual([]);
expect(execCall).toBeTruthy();
expect(execCall?.[1]).toContain('--output-schema');
expect(execCall?.[1]).not.toContain(
'--dangerously-bypass-approvals-and-sandbox'
);
});
it('drops GitHub workspace env for OpenRouter-backed Codex in fork sandbox mode', async () => {
process.env.REVIEWROUTER_FORK_AGENTIC_SANDBOX = 'true';
process.env.GITHUB_WORKSPACE = '/home/runner/work/repo/repo';
process.env.OPENROUTER_API_KEY = 'sk-or-test';
spawnMock.mockImplementation((_cmd: string, args: string[]) => {
if (args.includes('--version')) {
return createMockProcess();
}
return createMockProcess(() => {
const outputIndex = args.indexOf('--output-last-message');
const outputFile = args[outputIndex + 1];
fs.writeFileSync(outputFile, '{"findings":[]}');
});
});
const provider = new CodexProvider('openai/gpt-5.3-codex', {
agenticContext: true,
eventAudit: false,
modelProvider: 'openrouter',
providerNamePrefix: 'openrouter',
});
await provider.review('review prompt', 1000);
const execCall = spawnMock.mock.calls.find(
(call) => Array.isArray(call[1]) && call[1][0] === 'exec'
);
expect(execCall?.[1]).toContain('model_provider="openrouter"');
expect(execCall?.[2]?.env.OPENROUTER_API_KEY).toBe('sk-or-test');
expect(execCall?.[2]?.env.GITHUB_WORKSPACE).toBeUndefined();
});
it('reruns agentic review once when empty findings have no recorded exploration', async () => {
let execCount = 0;
const finding = {
findings: [
{
file: 'src/main/services/error/TriggerMatcher.ts',
startLine: null,
line: 83,
endLine: null,
severity: 'major',
title: 'Ignore patterns are inverted',
message:
'The changed matchesIgnorePatterns helper now returns true when no ignore patterns match, so callers skip errors that should be reported.',
suggestion: null,
},
],
revalidations: [],
};
spawnMock.mockImplementation((_cmd: string, args: string[]) => {
if (args.includes('--version')) {
return createMockProcess();
}
execCount += 1;
return createMockProcess((proc) => {
const outputIndex = args.indexOf('--output-last-message');
const outputFile = args[outputIndex + 1];
if (execCount === 1) {
fs.writeFileSync(outputFile, '{"findings":[],"revalidations":[]}');
return;
}
proc.stdout.emit(
'data',
`${JSON.stringify({
item: {
type: 'command_execution',
command:
'sed -n "70,95p" src/main/services/error/TriggerMatcher.ts',
},
})}\n`
);
fs.writeFileSync(outputFile, JSON.stringify(finding));
});
});
const provider = new CodexProvider('gpt-5.4-mini', {
agenticContext: true,
});
const result = await provider.review(
[
'Files changed:',
'- src/main/services/error/TriggerMatcher.ts (modified, +1/-1)',
'',
'Diff:',
'diff --git a/src/main/services/error/TriggerMatcher.ts b/src/main/services/error/TriggerMatcher.ts',
].join('\n'),
1000
);
const execCalls = spawnMock.mock.calls.filter(
(call) => Array.isArray(call[1]) && call[1][0] === 'exec'
);
expect(execCalls).toHaveLength(2);
expect(execCalls[0][1]).toContain('--json');
expect(result.findings ?? []).toHaveLength(1);
expect(result.findings?.[0]?.title).toBe('Ignore patterns are inverted');
});
it('reruns agentic review when non-empty findings have no recorded exploration', async () => {
let execCount = 0;
const firstFinding = {
findings: [
{
file: 'src/renderer/utils/memberHelpers.ts',
startLine: null,
line: 1353,
endLine: null,
severity: 'major',
title: 'Spawn diagnostic errors are hidden',
message:
'The helper marks errored bootstrap-confirmed spawn entries as healthy.',
suggestion: null,
},
],
revalidations: [],
};
const exploredFinding = {
findings: [
{
file: 'src/renderer/utils/memberHelpers.ts',
startLine: null,
line: 1353,
endLine: null,
severity: 'major',
title: 'Spawn diagnostic errors are hidden after caller inspection',
message:
'After checking MemberList and teamRuntimeDisplayRows, the helper still renders spawn-level error diagnostics as healthy.',
suggestion: null,
},
],
revalidations: [],
};
spawnMock.mockImplementation((_cmd: string, args: string[]) => {
if (args.includes('--version')) {
return createMockProcess();
}
execCount += 1;
return createMockProcess((proc) => {
const outputIndex = args.indexOf('--output-last-message');
const outputFile = args[outputIndex + 1];
if (execCount === 1) {
fs.writeFileSync(outputFile, JSON.stringify(firstFinding));
return;
}
proc.stdout.emit(
'data',
`${JSON.stringify({
item: {
type: 'command_execution',
command: 'rg -n "runtimeDiagnosticSeverity" src/renderer',
},
})}\n`
);
fs.writeFileSync(outputFile, JSON.stringify(exploredFinding));
});
});
const provider = new CodexProvider('gpt-5.4-mini', {
agenticContext: true,
});
const result = await provider.review(
[
'Files changed:',
'- src/renderer/utils/memberHelpers.ts (modified, +4/-1)',
'',
'Diff:',
'diff --git a/src/renderer/utils/memberHelpers.ts b/src/renderer/utils/memberHelpers.ts',
].join('\n'),
1000
);
const execCalls = spawnMock.mock.calls.filter(
(call) => Array.isArray(call[1]) && call[1][0] === 'exec'
);
expect(execCalls).toHaveLength(2);
expect(result.findings?.[0]?.title).toBe(
'Spawn diagnostic errors are hidden after caller inspection'
);
});
it('preserves first-pass findings when audit retry still lacks exploration and returns fewer findings', async () => {
let execCount = 0;
const firstFinding = {
findings: [
{
file: 'src/features/team-runtime-lanes/core/domain/buildMixedPersistedLaunchSnapshot.ts',
startLine: 236,
line: 240,
endLine: 240,
severity: 'major',
title: 'Runtime diagnostic errors are rewritten as healthy',
message:
'The launch snapshot rewrites an errored runtime diagnostic as confirmed_alive.',
suggestion: null,
},
],
revalidations: [],
};
spawnMock.mockImplementation((_cmd: string, args: string[]) => {
if (args.includes('--version')) {
return createMockProcess();
}
execCount += 1;
return createMockProcess(() => {
const outputIndex = args.indexOf('--output-last-message');
const outputFile = args[outputIndex + 1];
fs.writeFileSync(
outputFile,
execCount === 1
? JSON.stringify(firstFinding)
: '{"findings":[],"revalidations":[]}'
);
});
});
const provider = new CodexProvider('gpt-5.4-mini', {
agenticContext: true,
});
const result = await provider.review(
[
'Files changed:',
'- src/features/team-runtime-lanes/core/domain/buildMixedPersistedLaunchSnapshot.ts (modified, +8/-2)',
'',
'Diff:',
'diff --git a/src/features/team-runtime-lanes/core/domain/buildMixedPersistedLaunchSnapshot.ts b/src/features/team-runtime-lanes/core/domain/buildMixedPersistedLaunchSnapshot.ts',
].join('\n'),
1000
);
const execCalls = spawnMock.mock.calls.filter(
(call) => Array.isArray(call[1]) && call[1][0] === 'exec'
);
expect(execCalls).toHaveLength(2);
expect(result.findings).toHaveLength(1);
expect(result.findings?.[0]?.title).toBe(
'Runtime diagnostic errors are rewritten as healthy'
);
});
it('preserves first-pass findings when audit retry still lacks exploration and returns the same count', async () => {
let execCount = 0;
const firstFinding = {
findings: [
{
file: 'src/features/team-runtime-lanes/core/domain/buildMixedPersistedLaunchSnapshot.ts',
startLine: 236,
line: 240,
endLine: 240,
severity: 'major',
title: 'Runtime diagnostic errors are rewritten as healthy',
message:
'The launch snapshot rewrites an errored runtime diagnostic as confirmed_alive.',
suggestion: null,
},
],
revalidations: [],
};
const retryFinding = {
findings: [
{
file: 'src/features/team-runtime-lanes/core/domain/buildMixedPersistedLaunchSnapshot.ts',
startLine: 236,
line: 240,
endLine: 240,
severity: 'major',
title:
'Retry result without exploration should not replace first pass',
message:
'This retry still did not inspect repository context, so it should not replace the first finding.',
suggestion: null,
},
],
revalidations: [],
};
spawnMock.mockImplementation((_cmd: string, args: string[]) => {
if (args.includes('--version')) {
return createMockProcess();
}
execCount += 1;
return createMockProcess(() => {
const outputIndex = args.indexOf('--output-last-message');
const outputFile = args[outputIndex + 1];
fs.writeFileSync(
outputFile,
JSON.stringify(execCount === 1 ? firstFinding : retryFinding)
);
});
});
const provider = new CodexProvider('gpt-5.4-mini', {
agenticContext: true,
});
const result = await provider.review(
[
'Files changed:',
'- src/features/team-runtime-lanes/core/domain/buildMixedPersistedLaunchSnapshot.ts (modified, +8/-2)',
'',
'Diff:',
'diff --git a/src/features/team-runtime-lanes/core/domain/buildMixedPersistedLaunchSnapshot.ts b/src/features/team-runtime-lanes/core/domain/buildMixedPersistedLaunchSnapshot.ts',
].join('\n'),
1000
);
const execCalls = spawnMock.mock.calls.filter(
(call) => Array.isArray(call[1]) && call[1][0] === 'exec'
);
expect(execCalls).toHaveLength(2);
expect(result.findings).toHaveLength(1);
expect(result.findings?.[0]?.title).toBe(
'Runtime diagnostic errors are rewritten as healthy'
);
});
it('preserves first-pass findings when audit retry hits a Codex usage limit', async () => {
let execCount = 0;
const firstFinding = {
findings: [
{
file: 'src/app.ts',
startLine: null,
line: 42,
endLine: null,
severity: 'major',
title: 'Retry quota should not discard first pass',
message:
'The first pass produced a valid review result before the exploration retry hit quota.',
suggestion: null,
},
],
revalidations: [],
};
spawnMock.mockImplementation((_cmd: string, args: string[]) => {
if (args.includes('--version')) {
return createMockProcess();
}
execCount += 1;
return createMockProcess(
(proc) => {
const outputIndex = args.indexOf('--output-last-message');
const outputFile = args[outputIndex + 1];
if (execCount === 1) {
fs.writeFileSync(outputFile, JSON.stringify(firstFinding));
return;
}
proc.stderr.emit(
'data',
"You've hit your usage limit. Visit https://example.test to purchase more credits."
);
},
execCount === 1 ? 0 : 1
);
});
const provider = new CodexProvider('gpt-5.4-mini', {
agenticContext: true,
});
const result = await provider.review(
[
'Files changed:',
'- src/app.ts (modified, +1/-1)',
'',
'Diff:',
'diff --git a/src/app.ts b/src/app.ts',
].join('\n'),
1000
);
const execCalls = spawnMock.mock.calls.filter(
(call) => Array.isArray(call[1]) && call[1][0] === 'exec'
);
expect(execCalls).toHaveLength(2);
expect(result.findings).toHaveLength(1);
expect(result.findings?.[0]?.title).toBe(
'Retry quota should not discard first pass'
);
});
it('does not rerun empty agentic review when a read-only exploration command is recorded', async () => {
spawnMock.mockImplementation((_cmd: string, args: string[]) => {
if (args.includes('--version')) {
return createMockProcess();
}
return createMockProcess((proc) => {
const outputIndex = args.indexOf('--output-last-message');
proc.stdout.emit(
'data',
`${JSON.stringify({
item: {
type: 'command_execution',
command: 'git diff -- src/main/services/error/TriggerMatcher.ts',
},
})}\n`
);
fs.writeFileSync(
args[outputIndex + 1],
'{"findings":[],"revalidations":[]}'
);
});
});
const provider = new CodexProvider('gpt-5.4-mini', {
agenticContext: true,
});
const result = await provider.review(
[
'Files changed:',
'- src/main/services/error/TriggerMatcher.ts (modified, +1/-1)',
'',
'Diff:',
'diff --git a/src/main/services/error/TriggerMatcher.ts b/src/main/services/error/TriggerMatcher.ts',
].join('\n'),
1000
);
const execCalls = spawnMock.mock.calls.filter(
(call) => Array.isArray(call[1]) && call[1][0] === 'exec'
);
expect(execCalls).toHaveLength(1);
expect(result.findings).toEqual([]);
});
it('does not repeat an oversized prompt only to satisfy the optional agentic audit', async () => {
spawnMock.mockImplementation((_cmd: string, args: string[]) => {
if (args.includes('--version')) {
return createMockProcess();
}
return createMockProcess(() => {
const outputIndex = args.indexOf('--output-last-message');
fs.writeFileSync(
args[outputIndex + 1],
'{"findings":[],"revalidations":[]}'
);
});
});
const provider = new CodexProvider('gpt-5.4-mini', {
agenticContext: true,
});
const result = await provider.review(
[
'Files changed:',
'- src/generated.ts (modified, +1/-1)',
'',
'Diff:',
'diff --git a/src/generated.ts b/src/generated.ts',
'x'.repeat(120_000),
].join('\n'),
1000
);
const execCalls = spawnMock.mock.calls.filter(
(call) => Array.isArray(call[1]) && call[1][0] === 'exec'
);
expect(execCalls).toHaveLength(1);
expect(result.findings).toEqual([]);
});
it('strict agentic audit reruns an oversized prompt, then fails if exploration is still missing', async () => {
process.env.CODEX_AGENTIC_AUDIT = 'strict';
spawnMock.mockImplementation((_cmd: string, args: string[]) => {
if (args.includes('--version')) {
return createMockProcess();
}
return createMockProcess(() => {
const outputIndex = args.indexOf('--output-last-message');
fs.writeFileSync(
args[outputIndex + 1],
'{"findings":[],"revalidations":[]}'
);
});
});
const provider = new CodexProvider('gpt-5.4-mini', {
agenticContext: true,
});
await expect(
provider.review(
[
'Files changed:',
'- src/app.ts (modified, +1/-1)',
'',
'Diff:',
'diff --git a/src/app.ts b/src/app.ts',
'x'.repeat(120_000),
].join('\n'),
1000
)
).rejects.toThrow('without recorded read-only repository exploration');
const execCalls = spawnMock.mock.calls.filter(
(call) => Array.isArray(call[1]) && call[1][0] === 'exec'
);
expect(execCalls).toHaveLength(2);
});
it('strict agentic audit fails non-empty findings when retry still lacks exploration', async () => {
process.env.CODEX_AGENTIC_AUDIT = 'strict';
spawnMock.mockImplementation((_cmd: string, args: string[]) => {
if (args.includes('--version')) {
return createMockProcess();
}
return createMockProcess(() => {
const outputIndex = args.indexOf('--output-last-message');
fs.writeFileSync(
args[outputIndex + 1],
JSON.stringify({
findings: [
{
file: 'src/app.ts',
startLine: null,
line: 7,
endLine: null,
severity: 'major',
title: 'State is reported as healthy',
message:
'The changed branch reports a failed runtime status as healthy.',
suggestion: null,
},
],
revalidations: [],
})
);
});
});
const provider = new CodexProvider('gpt-5.4-mini', {
agenticContext: true,
});
await expect(
provider.review(
[
'Files changed:',
'- src/app.ts (modified, +1/-1)',
'',
'Diff:',
'diff --git a/src/app.ts b/src/app.ts',
].join('\n'),
1000