Expand file tree
/
Copy pathcli.test.ts
More file actions
2257 lines (2037 loc) · 128 KB
/
Copy pathcli.test.ts
File metadata and controls
2257 lines (2037 loc) · 128 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
/**
* Unit tests for CLI commands.
* Mocks execSync (getGitInfo), runLocalAction, IssueMetadataRepository, and the fixer port.
*/
import { execSync } from 'child_process';
import { join } from 'node:path';
import { program } from '../cli';
import { logError } from '../utils/logger';
import { runLocalAction } from '../actions/local_action';
import { ACTIONS } from '../data/model/action_types';
import { INPUT_KEYS } from '../application/contracts/input_keys';
import type { SetupTokenPermissionReport, SetupTokenPermissionRequirement } from '../domain/setup_token_permissions';
import { WebSetupBridge } from '../cli/web_setup_bridge';
import { WebSetupQuestionnaireCollector } from '../cli/web_setup_adapters';
import { startWebSetupServer, openWebSetupBrowser } from '../cli/web_setup_server';
import { captureSetupApplySnapshot, setupApplySnapshotMatches } from '../cli/setup_apply_snapshot';
import { acquireSetupSessionGuard } from '../cli/setup_session_guard';
import { createSetupReviewState } from '../application/policies/setup_questionnaire_policy';
import type { WebSetupPrompt } from '../application/contracts/web_setup_view';
import { SetupDoctorWorkspaceQueryAdapter } from '../infrastructure/setup_workspace_adapter';
import { SetupSessionCoordinator, type SetupSessionPorts } from '../application/usecases/setup/setup_session_coordinator';
jest.mock('child_process', () => ({
execSync: jest.fn(),
}));
jest.mock('../actions/local_action', () => ({
runLocalAction: jest.fn().mockResolvedValue([]),
}));
// Setup serialization is exercised against temporary Git repositories in its
// dedicated adapter tests; CLI command tests mock the filesystem boundary.
jest.mock('../cli/setup_session_guard', () => ({
acquireSetupSessionGuard: jest.fn(() => jest.fn()),
}));
jest.mock('../cli/web_setup_server', () => ({
startWebSetupServer: jest.fn(async () => ({ url: 'http://127.0.0.1:40000/', pairingCode: '0123456789abcdef', closed: Promise.resolve(), close: jest.fn() })),
openWebSetupBrowser: jest.fn(),
}));
jest.mock('../cli/setup_apply_snapshot', () => ({
captureSetupApplySnapshot: jest.fn(() => ({})),
setupApplySnapshotMatches: jest.fn(() => true),
}));
jest.mock('../utils/logger', () => ({
logError: jest.fn(),
logInfo: jest.fn(),
}));
const mockIsIssue = jest.fn();
jest.mock('../data/repository/issue/issue_metadata_repository', () => ({
IssueMetadataRepository: jest.fn().mockImplementation(() => ({
isIssue: mockIsIssue,
})),
}));
const mockFix = jest.fn();
jest.mock('../infrastructure/composition/agent_capability_composition_root', () => ({
createFixerQueryPort: () => ({ fix: mockFix }),
createLanguageQueryPort: () => ({ query: jest.fn() }),
}));
const mockGetSetupToken = jest.fn();
const mockSetupEnvFileExists = jest.fn();
jest.mock('../utils/setup_files', () => {
const actual = jest.requireActual<typeof import('../utils/setup_files')>('../utils/setup_files');
return {
...actual,
getSetupToken: (...args: unknown[]) => mockGetSetupToken(...args),
setupEnvFileExists: (...args: unknown[]) => mockSetupEnvFileExists(...args),
};
});
const mockDoctorExecute = jest.fn();
const mockDoctorPresent = jest.fn();
const mockDoctorPresenter = jest.fn();
jest.mock('../infrastructure/composition/setup_doctor_composition_root', () => ({
createSetupDoctorUseCase: () => ({ execute: mockDoctorExecute }),
createSetupMergeQueueReadinessUseCase: () => ({ inspect: jest.fn().mockResolvedValue([]) }),
}));
jest.mock('../cli/setup_doctor_presenter', () => ({
SetupDoctorPresenter: jest.fn().mockImplementation((...args: unknown[]) => {
mockDoctorPresenter(...args);
return { present: mockDoctorPresent };
}),
}));
const mockTokenPermissionInspect = jest.fn(async (request: { role: 'setup' | 'workflow'; token: string; requirements: readonly SetupTokenPermissionRequirement[] }): Promise<SetupTokenPermissionReport> => ({
role: request.role,
identityStatus: 'valid' as const,
identityMessage: 'verified',
ready: true,
confirmationRequired: false,
checks: request.requirements.map(requirement => ({ ...requirement, status: 'verified', message: 'available' })),
}));
jest.mock('../infrastructure/composition/setup_token_permissions_composition_root', () => ({
createSetupTokenPermissionsUseCase: () => ({ inspect: mockTokenPermissionInspect }),
}));
const defaultRemoteConfiguration = {
ownerType: 'User',
repositoryVisibility: 'private',
repositorySecrets: [],
repositorySecretsAccess: 'available',
organizationSecrets: [],
repositoryVariables: [],
repositoryVariablesAccess: 'available',
organizationVariables: [],
organizationAccess: 'not_applicable',
organizationSecretsAccess: 'not_applicable',
organizationVariablesAccess: 'not_applicable',
};
const mockRemoteConfigurationInspect = jest.fn().mockResolvedValue(defaultRemoteConfiguration);
const mockSetupCredentialsCollect = jest.fn().mockResolvedValue({
collection: { apiKeys: [] }, checks: [], existingSecretNames: [],
});
const mockSetupCredentialsOptions = jest.fn();
jest.mock('../infrastructure/composition/setup_credentials_composition_root', () => ({
createSetupCredentialsUseCase: (_prompt: unknown, _presenter: unknown, options: unknown) => {
mockSetupCredentialsOptions(options);
return { collect: mockSetupCredentialsCollect };
},
createSetupRemoteConfigurationReadPort: () => ({
inspect: mockRemoteConfigurationInspect,
inspectCredentialHealthWorkflow: jest.fn(async () => 'installed'),
}),
}));
describe('CLI', () => {
let exitSpy: jest.SpyInstance;
let consoleErrorSpy: jest.SpyInstance;
let consoleLogSpy: jest.SpyInstance;
beforeEach(() => {
jest.clearAllMocks();
mockRemoteConfigurationInspect.mockReset().mockResolvedValue(defaultRemoteConfiguration);
mockSetupCredentialsCollect.mockResolvedValue({ collection: { apiKeys: [] }, checks: [], existingSecretNames: [] });
process.exitCode = undefined;
process.env.AGENT_PROVIDER = 'opencode';
process.env.AGENT_MODEL = 'test-model';
process.env.AGENT_EXECUTABLE = 'opencode';
process.env.AGENT_MODEL_PROVIDER = 'openai';
process.env.OPENAI_API_KEY = 'test-key';
exitSpy = jest.spyOn(process, 'exit').mockImplementation((() => {}) as () => never);
(execSync as jest.Mock).mockImplementation((command: string) => Buffer.from(
command === 'git rev-parse --is-inside-work-tree' ? 'true'
: command === 'git rev-parse --show-prefix' ? ''
: command === 'git rev-parse HEAD'
? 'a'.repeat(40)
: 'https://github.com/test-owner/test-repo.git',
));
(runLocalAction as jest.Mock).mockResolvedValue([]);
mockIsIssue.mockResolvedValue(true);
consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
// Default: return override token when present (so setup --token ... still works)
mockGetSetupToken.mockImplementation((_cwd: string, override?: string) =>
override?.trim() && override.trim().length >= 20 ? override.trim() : undefined
);
mockSetupEnvFileExists.mockReturnValue(false);
mockDoctorExecute.mockResolvedValue({
catalog: { locale: 'en-US', message: jest.fn() },
report: { healthy: true, checks: [], totals: { pass: 0, warn: 0, fail: 0, skipped: 0 } },
});
});
afterEach(() => {
process.exitCode = undefined;
exitSpy?.mockRestore();
consoleErrorSpy?.mockRestore();
consoleLogSpy?.mockRestore();
});
it('never exposes an environment token in command help', () => {
const sentinel = 'github_pat_help_output_must_not_contain_this_value';
const previousToken = process.env.PERSONAL_ACCESS_TOKEN;
process.env.PERSONAL_ACCESS_TOKEN = sentinel;
try {
const help = [program.helpInformation(), ...program.commands.map((command) => command.helpInformation())].join('\n');
expect(help).not.toContain(sentinel);
} finally {
if (previousToken === undefined) delete process.env.PERSONAL_ACCESS_TOKEN;
else process.env.PERSONAL_ACCESS_TOKEN = previousToken;
}
});
describe('think', () => {
it('calls runLocalAction with think action and question from -q', async () => {
await program.parseAsync(['node', 'cli', 'think', '-q', 'how does X work?']);
expect(runLocalAction).toHaveBeenCalledTimes(1);
const params = (runLocalAction as jest.Mock).mock.calls[0][0];
expect(params[INPUT_KEYS.SINGLE_ACTION]).toBe(ACTIONS.THINK);
expect(params).not.toHaveProperty(INPUT_KEYS.SINGLE_ACTION_ISSUE);
expect(params).not.toHaveProperty(INPUT_KEYS.WELCOME_TITLE);
expect(params.repo).toEqual({ owner: 'test-owner', repo: 'test-repo' });
expect(params).toMatchObject({
eventName: 'issue_comment',
issue: {},
comment: { body: 'how does X work?' },
});
});
it('exits with error when getGitInfo fails', async () => {
(execSync as jest.Mock).mockImplementation(() => {
throw new Error('git not found');
});
const { logError } = require('../utils/logger');
await program.parseAsync(['node', 'cli', 'think', '-q', 'hello']);
expect(logError).toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});
it('exits when getGitInfo returns non-GitHub URL', async () => {
(execSync as jest.Mock).mockReturnValue(Buffer.from('https://gitlab.com/foo/bar.git'));
const { logError } = require('../utils/logger');
await program.parseAsync(['node', 'cli', 'think', '-q', 'hello']);
expect(logError).toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});
});
describe('doctor', () => {
it('passes the read-only choice to diagnosis without dispatching health checks from the command', async () => {
await program.parseAsync(['node', 'cli', 'doctor', '--non-interactive', '--read-only', '--token', 'github_pat_doctor_test_token']);
expect(mockDoctorExecute).toHaveBeenCalledWith(expect.objectContaining({ readOnly: true }));
});
it('presents the report with its resolved catalog and returns a failing exit code when unhealthy', async () => {
const catalog = { locale: 'es-ES', message: jest.fn() };
const report = { healthy: false, checks: [], totals: { pass: 0, warn: 0, fail: 1, skipped: 0 } };
mockDoctorExecute.mockResolvedValueOnce({ catalog, report });
await program.parseAsync([
'node',
'cli',
'doctor',
'--non-interactive',
'--token',
'github_pat_doctor_test_token',
]);
expect(mockDoctorExecute).toHaveBeenCalledWith(expect.objectContaining({
owner: 'test-owner',
repository: 'test-repo',
setupToken: 'github_pat_doctor_test_token',
}));
expect(mockDoctorPresenter).toHaveBeenCalledWith(catalog);
expect(mockDoctorPresent).toHaveBeenCalledWith(report);
expect(process.exitCode).toBe(1);
});
});
describe('do', () => {
it('calls the fixer port and logs response', async () => {
const logSpy = jest.spyOn(console, 'log').mockImplementation();
mockFix.mockResolvedValue({ text: 'OK', sessionId: 's1' });
await program.parseAsync(['node', 'cli', 'do', '-p', 'refactor this']);
expect(mockFix).toHaveBeenCalled();
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('RESPONSE'));
logSpy.mockRestore();
});
it('includes repository identity and current branch in the OpenCode prompt', async () => {
mockFix.mockResolvedValue({ text: 'OK', sessionId: 's1' });
await program.parseAsync(['node', 'cli', 'do', '-p', 'refactor this']);
const prompt = mockFix.mock.calls[0][0].prompt as string;
expect(prompt).toContain('Repository identity: test-owner/test-repo');
expect(prompt).toContain('Current branch:');
});
it('calls process.exit(1) when do fails', async () => {
mockFix.mockRejectedValue(new Error('OpenCode down'));
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
await program.parseAsync(['node', 'cli', 'do', '-p', 'hello']);
expect(process.exitCode).toBe(1);
const errMsg = consoleSpy.mock.calls.flat().join(' ');
expect(errMsg).toContain('Unable to execute the request.');
expect(errMsg).not.toContain('OpenCode down');
consoleSpy.mockRestore();
});
it('exits when getGitInfo fails in do', async () => {
(execSync as jest.Mock).mockImplementation(() => {
throw new Error('git not found');
});
const { logError } = require('../utils/logger');
(runLocalAction as jest.Mock).mockClear();
await program.parseAsync(['node', 'cli', 'do', '-p', 'hello']);
expect(logError).toHaveBeenCalled();
expect(process.exitCode).toBe(1);
expect(runLocalAction).not.toHaveBeenCalled();
});
it('exits when copilotMessage returns null', async () => {
mockFix.mockResolvedValue(null);
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
await program.parseAsync(['node', 'cli', 'do', '-p', 'hello']);
expect(process.exitCode).toBe(1);
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Request failed'));
consoleSpy.mockRestore();
});
it('logs a safe correlation reference and exits with debug when do throws', async () => {
const err = new Error('OpenCode down');
mockFix.mockRejectedValue(err);
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
await program.parseAsync(['node', 'cli', 'do', '-p', 'hello', '--debug']);
expect(process.exitCode).toBe(1);
const messages = consoleSpy.mock.calls.flat().map(String);
expect(messages.some((m) => m.includes('Unable to execute the request.'))).toBe(true);
expect(messages.some((m) => m.includes('Reference:'))).toBe(true);
expect(messages).not.toContain(err.message);
consoleSpy.mockRestore();
});
});
describe('check-progress', () => {
it('calls runLocalAction with CHECK_PROGRESS and issue number', async () => {
await program.parseAsync(['node', 'cli', 'check-progress', '-i', '99']);
expect(runLocalAction).toHaveBeenCalledTimes(1);
const params = (runLocalAction as jest.Mock).mock.calls[0][0];
expect(params[INPUT_KEYS.SINGLE_ACTION]).toBe(ACTIONS.CHECK_PROGRESS);
expect(params[INPUT_KEYS.SINGLE_ACTION_ISSUE]).toBe(99);
expect(params.issue?.number).toBe(99);
expect(params.after).toBe('a'.repeat(40));
expect(params[INPUT_KEYS.WELCOME_TITLE]).toContain('Progress');
});
it('shows message when issue number is invalid', async () => {
const logSpy = jest.spyOn(console, 'log').mockImplementation();
await program.parseAsync(['node', 'cli', 'check-progress', '-i', '0']);
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Invalid issue number'));
logSpy.mockRestore();
});
it('shows message when issue number is missing', async () => {
const logSpy = jest.spyOn(console, 'log').mockImplementation();
(runLocalAction as jest.Mock).mockClear();
await program.parseAsync(['node', 'cli', 'check-progress']);
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('issue number'));
expect(runLocalAction).not.toHaveBeenCalled();
logSpy.mockRestore();
});
it('exits when getGitInfo fails in check-progress', async () => {
(execSync as jest.Mock).mockImplementation(() => {
throw new Error('git not found');
});
const { logError } = require('../utils/logger');
await program.parseAsync(['node', 'cli', 'check-progress', '-i', '1']);
expect(logError).toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});
it('passes branch in params when -b is provided', async () => {
await program.parseAsync(['node', 'cli', 'check-progress', '-i', '5', '-b', 'feature/foo']);
expect(runLocalAction).toHaveBeenCalledTimes(1);
const params = (runLocalAction as jest.Mock).mock.calls[0][0];
expect(params.commits?.ref).toBe('refs/heads/feature/foo');
});
it('fails closed before local execution when the workspace revision is unavailable', async () => {
(execSync as jest.Mock).mockImplementation((command: string) => {
if (command === 'git rev-parse HEAD') throw new Error('missing head');
return Buffer.from('https://github.com/test-owner/test-repo.git');
});
const { logError } = require('../utils/logger');
await program.parseAsync(['node', 'cli', 'check-progress', '-i', '5']);
expect(logError).toHaveBeenCalledWith('Unable to resolve the current Git revision for progress analysis.');
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});
it('omits the correlation reference outside debug mode for check-progress failures', async () => {
(runLocalAction as jest.Mock).mockRejectedValueOnce(new Error('check-progress-secret-marker'));
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
await program.parseAsync(['node', 'cli', 'check-progress', '-i', '1']);
const messages = consoleSpy.mock.calls.flat().map(String);
expect(messages).toContain('❌ Unable to check progress.');
expect(messages.some((m) => m.includes('Reference:'))).toBe(false);
expect(messages.some((m) => m.includes('check-progress-secret-marker'))).toBe(false);
consoleSpy.mockRestore();
});
it('exits when runLocalAction rejects in check-progress', async () => {
(runLocalAction as jest.Mock).mockRejectedValueOnce(new Error('check-progress-secret-marker'));
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
await program.parseAsync(['node', 'cli', 'check-progress', '-i', '1', '--debug']);
expect(process.exitCode).toBe(1);
const messages = consoleSpy.mock.calls.flat().map(String);
expect(messages.some((m) => m.includes('Unable to check progress.'))).toBe(true);
expect(messages.some((m) => m.includes('Reference:'))).toBe(true);
expect(messages.some((m) => m.includes('check-progress-secret-marker'))).toBe(false);
consoleSpy.mockRestore();
});
});
describe('recommend-steps', () => {
it('calls runLocalAction with RECOMMEND_STEPS', async () => {
await program.parseAsync(['node', 'cli', 'recommend-steps', '-i', '5']);
expect(runLocalAction).toHaveBeenCalledTimes(1);
const params = (runLocalAction as jest.Mock).mock.calls[0][0];
expect(params[INPUT_KEYS.SINGLE_ACTION]).toBe(ACTIONS.RECOMMEND_STEPS);
expect(params.issue?.number).toBe(5);
});
it('exits when getGitInfo fails', async () => {
(execSync as jest.Mock).mockImplementation(() => {
throw new Error('git not found');
});
const { logError } = require('../utils/logger');
(runLocalAction as jest.Mock).mockClear();
await program.parseAsync(['node', 'cli', 'recommend-steps', '-i', '1']);
expect(logError).toHaveBeenCalled();
expect(process.exitCode).toBe(1);
const runCalls = (runLocalAction as jest.Mock).mock.calls;
const ranWithValidRepo = runCalls.some((c) => c[0]?.repo?.owner && c[0]?.repo?.repo);
expect(ranWithValidRepo).toBe(false);
});
it('shows message when issue number is invalid', async () => {
const logSpy = jest.spyOn(console, 'log').mockImplementation();
(runLocalAction as jest.Mock).mockClear();
await program.parseAsync(['node', 'cli', 'recommend-steps', '-i', 'x']);
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('valid issue number'));
expect(runLocalAction).not.toHaveBeenCalled();
logSpy.mockRestore();
});
it('omits the correlation reference outside debug mode for recommend-steps failures', async () => {
(runLocalAction as jest.Mock).mockRejectedValueOnce(new Error('recommend-secret-marker'));
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
await program.parseAsync(['node', 'cli', 'recommend-steps', '-i', '1']);
const messages = consoleSpy.mock.calls.flat().map(String);
expect(messages).toContain('❌ Unable to recommend steps.');
expect(messages.some((m) => m.includes('Reference:'))).toBe(false);
expect(messages.some((m) => m.includes('recommend-secret-marker'))).toBe(false);
consoleSpy.mockRestore();
});
it('does not expose a raw recommend-steps failure, including in debug mode', async () => {
(runLocalAction as jest.Mock).mockRejectedValueOnce(new Error('recommend-secret-marker'));
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
await program.parseAsync(['node', 'cli', 'recommend-steps', '-i', '1', '--debug']);
expect(process.exitCode).toBe(1);
const messages = consoleSpy.mock.calls.flat().map(String);
expect(messages.some((m) => m.includes('Unable to recommend steps.'))).toBe(true);
expect(messages.some((m) => m.includes('Reference:'))).toBe(true);
expect(messages.some((m) => m.includes('recommend-secret-marker'))).toBe(false);
consoleSpy.mockRestore();
});
});
describe('setup', () => {
// Token check: hasValidSetupToken/setupEnvFileExists and message variants are covered in
// setup_files.test.ts and initial_setup_use_case.test.ts.
beforeEach(() => {
const setupCommand = program.commands.find(command => command.name() === 'setup')!;
for (const option of setupCommand.options) {
setupCommand.setOptionValue(option.attributeName(), option.defaultValue);
}
(runLocalAction as jest.Mock).mockResolvedValue([{ id: 'InitialSetupUseCase', success: true, executed: true, errors: [] }]);
});
describe('local web command handoff', () => {
let ask: jest.SpyInstance;
let collect: jest.SpyInstance;
const webView = () => ((startWebSetupServer as jest.Mock).mock.calls[0][0] as WebSetupBridge).snapshot();
const answerWebPrompt = async (prompt: WebSetupPrompt): Promise<string> => {
if (prompt.kind === 'management') return 'wizard';
if (prompt.title === 'Confirm this repository') return 'Yes, this is my repository';
if (prompt.copyId === 'setup.scope') return 'This repository';
if (prompt.copyId === 'setup.source') return 'Customize configuration';
if (prompt.title === 'Choose setup detail') return 'Basic guided setup';
if (prompt.title === 'How will you provide your setup PAT?') return 'Manual PAT';
if (prompt.title === 'Temporary setup PAT') return 'github_pat_web_setup_test_token';
if (prompt.kind === 'plan') return 'approve';
if (prompt.title === 'Apply this setup now?') return 'Apply setup';
if (prompt.title === 'Update existing workflows?') return 'Keep existing';
throw new Error(`Unexpected browser prompt: ${prompt.title}`);
};
beforeEach(() => {
(setupApplySnapshotMatches as jest.Mock).mockReturnValue(true);
(execSync as jest.Mock).mockImplementation((command: string) => Buffer.from(
command === 'git rev-parse --is-inside-work-tree' ? 'true'
: command === 'git rev-parse --show-prefix' ? ''
: command === 'git rev-parse HEAD' ? 'a'.repeat(40)
: command === 'git rev-parse --show-toplevel' ? process.cwd()
: command === 'git rev-parse --abbrev-ref HEAD' || command === 'git symbolic-ref --quiet --short HEAD' ? 'develop'
: 'https://github.com/test-owner/test-repo.git',
));
ask = jest.spyOn(WebSetupBridge.prototype, 'ask').mockImplementation(answerWebPrompt);
collect = jest.spyOn(WebSetupQuestionnaireCollector.prototype, 'collect')
.mockImplementation(async initial => createSetupReviewState(initial.draft));
});
afterEach(() => { ask.mockRestore(); collect.mockRestore(); });
it('uses one browser session through PAT, plan, revalidation, and Apply', async () => {
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(startWebSetupServer).toHaveBeenCalledTimes(1);
expect(openWebSetupBrowser).toHaveBeenCalledWith('http://127.0.0.1:40000/');
const { logInfo } = require('../utils/logger');
expect(logInfo).toHaveBeenCalledWith(expect.stringContaining('0123456789abcdef'), false, undefined, true);
expect(ask.mock.calls.map(call => call[0].title)).toEqual(expect.arrayContaining([
'Confirm this repository', 'How will you provide your setup PAT?', 'Temporary setup PAT',
'Review your setup plan', 'Apply this setup now?',
]));
expect(mockTokenPermissionInspect).toHaveBeenCalledTimes(4);
expect(captureSetupApplySnapshot).toHaveBeenCalledTimes(1);
expect(setupApplySnapshotMatches).toHaveBeenCalledTimes(2);
expect(runLocalAction).toHaveBeenCalledTimes(1);
expect(process.exitCode).toBeUndefined();
expect(webView().journey?.outcome).toBe('complete');
expect(webView().outcome).toBe('complete');
const bridge = (startWebSetupServer as jest.Mock).mock.calls[0][0] as WebSetupBridge;
expect(await bridge.runReadOnlyDoctor()).toBe('complete');
expect(mockDoctorExecute).toHaveBeenCalledWith(expect.objectContaining({
owner: 'test-owner', repository: 'test-repo', setupToken: 'github_pat_web_setup_test_token', readOnly: true,
}));
expect(bridge.snapshot().doctor).toEqual({ status: 'complete', healthy: true, pass: 0, warn: 0, fail: 0, skipped: 0 });
});
it('keeps organization-reuse write audits behind the browser Apply confirmation', async () => {
const original = mockTokenPermissionInspect.getMockImplementation()!;
mockRemoteConfigurationInspect.mockResolvedValue({ ...defaultRemoteConfiguration, ownerType: 'Organization',
repositoryId: 42, defaultBranch: 'master', organizationAccess: 'available',
organizationSecretsAccess: 'available', organizationVariablesAccess: 'available' });
ask.mockImplementation(async (prompt: WebSetupPrompt) => prompt.copyId === 'setup.source'
? 'Reuse organization configuration' : answerWebPrompt(prompt));
mockTokenPermissionInspect.mockImplementation(async request => {
if (request.requirements.some(requirement => requirement.level === 'write')) {
expect(ask.mock.calls.some(([prompt]) => prompt.title === 'Apply this setup now?')).toBe(true);
}
return original(request);
});
try {
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets', '--skip-variables']);
expect(mockTokenPermissionInspect).toHaveBeenCalledTimes(2);
expect(runLocalAction).toHaveBeenCalledTimes(1); expect(process.exitCode).toBeUndefined();
} finally { mockTokenPermissionInspect.mockReset().mockImplementation(original); }
});
it('retains a management mutation receipt and stops before the full installer after an uncertain quick write', async () => {
const management = require('../cli/setup_management_adapter') as typeof import('../cli/setup_management_adapter');
const manage = jest.spyOn(management, 'manageWebSetup').mockImplementation(async (bridge, _root, _owner, _repository, possibleMutation, record) => {
bridge.setSurface('management'); possibleMutation();
const effect = { id:'variables' as const,state:'needs-inspection' as const,scope:'organization' as const };
record(effect); bridge.progress(effect);
bridge.resultReason('provider');
return 'partial';
});
try {
await program.parseAsync(['node','cli','setup','--web']);
expect(webView().outcome).toBe('partial');
expect(webView().journey).toMatchObject({outcome:'partial',mutationStarted:true});
expect(webView().resultDetail).toMatchObject({reasonCode:'provider',effects:[{id:'variables',state:'needs-inspection',scope:'organization'}]});
expect(runLocalAction).not.toHaveBeenCalled(); expect(process.exitCode).toBe(1);
expect(mockTokenPermissionInspect).not.toHaveBeenCalled();
} finally { manage.mockRestore(); }
});
it.each([false,true])('reports a management exception conservatively after prior mutation=%s', async changed => {
const management=require('../cli/setup_management_adapter') as typeof import('../cli/setup_management_adapter');
const manage=jest.spyOn(management,'manageWebSetup').mockImplementation(async (bridge,_root,_owner,_repository,possibleMutation) => {
bridge.setSurface('management'); if (changed) possibleMutation(); throw new Error('private-provider-detail');
});
try {
await program.parseAsync(['node','cli','setup','--web']);
expect(webView().outcome).toBe(changed ? 'partial' : 'blocked');
expect(JSON.stringify(webView())).not.toContain('private-provider-detail');
expect(runLocalAction).not.toHaveBeenCalled(); expect(process.exitCode).toBe(1);
} finally { manage.mockRestore(); }
});
it('finishes a configuration inspection successfully without certifying an installation', async () => {
ask.mockImplementation(async prompt => prompt.kind === 'management' ? 'close' : answerWebPrompt(prompt));
await program.parseAsync(['node','cli','setup','--web']);
expect(webView()).toMatchObject({surface:'management',outcome:'complete',journey:{outcome:'complete',mutationStarted:false}});
expect(runLocalAction).not.toHaveBeenCalled(); expect(mockTokenPermissionInspect).not.toHaveBeenCalled();
expect(process.exitCode).toBeUndefined();
});
it.each(['apply','cancel'] as const)('keeps prior quick changes while a fresh complete assistant proceeds to %s', async decision => {
const management = require('../cli/setup_management_adapter') as typeof import('../cli/setup_management_adapter');
const manage = jest.spyOn(management,'manageWebSetup').mockImplementation(async (bridge,_root,_owner,_repository,possibleMutation,record) => {
bridge.setSurface('management'); possibleMutation();
const effect={id:'variables' as const,state:'completed' as const,scope:'organization' as const}; record(effect); bridge.progress(effect);
bridge.setSurface('wizard'); return 'continue';
});
if (decision === 'cancel') ask.mockImplementation(async prompt => prompt.title === 'Choose setup detail' ? undefined : answerWebPrompt(prompt));
try {
await program.parseAsync(['node','cli','setup','--web','--pr-approval-mode','off','--skip-secrets']);
expect(webView().outcome).toBe(decision === 'apply' ? 'complete' : 'partial');
expect(webView().journey?.mutationStarted).toBe(true);
expect(runLocalAction).toHaveBeenCalledTimes(decision === 'apply' ? 1 : 0);
expect(process.exitCode).toBe(decision === 'apply' ? undefined : 130);
} finally { manage.mockRestore(); }
});
it('prints the pairing code to stdout even without an interactive TTY', async () => {
const descriptor = Object.getOwnPropertyDescriptor(process.stdout, 'isTTY');
Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: false });
try {
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
const { logInfo } = require('../utils/logger');
expect(logInfo).toHaveBeenCalledWith(expect.stringContaining('0123456789abcdef'), false, undefined, true);
expect(startWebSetupServer).toHaveBeenCalledTimes(1);
} finally {
if (descriptor) Object.defineProperty(process.stdout, 'isTTY', descriptor);
else Reflect.deleteProperty(process.stdout, 'isTTY');
}
});
it('stops before acquiring a PAT when repository confirmation is declined', async () => {
ask.mockResolvedValueOnce('Stop and choose another checkout');
await program.parseAsync(['node', 'cli', 'setup', '--web']);
expect(mockTokenPermissionInspect).not.toHaveBeenCalled();
expect(runLocalAction).not.toHaveBeenCalled();
expect(webView().journey?.outcome).toBe('cancelled');
expect(webView().outcome).toBe('cancelled');
});
it('treats a dismissed repository confirmation as cancellation', async () => {
ask.mockResolvedValueOnce(undefined);
await program.parseAsync(['node', 'cli', 'setup', '--web']);
expect(mockTokenPermissionInspect).not.toHaveBeenCalled();
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(130);
});
it('rejects detached HEAD before opening the browser or collecting a PAT', async () => {
(execSync as jest.Mock).mockImplementation((command: string) => {
if (command === 'git symbolic-ref --quiet --short HEAD') throw new Error('detached HEAD');
return Buffer.from(command === 'git rev-parse --is-inside-work-tree' ? 'true'
: command === 'git rev-parse --show-prefix' ? ''
: command === 'git rev-parse HEAD' ? 'a'.repeat(40)
: command === 'git rev-parse --show-toplevel' ? process.cwd()
: 'https://github.com/test-owner/test-repo.git');
});
await program.parseAsync(['node', 'cli', 'setup', '--web']);
expect(startWebSetupServer).not.toHaveBeenCalled();
expect(openWebSetupBrowser).not.toHaveBeenCalled();
expect(ask).not.toHaveBeenCalled();
expect(mockTokenPermissionInspect).not.toHaveBeenCalled();
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
const { logError } = require('../utils/logger');
expect(logError).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringContaining('Check out a branch') }));
});
it('rejects web setup from a subdirectory before opening the browser or collecting a PAT', async () => {
const root = process.cwd();
const nested = join(root, 'src');
const cwd = jest.spyOn(process, 'cwd').mockReturnValue(nested);
(execSync as jest.Mock).mockImplementation((command: string) => Buffer.from(
command === 'git rev-parse --show-toplevel' ? root
: command === 'git config --get remote.origin.url' ? 'https://github.com/test-owner/test-repo.git'
: 'true',
));
try {
await program.parseAsync(['node', 'cli', 'setup', '--web']);
expect(startWebSetupServer).not.toHaveBeenCalled();
expect(acquireSetupSessionGuard).not.toHaveBeenCalled();
expect(mockTokenPermissionInspect).not.toHaveBeenCalled();
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
const { logError } = require('../utils/logger');
expect(logError).toHaveBeenCalledWith(expect.objectContaining({
message: expect.stringContaining(`repository root (${root})`),
}));
} finally { cwd.mockRestore(); }
});
it('reports a blocked browser session if launch fails before the journey starts', async () => {
(openWebSetupBrowser as jest.Mock).mockImplementationOnce(() => { throw new Error('Browser launch failed'); });
const finish = jest.spyOn(WebSetupBridge.prototype, 'finish');
try {
await program.parseAsync(['node', 'cli', 'setup', '--web']);
expect(finish).toHaveBeenCalledWith('blocked', expect.stringContaining('No further setup changes'));
expect(mockTokenPermissionInspect).not.toHaveBeenCalled();
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
} finally { finish.mockRestore(); }
});
it.each([
[undefined, 130],
['decline', undefined],
] as const)('honors a %s browser plan decision before credentials or Apply', async (answer, exitCode) => {
ask.mockImplementation(async (prompt: WebSetupPrompt) => prompt.kind === 'plan'
? answer : answerWebPrompt(prompt));
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(exitCode);
expect(ask.mock.calls.map(call => call[0].title)).not.toContain('Apply this setup now?');
});
it('guides setup PAT review and confirms the audited operator account before planning', async () => {
ask.mockImplementation(async (prompt: WebSetupPrompt) => {
if (prompt.title === 'How will you provide your setup PAT?') return 'Guided GitHub link';
if (prompt.title === 'What kind of GitHub account owns this repository?') return 'Personal account';
if (prompt.title === 'Review these provisional setup PAT grants') return 'Continue to GitHub';
if (prompt.title.includes('Is that the intended operator account?')) return 'Yes, continue';
return answerWebPrompt(prompt);
});
mockTokenPermissionInspect.mockResolvedValueOnce({
role: 'setup', account: 'operator', identityStatus: 'valid', identityMessage: 'verified',
ready: true, confirmationRequired: false, checks: [],
});
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(ask.mock.calls.map(call => call[0].title)).toEqual(expect.arrayContaining([
'Review these provisional setup PAT grants',
expect.stringContaining('Is that the intended operator account?'),
]));
expect(runLocalAction).toHaveBeenCalledTimes(1);
});
it('warns when the final guided plan no longer needs earlier PAT grants', async () => {
ask.mockImplementation(async (prompt: WebSetupPrompt) => {
if (prompt.title === 'How will you provide your setup PAT?') return 'Guided GitHub link';
if (prompt.title === 'What kind of GitHub account owns this repository?') return 'Personal account';
if (prompt.title === 'Review these provisional setup PAT grants') return 'Continue to GitHub';
if (prompt.title.includes('Is that the intended operator account?')) return 'Yes, continue';
return answerWebPrompt(prompt);
});
collect.mockImplementationOnce(async initial => createSetupReviewState(initial.draft))
.mockImplementationOnce(async initial => createSetupReviewState({
...initial.draft, manageRepositoryVariables: false,
}));
mockTokenPermissionInspect.mockResolvedValueOnce({
role: 'setup', account: 'operator', identityStatus: 'valid', identityMessage: 'verified',
ready: true, confirmationRequired: false, checks: [],
});
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
const { logInfo } = require('../utils/logger');
expect(logInfo).toHaveBeenCalledWith(expect.stringContaining('Your PAT may have excess access'));
});
it('keeps web dry-run local and never asks for either PAT or Apply', async () => {
await program.parseAsync(['node', 'cli', 'setup', '--web', '--dry-run', '--pr-approval-mode', 'off']);
expect(ask.mock.calls.map(call => call[0].title)).not.toContain('Temporary setup PAT');
expect(ask.mock.calls.map(call => call[0].title)).not.toContain('Apply this setup now?');
expect(mockTokenPermissionInspect).not.toHaveBeenCalled();
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBeUndefined();
expect(webView().journey?.outcome).toBe('dry-run');
expect(webView().outcome).toBe('dry-run');
});
it('requires explicit selection before using an environment PAT', async () => {
mockGetSetupToken.mockReturnValueOnce('github_pat_from_environment_test');
ask.mockImplementation(async (prompt: WebSetupPrompt) => prompt.title === 'An environment setup PAT is available'
? 'Use the environment PAT' : answerWebPrompt(prompt));
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(ask.mock.calls.map(call => call[0].title)).toContain('An environment setup PAT is available');
expect(ask.mock.calls.map(call => call[0].title)).not.toContain('Temporary setup PAT');
expect(mockTokenPermissionInspect.mock.calls[0][0].token).toBe('github_pat_from_environment_test');
expect(runLocalAction).toHaveBeenCalledTimes(1);
});
it('discards an environment PAT when the operator chooses a different one', async () => {
mockGetSetupToken.mockReturnValueOnce('github_pat_from_environment_test');
ask.mockImplementation(async (prompt: WebSetupPrompt) => prompt.title === 'An environment setup PAT is available'
? 'Create or enter a different PAT' : answerWebPrompt(prompt));
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(ask.mock.calls.map(call => call[0].title)).toContain('Temporary setup PAT');
expect(mockTokenPermissionInspect.mock.calls[0][0].token).toBe('github_pat_web_setup_test_token');
expect(runLocalAction).toHaveBeenCalledTimes(1);
});
it('does not use an environment PAT when the browser choice is cancelled', async () => {
mockGetSetupToken.mockReturnValueOnce('github_pat_from_environment_test');
ask.mockImplementation(async (prompt: WebSetupPrompt) => prompt.title === 'An environment setup PAT is available'
? undefined : answerWebPrompt(prompt));
await program.parseAsync(['node', 'cli', 'setup', '--web']);
expect(mockTokenPermissionInspect).not.toHaveBeenCalled();
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(130);
});
it('blocks final Apply if GitHub facts changed after the reviewed plan', async () => {
mockRemoteConfigurationInspect.mockResolvedValueOnce(defaultRemoteConfiguration)
.mockResolvedValueOnce({ ...defaultRemoteConfiguration, repositoryVisibility: 'public' });
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
expect(webView().journey?.outcome).toBe('blocked');
expect(webView().outcome).toBe('blocked');
});
it('does not enter the mutation boundary when final Apply is declined', async () => {
ask.mockImplementation(async (prompt: WebSetupPrompt) => prompt.title === 'Apply this setup now?'
? 'Stop without applying' : answerWebPrompt(prompt));
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBeUndefined();
});
it('treats a dismissed final Apply prompt as cancellation', async () => {
ask.mockImplementation(async (prompt: WebSetupPrompt) => prompt.title === 'Apply this setup now?'
? undefined : answerWebPrompt(prompt));
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(130);
});
it.each(['cancelled', 'expired'] as const)('does not Apply after the browser session is %s', async state => {
ask.mockImplementation(async function (this: WebSetupBridge, prompt: WebSetupPrompt) {
if (prompt.title === 'Apply this setup now?') {
if (state === 'cancelled') this.cancel();
else this.finish('blocked', 'The local session expired.');
return 'Apply setup';
}
return answerWebPrompt(prompt);
});
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(state === 'cancelled' ? 130 : 1);
});
it('reports partial completion when an approved action fails', async () => {
(runLocalAction as jest.Mock).mockResolvedValueOnce([{ success: false, errors: ['provider failed'] }]);
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(runLocalAction).toHaveBeenCalledTimes(1);
expect(process.exitCode).toBe(1);
expect(webView().journey?.outcome).toBe('partial');
expect(webView().outcome).toBe('partial');
const { logInfo } = require('../utils/logger');
expect(logInfo).toHaveBeenCalledWith(expect.stringContaining('partial completion'));
});
it('does not call an empty mutation result complete', async () => {
(runLocalAction as jest.Mock).mockResolvedValueOnce([]);
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(process.exitCode).toBe(1);
});
it('passes only explicitly approved changed workflows to the mutation boundary', async () => {
const comparison = jest.spyOn(SetupDoctorWorkspaceQueryAdapter.prototype, 'compareWorkflows')
.mockReturnValue([
{ file: 'copilot_issue.yml', destination: '.github/workflows/copilot_issue.yml', status: 'changed' },
{ file: 'unmanaged.yml', destination: '.github/workflows/unmanaged.yml', status: 'unmanaged' },
]);
ask.mockImplementation(async (prompt: WebSetupPrompt) => prompt.title === 'Update existing workflows?'
? 'Update setup-managed workflows' : answerWebPrompt(prompt));
try {
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(runLocalAction).toHaveBeenCalledWith(expect.objectContaining({ setupWorkflowUpdates: ['copilot_issue.yml'] }),
expect.objectContaining({ onSetupProgress: expect.any(Function) }));
} finally { comparison.mockRestore(); }
});
it('refuses to launch a browser session without a verified HEAD', async () => {
(execSync as jest.Mock).mockImplementation((command: string) => {
if (command === 'git rev-parse HEAD') throw new Error('missing HEAD');
return Buffer.from(command === 'git rev-parse --show-toplevel' ? process.cwd()
: 'https://github.com/test-owner/test-repo.git');
});
await program.parseAsync(['node', 'cli', 'setup', '--web']);
expect(startWebSetupServer).not.toHaveBeenCalled();
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});
it('fails closed when selected files drift after browser plan approval', async () => {
(setupApplySnapshotMatches as jest.Mock).mockReturnValue(false);
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});
it('fails closed when the approved file snapshot is unavailable', async () => {
(captureSetupApplySnapshot as jest.Mock).mockReturnValueOnce(undefined);
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
const { logError } = require('../utils/logger');
expect(logError).toHaveBeenCalledWith(expect.objectContaining({
message: expect.stringContaining('approved setup evidence is incomplete'),
}));
});
it('fails closed when the GitHub remote becomes unresolvable just before Apply', async () => {
let remoteReads = 0;
(execSync as jest.Mock).mockImplementation((command: string) => Buffer.from(
command === 'git rev-parse --is-inside-work-tree' ? 'true'
: command === 'git rev-parse --show-prefix' ? ''
: command === 'git rev-parse HEAD' ? 'a'.repeat(40)
: command === 'git rev-parse --show-toplevel' ? process.cwd()
: command === 'git symbolic-ref --quiet --short HEAD' ? 'develop'
: command === 'git config --get remote.origin.url' && ++remoteReads > 1
? 'not-a-github-remote' : 'https://github.com/test-owner/test-repo.git',
));
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(remoteReads).toBeGreaterThan(1);
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});
it('fails closed when the attached branch disappears just before Apply', async () => {
let branchReads = 0;
(execSync as jest.Mock).mockImplementation((command: string) => {
if (command === 'git symbolic-ref --quiet --short HEAD' && ++branchReads > 1) throw new Error('detached HEAD');
return Buffer.from(command === 'git rev-parse --is-inside-work-tree' ? 'true'
: command === 'git rev-parse --show-prefix' ? ''
: command === 'git rev-parse HEAD' ? 'a'.repeat(40)
: command === 'git rev-parse --show-toplevel' ? process.cwd()
: command === 'git symbolic-ref --quiet --short HEAD' ? 'develop'
: 'https://github.com/test-owner/test-repo.git');
});
await program.parseAsync(['node', 'cli', 'setup', '--web', '--pr-approval-mode', 'off', '--skip-secrets']);
expect(branchReads).toBeGreaterThan(1);
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});
it('rejects unattended CLI approval flags in web mode', async () => {
await program.parseAsync(['node', 'cli', 'setup', '--web', '--yes']);
expect(startWebSetupServer).not.toHaveBeenCalled();
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});
it.each([
['--non-interactive'],
['--token', 'github_pat_operator_test_token'],
['--workflow-pat', 'github_pat_bot_test_token'],
['--secret', 'PAT=github_pat_bot_test_token'],
['--confirm-unverifiable-write-permissions'],
])('rejects incompatible web option %s before opening the browser', async (...flags) => {
await program.parseAsync(['node', 'cli', 'setup', '--web', ...flags]);
expect(startWebSetupServer).not.toHaveBeenCalled();
expect(runLocalAction).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});
});
const guidedTerminal = (answer?: (prompt: string) => string | undefined) => ({
isInteractive: () => true,
readText: jest.fn(async (prompt: string) => ({ kind: 'value' as const, value: answer?.(prompt)
?? (prompt.includes('repository owner an organization') ? '2'
: prompt.includes('Review these intended grants') ? '1' : '') })),
readSecret: jest.fn().mockResolvedValue({ kind: 'value', value: 'github_pat_guided_setup_test_token' }),
close: jest.fn(),
});
const acceptedSetupPatReport = () => ({
role: 'setup' as const, identityStatus: 'valid' as const, identityMessage: 'verified',
account: 'operator', ready: true, confirmationRequired: false, checks: [],
});
it.each(['--non-interactive', '--dry-run', '--yes'])('rejects a batch review bypass flag before PAT auditing: %s', async flag => {
await program.parseAsync(['node', 'cli', 'setup', '--batch', flag, ...(flag === '--non-interactive' ? ['--yes'] : []), '--token', 'github_pat_fixture_operator_token']);
expect(process.exitCode).toBe(1); expect(mockTokenPermissionInspect).not.toHaveBeenCalled(); expect(runLocalAction).not.toHaveBeenCalled();
expect(logError).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringContaining('--batch requires interactive review') }));
});