Repository navigation
Expand file tree
/
Copy pathvalidate_workflow_contract.test.ts
More file actions
1852 lines (1688 loc) · 109 KB
/
Copy pathvalidate_workflow_contract.test.ts
File metadata and controls
1852 lines (1688 loc) · 109 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 path from 'node:path';
import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
import { tmpdir } from 'node:os';
import { runInNewContext } from 'node:vm';
import * as yaml from 'js-yaml';
import { WORKFLOW_QUEUE_POLICY } from '../../application/policies/workflow_queue_policy';
import { selectedSetupRunsOn } from '../../application/policies/setup_runner_policy';
const CRLF_WHITESPACE = 'core.whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol';
interface ContractModule {
issueAdmissionConfigurationExpression(workflow: Record<string, unknown>): string;
assertQueueWorkflow(file: string, workflow: Record<string, unknown>): void;
assertDirectEventTriggers(file: string, workflow: Record<string, unknown>): void;
assertRunner(file: string, workflow: Record<string, unknown>): void;
assertPortableRunShell(file: string, workflow: Record<string, unknown>): void;
assertMajorActionReferences(file: string, workflow: Record<string, unknown>): void;
assertCopilotActionInputs(file: string, workflow: Record<string, unknown>): void;
assertNoJobLevelSecrets(file: string, workflow: Record<string, unknown>): void;
assertAgentWorkflowPermissions(file: string, workflow: Record<string, unknown>): void;
assertAgentInstallationPrerequisites(file: string, workflow: Record<string, unknown>): void;
assertRepositoryLocaleInputs(file: string, workflow: Record<string, unknown>): void;
assertRepositoryBugbotContextExclusions(file: string, workflow: Record<string, unknown>): void;
assertIssueBranchConfigurationInputs(file: string, workflow: Record<string, unknown>): void;
assertLightweightBranchSyncWorkflow(file: string, workflow: Record<string, unknown>): void;
MIN_QUEUE_JOB_TIMEOUT_MINUTES: number;
DEPLOYMENT_VALIDATION_TIMEOUT_MINUTES: number;
PREPARE_VERSION_TIMEOUT_MINUTES: number;
PREPARE_COMPILED_TIMEOUT_MINUTES: number;
TAG_TIMEOUT_MINUTES: number;
NPM_PUBLISH_TIMEOUT_MINUTES: number;
FINALIZE_RELEASE_TIMEOUT_MINUTES: number;
QUEUE_WAIT_MINUTES: number;
QUEUE_WORKFLOW_MANIFEST: readonly { file: string; workflowName: string; jobId: string }[];
assertQueueBudget(queueWaitMinutes: number, minimumJobTimeoutMinutes: number): void;
validateWorkflow(file: string, workflow: Record<string, unknown>): void;
}
const {
issueAdmissionConfigurationExpression,
assertQueueWorkflow,
assertDirectEventTriggers,
assertRunner,
assertPortableRunShell,
assertMajorActionReferences,
assertCopilotActionInputs,
assertNoJobLevelSecrets,
assertAgentWorkflowPermissions,
assertAgentInstallationPrerequisites,
assertRepositoryLocaleInputs,
assertRepositoryBugbotContextExclusions,
assertIssueBranchConfigurationInputs,
assertLightweightBranchSyncWorkflow,
MIN_QUEUE_JOB_TIMEOUT_MINUTES,
DEPLOYMENT_VALIDATION_TIMEOUT_MINUTES,
PREPARE_VERSION_TIMEOUT_MINUTES,
PREPARE_COMPILED_TIMEOUT_MINUTES,
TAG_TIMEOUT_MINUTES,
NPM_PUBLISH_TIMEOUT_MINUTES,
FINALIZE_RELEASE_TIMEOUT_MINUTES,
QUEUE_WAIT_MINUTES,
QUEUE_WORKFLOW_MANIFEST,
assertQueueBudget,
validateWorkflow,
} = require('../../../scripts/validate-workflow-contract.cjs') as ContractModule;
const queueFile = path.join(process.cwd(), '.github', 'workflows', 'copilot_issue.yml');
const mutationDirectories = ['.github/workflows', 'setup/workflows'] as const;
const mutationWorkflowNames = ['release_workflow.yml', 'hotfix_workflow.yml'] as const;
type MutationWorkflow = { jobs: Record<string, Record<string, any>>; [key: string]: any };
type RegistryVisibilityCase = {
name: string; timeout: string; interval: string; visibleAt: number; success: boolean; elapsed: number;
slowAt?: number; lookupDuration?: number; ignoreLookupTimeout?: boolean;
};
function loadMutationWorkflow(directory: string, fileName: string): { file: string; workflow: MutationWorkflow } {
const file = path.join(process.cwd(), directory, fileName);
return {
file,
workflow: JSON.parse(JSON.stringify(yaml.load(readFileSync(file, 'utf8')))),
};
}
function expectMutationRejected(
directory: string,
fileName: string,
mutate: (workflow: MutationWorkflow) => void,
expectedMessage: string,
): void {
const { file, workflow } = loadMutationWorkflow(directory, fileName);
mutate(workflow);
expect(() => validateWorkflow(file, workflow)).toThrow(expectedMessage);
}
const validWorkflow = yaml.load(readFileSync(queueFile, 'utf8')) as MutationWorkflow;
describe('workflow contract validator', () => {
it.each(['.github/workflows', 'setup/workflows'].flatMap(directory =>
['copilot_commit.yml', 'copilot_branch_sync.yml'].flatMap(name =>
['remove', 'shadow'].map(mutation => [directory, name, mutation]))))(
'rejects %s/%s when permission-probe exclusion is %s', (directory, name, mutation) => {
const { file, workflow } = loadMutationWorkflow(directory, name);
if (mutation === 'remove') workflow.on.push.branches = workflow.on.push.branches
.filter((branch: string) => branch !== '!copilot-permission-test-*');
else workflow.on.push.branches.push('**');
expect(() => validateWorkflow(file, workflow)).toThrow(/permission-probe/);
},
);
it.each(['.github/workflows', 'setup/workflows'].flatMap(directory =>
['copilot_commit.yml', 'copilot_branch_sync.yml'].map(name => [directory, name])))(
'excludes probe refs and preserves ordinary push admission in %s/%s', (directory, name) => {
const { file, workflow } = loadMutationWorkflow(directory, name);
expect(() => validateWorkflow(file, workflow)).not.toThrow();
const admitted = (ref: string) => (workflow.on.push.branches as string[]).reduce((accept, pattern) => {
const excluded = pattern.startsWith('!');
return path.posix.matchesGlob(ref, excluded ? pattern.slice(1) : pattern) ? !excluded : accept;
}, false);
expect(admitted(`copilot-permission-test-${'a'.repeat(32)}`)).toBe(false);
expect(admitted(`copilot-permission-test-${'0123456789abcdef'.repeat(2)}`)).toBe(false);
for (const ref of ['feature/42-change', 'bugfix/570-runner', 'release/3.5.7', 'hotfix/urgent',
'feature/copilot-permission-test-example', 'copilot-permission-testing']) expect(admitted(ref)).toBe(true);
for (const ref of ['master', 'develop', 'setup/copilot/reviewed-operation']) {
expect(admitted(ref)).toBe(name === 'copilot_branch_sync.yml');
}
},
);
it.each(['.github/workflows', 'setup/workflows'])('excludes issue-less installer pushes from Commit in %s', directory => {
const { file, workflow } = loadMutationWorkflow(directory, 'copilot_commit.yml');
expect(() => validateWorkflow(file, workflow)).not.toThrow();
workflow.on.push.branches = workflow.on.push.branches.filter((branch: string) => branch !== '!setup/copilot/**');
expect(() => validateWorkflow(file, workflow)).toThrow('exclude installer-owned setup/copilot branches');
});
it('keeps branch and SDD configuration consistent across issue, PR, review and push callbacks', () => {
for (const directory of ['.github/workflows', 'setup/workflows']) {
for (const fileName of ['copilot_issue.yml', 'copilot_issue_comment.yml', 'copilot_commit.yml',
'copilot_pull_request.yml', 'copilot_pull_request_review_state.yml', 'copilot_pull_request_comment.yml']) {
const { file, workflow } = loadMutationWorkflow(directory, fileName);
expect(() => assertIssueBranchConfigurationInputs(file, workflow)).not.toThrow();
}
}
});
it('seeds trusted fixer build tools while requiring separate candidate readiness', () => {
const {file, workflow} = loadMutationWorkflow('.github/workflows', 'copilot_comment_runtime.yml');
const steps = workflow.jobs.copilot.steps;
const seed = steps.find((step: {name?:string}) => step.name === 'Seed trusted source build tools');
expect(seed?.run).toBe('pnpm install --frozen-lockfile --ignore-scripts --ignore-pnpmfile --config.manage-package-manager-versions=false --prod=false');
expect(seed?.if).toBe("env.COPILOT_PREPARE_VERIFICATION == 'true'");
expect(steps.indexOf(seed)).toBeLessThan(steps.findIndex((step: {id?:string}) => step.id === 'copilot'));
expect(steps.find((step: {name?:string}) => step.name === 'Prepare repository pnpm')?.if).toBe("env.COPILOT_PREPARE_VERIFICATION == 'true'");
expect(() => validateWorkflow(file, workflow)).not.toThrow();
steps.splice(3,0,{name:'Install repository verification dependencies',if:"env.COPILOT_PREPARE_VERIFICATION == 'true'",run:'pnpm install --frozen-lockfile --ignore-scripts',shell:'bash'});
expect(() => validateWorkflow(file, workflow)).toThrow();
});
it.each(['issue-managed-branches', 'pre-branch-sdd', 'verification-setup'])(
'rejects a comment coordinator that omits or disables the installed %s policy', input => {
const { file, workflow } = loadMutationWorkflow('.github/workflows', 'copilot_comment_runtime.yml');
const action = workflow.jobs.copilot.steps.find((step: { id?: string }) => step.id === 'copilot');
delete action.with[input];
expect(() => validateWorkflow(file, workflow)).toThrow('native comment runtime');
action.with[input] = false;
expect(() => validateWorkflow(file, workflow)).toThrow('native comment runtime');
},
);
it('rejects a distributed callback that enables the SDD gate instead of inheriting its configured default', () => {
const { file, workflow } = loadMutationWorkflow('setup/workflows', 'copilot_pull_request_comment.yml');
const action = workflow.jobs['copilot-pull-requests'];
action.with['pre-branch-sdd'] = "${{ vars.PRE_BRANCH_SDD || 'true' }}";
expect(() => assertIssueBranchConfigurationInputs(file, workflow)).toThrow('must pass consistent');
});
it('rejects installed and generated PR workflows that omit the draft-to-ready event', () => {
for (const directory of ['.github/workflows', 'setup/workflows']) {
const file = path.join(process.cwd(), directory, 'copilot_pull_request.yml');
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
expect(() => assertDirectEventTriggers(file, workflow)).not.toThrow();
workflow.on.pull_request.types = workflow.on.pull_request.types.filter((type: string) => type !== 'ready_for_review');
expect(() => assertDirectEventTriggers(file, workflow)).toThrow('must handle code/lifecycle PR events');
}
});
it.each(['.github/workflows', 'setup/workflows'])(
'keeps the Codex model fallback and exact allowlist synchronized in %s',
directory => {
const modelFallback = "${{ vars.AGENT_MODEL || 'gpt-6-luna' }}";
const allowedFallback = "${{ vars.AGENT_ALLOWED_MODELS || 'openai/gpt-6-luna' }}";
for (const fileName of [
'copilot_close_inactive_issues.yml', 'copilot_commit.yml', 'copilot_issue.yml',
'copilot_issue_comment.yml', 'copilot_pull_request.yml',
'copilot_pull_request_comment.yml', 'copilot_pull_request_review_state.yml',
]) {
const coordinator = ['copilot_issue_comment.yml', 'copilot_pull_request_comment.yml'].includes(fileName);
const workflow = yaml.load(readFileSync(path.join(process.cwd(), coordinator ? '.github/workflows' : directory, coordinator ? 'copilot_comment_runtime.yml' : fileName), 'utf8')) as MutationWorkflow;
const steps = Object.values(workflow.jobs).flatMap(job => job.steps ?? []);
const modelInputs = steps.filter(step => step.with?.['agent-model']);
expect(modelInputs).not.toHaveLength(0);
expect(modelInputs.every(step => step.with['agent-model'] === modelFallback)).toBe(true);
if (fileName === 'copilot_close_inactive_issues.yml') continue;
const allowlists = steps.filter(step => step.env?.AGENT_ALLOWED_MODELS);
expect(allowlists).not.toHaveLength(0);
expect(allowlists.every(step => step.env.AGENT_ALLOWED_MODELS === allowedFallback)).toBe(true);
}
},
);
it('publishes the same default on the action input surface', () => {
const manifest = yaml.load(readFileSync(path.join(process.cwd(), 'action.yml'), 'utf8')) as {
inputs: Record<string, { default?: string }>;
};
expect(manifest.inputs['agent-model'].default).toBe('gpt-6-luna');
});
it('excludes retired decorative image inputs from the public action contract', () => {
const manifest = yaml.load(
readFileSync(path.join(process.cwd(), 'action.yml'), 'utf8'),
) as {
inputs: Record<string, { default?: string; description?: string }>;
};
expect(Object.keys(manifest.inputs)).not.toContainEqual(expect.stringMatching(/^images-(?:on-|issue-|pull-request-|commit-)/u));
});
it('keeps the repository validation manifest unique and the queue budget synchronized', () => {
const workflowNames = QUEUE_WORKFLOW_MANIFEST.map(entry => entry.workflowName);
expect(new Set(workflowNames).size).toBe(workflowNames.length);
expect(WORKFLOW_QUEUE_POLICY.maximumQueueWaitMilliseconds).toBe(90 * 60 * 1000);
expect(MIN_QUEUE_JOB_TIMEOUT_MINUTES).toBeGreaterThanOrEqual(QUEUE_WAIT_MINUTES);
});
it('enforces the minimum job timeout to be at least the queue wait budget', () => {
expect(() => assertQueueBudget(90, 89)).toThrow('must be >= queue wait');
expect(() => assertQueueBudget(90, 90)).not.toThrow();
});
it('scopes replaceable event lanes to their branch or PR owner', () => {
for (const directory of ['.github/workflows', 'setup/workflows']) {
for (const manifest of QUEUE_WORKFLOW_MANIFEST) {
const file = path.join(process.cwd(), directory, manifest.file);
const workflow = yaml.load(readFileSync(file, 'utf8')) as Record<string, unknown> & {
jobs: Record<string, { concurrency?: unknown }>;
};
if (manifest.file === 'copilot_issue.yml') {
expect(workflow.concurrency).toEqual({ group: 'copilot-issue-${{ github.repository }}-${{ github.event.issue.number }}', 'cancel-in-progress': false, queue: 'max' });
} else expect(workflow.concurrency).toBeUndefined();
if (['copilot_commit.yml', 'copilot_pull_request.yml', 'copilot_pull_request_review_state.yml'].includes(manifest.file)) {
const expectedGroup = manifest.file === 'copilot_commit.yml'
? 'copilot-push-${{ github.repository }}-${{ github.ref_name }}'
: `copilot-pr-${'${{ github.repository }}'}-${'${{ github.event.pull_request.number }}'}-${manifest.file === 'copilot_pull_request.yml' ? 'analysis' : 'review-state'}`;
expect(workflow.jobs[manifest.jobId].concurrency).toEqual({
group: expectedGroup,
'cancel-in-progress': true,
});
} else {
expect(workflow.jobs[manifest.jobId].concurrency).toBeUndefined();
}
expect(() => validateWorkflow(file, workflow)).not.toThrow();
}
}
});
it.each(['.github/workflows', 'setup/workflows'])(
'isolates two PRs on the same head branch while retaining stable independent lanes in %s',
directory => {
const render = (file: string, jobId: string, pullNumber: number, headRef = 'master') => {
const workflow = yaml.load(readFileSync(path.join(process.cwd(), directory, file), 'utf8')) as MutationWorkflow;
return workflow.jobs[jobId].concurrency.group
.replace('${{ github.repository }}', 'example/repository')
.replace('${{ github.event.pull_request.number }}', String(pullNumber))
.replace('${{ github.event.pull_request.head.ref || github.ref_name }}', headRef);
};
const analysis = (number: number, headRef?: string) => render('copilot_pull_request.yml', 'copilot-pull-requests', number, headRef);
const observer = (number: number, headRef?: string) => render('copilot_pull_request_review_state.yml', 'copilot-pull-request-review-state', number, headRef);
expect(analysis(21)).not.toBe(analysis(22));
expect(observer(21)).not.toBe(observer(22));
expect(analysis(21)).toBe(analysis(21, 'renamed-head'));
expect(observer(21)).toBe(observer(21, 'renamed-head'));
expect(analysis(21)).not.toBe(observer(21));
},
);
it.each(['.github/workflows', 'setup/workflows'].flatMap(directory => [
[directory, 'copilot_pull_request.yml', 'copilot-pull-requests', 'analysis'],
[directory, 'copilot_pull_request_review_state.yml', 'copilot-pull-request-review-state', 'review-state'],
]))('rejects cross-PR branch collisions in %s/%s', (directory, fileName, jobId, lane) => {
const file = path.join(process.cwd(), directory, fileName);
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
workflow.jobs[jobId].concurrency.group = `copilot-pr-${'${{ github.repository }}'}-${'${{ github.event.pull_request.head.ref || github.ref_name }}'}-${lane}`;
expect(() => validateWorkflow(file, workflow)).toThrow('PR number');
});
it.each(['.github/workflows', 'setup/workflows'].flatMap(directory => [
[directory, 'copilot_pull_request.yml', 'copilot-pull-requests'],
[directory, 'copilot_pull_request_review_state.yml', 'copilot-pull-request-review-state'],
]))(
'rejects pull-request workflows that do not cancel superseded events in %s/%s',
(directory, fileName, jobId) => {
const file = path.join(process.cwd(), directory, fileName);
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
workflow.jobs[jobId].concurrency['cancel-in-progress'] = false;
expect(() => validateWorkflow(file, workflow)).toThrow('cancel superseded runs');
},
);
it.each([
['copilot_commit.yml', 'copilot-commits', 'copilot-pr-${{ github.repository }}-${{ github.ref_name }}'],
['copilot_pull_request.yml', 'copilot-pull-requests', 'copilot-push-${{ github.repository }}-${{ github.ref_name }}'],
['copilot_pull_request_review_state.yml', 'copilot-pull-request-review-state', 'copilot-pr-${{ github.repository }}-${{ github.event.pull_request.number }}-analysis'],
])(
'rejects a cross-workflow concurrency group in %s',
(workflowFile, jobId, sharedGroup) => {
const file = path.join(process.cwd(), '.github/workflows', workflowFile);
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
workflow.jobs[jobId].concurrency.group = sharedGroup;
expect(() => validateWorkflow(file, workflow)).toThrow('avoid cross-canceling another event owner');
},
);
it.each(['.github/workflows', 'setup/workflows'])(
'rejects a PR group that lets review-state events cancel active analysis in %s',
(directory) => {
const file = path.join(process.cwd(), directory, 'copilot_pull_request.yml');
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
workflow.jobs['copilot-pull-requests'].concurrency.group =
'copilot-pr-${{ github.repository }}-${{ github.event.pull_request.number }}';
expect(() => validateWorkflow(file, workflow)).toThrow('avoid cross-canceling another event owner');
},
);
it('rejects an event workflow that bypasses native issue admission', () => {
const workflow = JSON.parse(JSON.stringify(validWorkflow));
delete workflow.jobs['copilot-issues'].if;
expect(() => assertQueueWorkflow(queueFile, workflow)).toThrow('isolated native issue admission');
});
it.each(['.github/workflows', 'setup/workflows'])(
'keeps the %s branch-sync observer ordinary-branch, bot-push-safe, and agent-free',
(directory) => {
const file = path.join(process.cwd(), directory, 'copilot_branch_sync.yml');
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
expect(() => assertLightweightBranchSyncWorkflow(file, workflow)).not.toThrow();
workflow.jobs['branch-sync'].steps.at(-1).with['fixer-model'] = 'model';
expect(() => assertLightweightBranchSyncWorkflow(file, workflow)).toThrow('lightweight branch-sync');
},
);
it.each(['copilot_pull_request.yml', 'copilot_pull_request_review_state.yml', 'copilot_pull_request_comment.yml'])(
'requires same-repository PR gating for %s',
(fileName) => {
for (const directory of ['.github/workflows', 'setup/workflows']) {
const file = path.join(process.cwd(), directory, fileName);
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
const jobId = fileName === 'copilot_pull_request_review_state.yml'
? 'copilot-pull-request-review-state'
: 'copilot-pull-requests';
const job = workflow.jobs[jobId];
job.if = "${{ vars.COPILOT_BOT_LOGIN == '' || github.actor != vars.COPILOT_BOT_LOGIN }}";
expect(() => validateWorkflow(file, workflow)).toThrow('same-repository PR gate');
}
},
);
it('rejects workflow_run and keeps PR analysis separate from review-state events', () => {
for (const directory of ['.github/workflows', 'setup/workflows']) {
const analysisFile = path.join(process.cwd(), directory, 'copilot_pull_request.yml');
const analysis = yaml.load(readFileSync(analysisFile, 'utf8')) as Record<string, any>;
expect(() => assertDirectEventTriggers(analysisFile, analysis)).not.toThrow();
analysis.on.pull_request_review = { types: ['submitted'] };
expect(() => assertDirectEventTriggers(analysisFile, analysis)).toThrow('only direct pull_request');
const reviewFile = path.join(process.cwd(), directory, 'copilot_pull_request_review_state.yml');
const review = yaml.load(readFileSync(reviewFile, 'utf8')) as Record<string, any>;
expect(() => assertDirectEventTriggers(reviewFile, review)).not.toThrow();
review.on.workflow_run = { types: ['completed'] };
expect(() => assertDirectEventTriggers(reviewFile, review)).toThrow('must not define workflow_run');
delete review.on.workflow_run;
review.on.pull_request = { types: ['synchronize'] };
expect(() => assertDirectEventTriggers(reviewFile, review)).toThrow('only direct pull_request_review');
}
});
it.each(['.github/workflows', 'setup/workflows'])(
'rejects metadata-only PR triggers, embedded merge checks, and unsafe PR check identities in %s',
(directory) => {
const file = path.join(process.cwd(), directory, 'copilot_pull_request.yml');
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
workflow.on.pull_request.types.push('edited');
expect(() => assertDirectEventTriggers(file, workflow)).toThrow('metadata-only edited events');
workflow.on.pull_request.types = workflow.on.pull_request.types.filter((type: string) => type !== 'edited');
workflow.on.merge_group = { types: ['checks_requested'] };
expect(() => assertDirectEventTriggers(file, workflow)).toThrow('dedicated pull-request merge-queue workflow');
delete workflow.on.merge_group;
workflow.jobs['copilot-pull-requests'].name = 'Unsafe dynamic identity';
expect(() => assertDirectEventTriggers(file, workflow)).toThrow('normal PR analysis check identity');
},
);
it.each(['.github/workflows', 'setup/workflows'])(
'rejects a non-fixed review-state identity in %s',
(directory) => {
const file = path.join(process.cwd(), directory, 'copilot_pull_request_review_state.yml');
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
workflow.jobs['copilot-pull-request-review-state'].name = '${{ github.event.action }}';
expect(() => assertDirectEventTriggers(file, workflow)).toThrow('review-state workflow and check identity');
},
);
it.each(['.github/workflows', 'setup/workflows'])(
'keeps merge-queue required checks isolated, exact, and lightweight in %s',
(directory) => {
const file = path.join(process.cwd(), directory, 'copilot_pull_request_merge_queue.yml');
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
expect(() => validateWorkflow(file, workflow)).not.toThrow();
workflow.jobs['copilot-pull-request-required-check'].name = 'Copilot - Merge Queue';
expect(() => validateWorkflow(file, workflow)).toThrow('required-check identity');
},
);
it.each(['.github/workflows', 'setup/workflows'])('requires the exact push review range fetch in %s', (directory) => {
const file = path.join(process.cwd(), directory, 'copilot_commit.yml');
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
workflow.jobs['copilot-commits'].steps = workflow.jobs['copilot-commits'].steps.filter(
(step: { name?: string }) => step.name !== 'Fetch push review range',
);
expect(() => validateWorkflow(file, workflow)).toThrow('must materialize and verify the exact GitHub before/after review range');
});
it.each([
['.github/workflows', 'copilot_commit.yml', 'copilot-commits'],
['.github/workflows', 'release_workflow.yml', 'prepare-compiled-files'],
['setup/workflows', 'copilot_commit.yml', 'copilot-commits'],
['setup/workflows', 'copilot_pull_request.yml', 'copilot-pull-requests'],
])('requires portable Bash for run steps in %s/%s', (directory, fileName, jobId) => {
const file = path.join(process.cwd(), directory, fileName);
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
expect(() => assertPortableRunShell(file, workflow)).not.toThrow();
delete workflow.defaults;
delete workflow.jobs[jobId].defaults;
for (const step of workflow.jobs[jobId].steps) delete step.shell;
expect(() => assertPortableRunShell(file, workflow)).toThrow('must select shell: bash');
});
it('rejects a platform-specific shell override on a Codex runner', () => {
const file = path.join(process.cwd(), '.github/workflows/copilot_commit.yml');
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
workflow.jobs['copilot-commits'].steps.find((step: { run?: string }) => step.run).shell = 'pwsh';
expect(() => assertPortableRunShell(file, workflow)).toThrow('must select shell: bash');
});
it.each(['.github/workflows', 'setup/workflows'])('requires a full checkout for push review ranges in %s', (directory) => {
const file = path.join(process.cwd(), directory, 'copilot_commit.yml');
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
const step = workflow.jobs['copilot-commits'].steps.find(
(candidate: { uses?: string }) => candidate.uses?.startsWith('actions/checkout@'),
);
step.with['fetch-depth'] = 1;
expect(() => validateWorkflow(file, workflow)).toThrow('must materialize and verify the exact GitHub before/after review range');
});
it.each(['.github/workflows', 'setup/workflows'])('requires a non-fatal before fetch for force-pushed PRs in %s', (directory) => {
const file = path.join(process.cwd(), directory, 'copilot_pull_request.yml');
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
const step = workflow.jobs['copilot-pull-requests'].steps.find(
(candidate: { name?: string }) => candidate.name === 'Fetch incremental review range',
);
step.run = 'git cat-file -e "${BEFORE_SHA}^{commit}"';
expect(() => validateWorkflow(file, workflow)).toThrow('must materialize and verify the exact GitHub before/after review range');
});
it('validates the exact mutex and validation-first DAG for active and setup release/hotfix workflows', () => {
for (const directory of ['.github/workflows', 'setup/workflows']) {
for (const fileName of ['release_workflow.yml', 'hotfix_workflow.yml']) {
const file = path.join(process.cwd(), directory, fileName);
const workflow = yaml.load(readFileSync(file, 'utf8')) as Record<string, unknown>;
expect(() => validateWorkflow(file, workflow)).not.toThrow();
}
}
});
it.each(['.github/workflows', 'setup/workflows'])(
'validates the dedicated managed-PR continuation in %s',
(directory) => {
const file = path.join(process.cwd(), directory, 'copilot_deployment_orchestration.yml');
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
expect(() => validateWorkflow(file, workflow)).not.toThrow();
expect(workflow.jobs['resolve-operation'].if).toContain('github.event.pull_request.head.repo.full_name == github.repository');
expect(workflow.jobs.mutate.concurrency).toEqual({
group: 'copilot-deployment-${{ github.repository_id }}-${{ needs.resolve-operation.outputs.issue }}',
'cancel-in-progress': false,
queue: 'max',
});
const continuation = workflow.jobs.mutate.steps.find(
(step: { with?: Record<string, unknown> }) => step.with?.['single-action'] === 'continue_deployment_action',
);
expect(continuation?.with?.['merge-queue-check-attestations'])
.toBe("${{ vars.MERGE_QUEUE_CHECK_ATTESTATIONS || '[]' }}");
},
);
it.each(['.github/workflows', 'setup/workflows'])(
'rejects continuation without live merge-queue attestations in %s',
(directory) => {
const file = path.join(process.cwd(), directory, 'copilot_deployment_orchestration.yml');
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
const continuation = workflow.jobs.mutate.steps.find(
(step: { with?: Record<string, unknown> }) => step.with?.['single-action'] === 'continue_deployment_action',
);
delete continuation.with['merge-queue-check-attestations'];
expect(() => validateWorkflow(file, workflow)).toThrow('live merge-queue attestations');
},
);
it.each([
'.github/workflows/ci_check.yml',
'.github/workflows/copilot_pull_request_merge_queue.yml',
'setup/workflows/copilot_pull_request_merge_queue.yml',
])('requires merge-group checks in %s', (relativeFile) => {
const file = path.join(process.cwd(), relativeFile);
const workflow = yaml.load(readFileSync(file, 'utf8')) as MutationWorkflow;
delete workflow.on.merge_group;
expect(() => validateWorkflow(file, workflow)).toThrow('must support merge_group checks_requested');
});
it.each(mutationDirectories.flatMap((directory) => mutationWorkflowNames.map((fileName) => [directory, fileName] as const)))(
'persists Git credentials only in the release/hotfix jobs that push in %s/%s',
(directory, fileName) => {
const { workflow } = loadMutationWorkflow(directory, fileName);
const preparationJobIds = directory === '.github/workflows'
? ['prepare-version-files', 'prepare-compiled-files']
: ['prepare-version-files'];
for (const [jobId, job] of Object.entries(workflow.jobs)) {
const checkoutSteps = job.steps.filter((step: { uses?: string }) => step.uses?.startsWith('actions/checkout@'));
for (const checkout of checkoutSteps) {
expect(checkout.with['persist-credentials']).toBe(preparationJobIds.includes(jobId));
}
}
const commitSteps = preparationJobIds.flatMap(jobId => workflow.jobs[jobId].steps)
.filter((step: { uses?: string }) => step.uses?.startsWith('EndBug/add-and-commit@'));
expect(commitSteps).toHaveLength(preparationJobIds.length);
for (const step of commitSteps) {
expect(step.with.committer_name).toBe('GitHub Actions');
expect(step.with.committer_email).toBe('actions@github.com');
expect(step.with.default_author).toBe('user_info');
}
},
);
it.each(mutationWorkflowNames)('rejects missing credentials in a push job for %s', (fileName) => {
expectMutationRejected('.github/workflows', fileName, (workflow) => {
const checkout = workflow.jobs['prepare-version-files'].steps.find(
(step: { uses?: string }) => step.uses?.startsWith('actions/checkout@'),
);
checkout.with['persist-credentials'] = false;
}, 'persist-credentials: true');
});
it.each(mutationWorkflowNames)('rejects persisted credentials outside push jobs for %s', (fileName) => {
expectMutationRejected('.github/workflows', fileName, (workflow) => {
const checkout = workflow.jobs.tag.steps.find(
(step: { uses?: string }) => step.uses?.startsWith('actions/checkout@'),
);
checkout.with['persist-credentials'] = true;
}, 'persist-credentials: false');
});
it.each(mutationWorkflowNames)('persists active %s publication failures and reports preparation failures', (fileName) => {
const { workflow } = loadMutationWorkflow('.github/workflows', fileName);
const report = workflow.jobs['report-failure'];
const durable = report.steps[1];
const action = report.steps[2];
const expectedToken = '${{ secrets.PAT }}';
expect(report.if).toBe("${{ failure() && needs.validate.result == 'success' && inputs.mode != 'replace' }}");
expect(report.permissions).toEqual({ contents: 'read', issues: 'write' });
expect(report.steps[0]).toEqual(expect.objectContaining({
uses: 'actions/checkout@v5',
with: { 'persist-credentials': false },
}));
expect(durable.with).toEqual(expect.objectContaining({
'single-action': 'failed_deployment_action',
'single-action-operation-id': '${{ inputs.operation-id }}',
'single-action-version': '${{ inputs.version }}',
token: expectedToken,
}));
expect(durable.if).toBe("${{ inputs.mode == 'publish' || inputs.mode == 'resume' }}");
expect(action.uses).toBe('./');
expect(action.if).toBe("${{ inputs.mode == 'prepare' }}");
expect(action.with).toEqual(expect.objectContaining({
'single-action': 'publish_issue_comment',
'single-action-issue': '${{ inputs.issue }}',
token: expectedToken,
}));
expect(action.with['single-action-message']).toContain('${{ github.run_id }}');
});
it.each(mutationWorkflowNames)('persists setup/%s publication failures and reports preparation failures', (fileName) => {
const { workflow } = loadMutationWorkflow('setup/workflows', fileName);
const report = workflow.jobs['report-failure'];
const durable = report.steps[0];
const action = report.steps[1];
expect(report.permissions).toEqual({ issues: 'write' });
expect(durable.with).toEqual(expect.objectContaining({
'single-action': 'failed_deployment_action',
'single-action-operation-id': '${{ inputs.operation-id }}',
'single-action-version': '${{ inputs.version }}',
token: '${{ secrets.PAT }}',
}));
expect(durable.if).toBe("${{ inputs.mode == 'publish' || inputs.mode == 'resume' }}");
expect(action.uses).toBe('vypdev/copilot@v3');
expect(action.if).toBe("${{ inputs.mode == 'prepare' }}");
expect(action.with).toEqual(expect.objectContaining({
'single-action': 'publish_issue_comment',
'single-action-issue': '${{ inputs.issue }}',
token: '${{ secrets.PAT }}',
}));
expect(action.with['single-action-message']).toContain('${{ github.run_id }}');
});
it('rejects a local Copilot reference from a distributed setup workflow', () => {
const { file, workflow } = loadMutationWorkflow('setup/workflows', 'release_workflow.yml');
const action = workflow.jobs.promote.steps.find((step: { with?: Record<string, unknown> }) =>
step.with?.['single-action'] === 'prepare_deployment_action');
action.uses = './';
expect(() => assertMajorActionReferences(file, workflow)).toThrow('must invoke Copilot with vypdev/copilot@v3');
});
it('rejects a distributed Copilot reference from an internal workflow', () => {
const { file, workflow } = loadMutationWorkflow('.github/workflows', 'release_workflow.yml');
const action = workflow.jobs.promote.steps.find((step: { with?: Record<string, unknown> }) =>
step.with?.['single-action'] === 'prepare_deployment_action');
action.uses = 'vypdev/copilot@v3';
expect(() => assertMajorActionReferences(file, workflow)).toThrow('must invoke Copilot with ./');
});
it.each(mutationWorkflowNames)('rejects a missing failure reporter in %s', (fileName) => {
expectMutationRejected('.github/workflows', fileName, (workflow) => {
delete workflow.jobs['report-failure'];
}, 'must define the exact validation-first job graph');
});
it.each(mutationWorkflowNames)('rejects a failure reporter that can run without a failed deployment in %s', (fileName) => {
expectMutationRejected('.github/workflows', fileName, (workflow) => {
workflow.jobs['report-failure'].if = '${{ always() }}';
}, 'must run only for a failed deployment');
});
it.each(mutationDirectories.flatMap((directory) => mutationWorkflowNames.map((fileName) => [directory, fileName] as const)))('enforces the exact validation and preparation budgets for %s/%s', (directory, fileName) => {
expectMutationRejected(directory, fileName, (workflow) => {
workflow.jobs.validate['timeout-minutes'] = DEPLOYMENT_VALIDATION_TIMEOUT_MINUTES - 1;
}, 'validate must have timeout-minutes 5');
expectMutationRejected(directory, fileName, (workflow) => {
workflow.jobs['prepare-version-files']['timeout-minutes'] = (directory === '.github/workflows' ? PREPARE_VERSION_TIMEOUT_MINUTES : 30) - 1;
}, `job prepare-version-files must have timeout-minutes ${directory === '.github/workflows' ? 15 : 30}`);
if (directory === '.github/workflows') {
expectMutationRejected(directory, fileName, (workflow) => {
workflow.jobs.tag['timeout-minutes'] = TAG_TIMEOUT_MINUTES - 1;
}, 'job tag must have timeout-minutes 10');
}
});
it.each(mutationDirectories.flatMap(directory => mutationWorkflowNames.flatMap(fileName =>
['prepare', 'publish', 'resume'].flatMap(phase => ['missing', 'stale'].map(value => [directory, fileName, phase, value])))))(
'rejects %s/%s %s with %s merge-queue attestations', (directory, fileName, phase, value) => {
expectMutationRejected(directory, fileName, workflow => {
const action = phase === 'prepare' ? 'prepare_deployment_action' : 'published_deployment_action';
const job = phase === 'resume' ? workflow.jobs['resume-reconciliation']
: Object.entries(workflow.jobs).find(([id, job]) => id !== 'resume-reconciliation'
&& (job.steps ?? []).some((step: any) => step.with?.['single-action'] === action))![1];
const step = job.steps.find((step: any) => step.with?.['single-action'] === action);
if (value === 'missing') delete step.with['merge-queue-check-attestations'];
else step.with['merge-queue-check-attestations'] = '[]';
}, 'live merge-queue attestations');
},
);
it.each(mutationWorkflowNames)('enforces the active compiled-files budget for %s', (fileName) => {
expectMutationRejected('.github/workflows', fileName, (workflow) => {
workflow.jobs['prepare-compiled-files']['timeout-minutes'] = PREPARE_COMPILED_TIMEOUT_MINUTES - 1;
}, 'job prepare-compiled-files must have timeout-minutes 30');
});
it.each(mutationDirectories.flatMap(directory => mutationWorkflowNames.map(fileName => [directory, fileName])))(
'executes %s/%s input validation with the bundled runtime and default token', (directory, fileName) => {
const { workflow } = loadMutationWorkflow(directory, fileName);
const step = workflow.jobs.validate.steps[0];
expect(step.uses).toBe('actions/github-script@v9');
expect(step.with['github-token']).toBeUndefined();
expect(step.run).toBeUndefined();
expect(workflow.jobs.validate.permissions).toEqual({});
const prepare = { MODE: 'prepare', OPERATION_ID: '', VERSION: '3.4.0', ISSUE: '499', TITLE: 'Minor release', CHANGELOG: 'Validated changes' };
const publish = { ...prepare, MODE: 'publish', OPERATION_ID: 'release-operation-499', TITLE: '', CHANGELOG: '' };
const scenarios = [
{ env: prepare, valid: true },
{ env: publish, valid: true },
{ env: { ...publish, MODE: 'resume' }, valid: true },
{ env: { ...publish, MODE: 'resume', OPERATION_ID: '' }, valid: false },
{ env: { ...prepare, ISSUE: '-1' }, valid: false },
{ env: { ...prepare, ISSUE: '9007199254740992' }, valid: false },
{ env: { ...prepare, VERSION: 'Automatic' }, valid: false },
{ env: { ...prepare, MODE: 'unknown' }, valid: false },
{ env: { ...prepare, OPERATION_ID: 'unexpected-operation' }, valid: false },
{ env: { ...prepare, TITLE: '' }, valid: false },
{ env: { ...prepare, CHANGELOG: '' }, valid: false },
{ env: { ...publish, OPERATION_ID: '' }, valid: false },
{ env: { ...publish, TITLE: 'unexpected title' }, valid: false },
{ env: { ...publish, CHANGELOG: 'unexpected changelog' }, valid: false },
];
for (const scenario of scenarios) {
const setFailed = jest.fn();
runInNewContext(step.with.script, { process: { env: scenario.env }, core: { setFailed } });
expect(setFailed).toHaveBeenCalledTimes(scenario.valid ? 0 : 1);
}
},
);
it.each([
["skipped proof", (job: Record<string, any>) => { job.steps[0].if = "${{ false }}"; }],
["ignored proof failure", (job: Record<string, any>) => { job.steps[0]['continue-on-error'] = true; }],
["different launcher", (job: Record<string, any>) => { job.steps.at(-1).with['single-action-issue'] = '1'; }],
] as const)("rejects recovery proof bypass: %s", (_name, mutate) => {
expectMutationRejected('.github/workflows', 'release_workflow.yml', workflow => {
mutate(workflow.jobs['resume-reconciliation']);
}, 'recovery must prove existing publication state');
});
it.each(mutationDirectories.flatMap(directory => mutationWorkflowNames.map(fileName => [directory, fileName]))) (
"isolates recovery and executes its durable-state proof in %s/%s", async (directory, fileName) => {
const { workflow } = loadMutationWorkflow(directory, fileName);
const job = workflow.jobs["resume-reconciliation"];
expect(job.needs).toBe("validate");
expect(job.if).toBe("${{ inputs.mode == 'resume' }}");
expect(job.steps.filter((step: { with?: Record<string, unknown> }) => step.with?.['single-action'])
.map((step: { with: Record<string, unknown> }) => step.with['single-action'])).toEqual(['published_deployment_action']);
expect(JSON.stringify(job)).not.toMatch(/npm publish|create_tag|create_release|publish_github_action/);
const state = { stateVersion: 1, revision: 10, operationId: 'operation-12345678', version: '3.5.2',
phase: 'blocked', lastFailure: { retryable: true, previousPhase: 'reconciliation_pending' },
publicationVerified: true, productionSha: 'c'.repeat(40), tag: 'v3.5.2',
publicationReceipt: { operationId: 'operation-12345678', productionSha: 'c'.repeat(40), tag: 'v3.5.2' } };
const scenarios = [
{ ...state }, { ...state, phase: 'reconciliation_pending' }, { ...state, phase: 'completed' },
{ ...state, operationId: 'other-operation' }, { ...state, version: '3.5.3' },
{ ...state, publicationVerified: false }, { ...state, revision: 0 },
{ ...state, phase: 'publishing' }, { ...state, lastFailure: { retryable: false } },
{ ...state, publicationReceipt: { ...state.publicationReceipt, productionSha: 'd'.repeat(40) } },
];
for (const [index, candidate] of scenarios.entries()) {
const github = { rest: { issues: { get: jest.fn().mockResolvedValue({ data: {
body: '<!-- copilot-configuration-start' + JSON.stringify({ schemaVersion: 3, deploymentOrchestration: candidate }) + 'copilot-configuration-end -->',
} }) } } };
const result = runInNewContext('(async () => {' + job.steps[0].with.script + '})()', {
github, context: { repo: { owner: 'owner', repo: 'repo' } },
process: { env: { ISSUE: '517', OPERATION_ID: state.operationId, VERSION: state.version } },
});
if (index < 3) await expect(result).resolves.toBeUndefined();
else await expect(result).rejects.toThrow('Recovery requires');
}
},
);
it.each(mutationWorkflowNames.flatMap(fileName => ([
{ name: 'already visible', timeout: '600', interval: '20', visibleAt: 0, success: true, elapsed: 0 },
{ name: 'lookup finishes at the deadline', timeout: '600', interval: '20', visibleAt: 600000, success: true, elapsed: 600000, slowAt: 580000, lookupDuration: 20000 },
{ name: 'not visible within ten minutes', timeout: '600', interval: '20', visibleAt: 601000, success: false, elapsed: 600000 },
{ name: 'clamped final interval', timeout: '61', interval: '60', visibleAt: 61000, success: false, elapsed: 61000 },
{ name: 'timeout below the allowed range', timeout: '59', interval: '20', visibleAt: 0, success: false, elapsed: 0 },
{ name: 'timeout above the allowed range', timeout: '901', interval: '20', visibleAt: 0, success: false, elapsed: 0 },
{ name: 'interval below the allowed range', timeout: '600', interval: '9', visibleAt: 0, success: false, elapsed: 0 },
{ name: 'interval above the allowed range', timeout: '600', interval: '61', visibleAt: 0, success: false, elapsed: 0 },
{ name: 'lookup is killed at the deadline', timeout: '600', interval: '20', visibleAt: 601000, success: false, elapsed: 600000, slowAt: 580000, lookupDuration: 30000 },
{ name: 'late successful response is rejected', timeout: '600', interval: '20', visibleAt: 600000, success: false, elapsed: 610000, slowAt: 580000, lookupDuration: 30000, ignoreLookupTimeout: true },
{ name: 'non-numeric timeout', timeout: '600seconds', interval: '20', visibleAt: 0, success: false, elapsed: 0 },
{ name: 'non-integer interval', timeout: '600', interval: '20.5', visibleAt: 0, success: false, elapsed: 0 },
] as RegistryVisibilityCase[]).map(scenario => ({ fileName, ...scenario }))))('$fileName: npm visibility $name', async scenario => {
const { workflow } = loadMutationWorkflow('.github/workflows', scenario.fileName);
const availability = workflow.jobs['publish-npm'].steps.find((step: { name?: string }) => step.name === 'Wait for npm registry visibility');
expect(availability.env.POLL_TIMEOUT).toBe("${{ vars.NPM_VISIBILITY_TIMEOUT_SECONDS || '600' }}");
expect(availability.uses).toBe('actions/github-script@v9');
let elapsed = 0;
let failure: string | undefined;
const lookup = jest.fn((command: string, args: string[], options: { timeout: number; killSignal: string }) => {
expect(command).toBe('npm');
expect(args).toContain('--fetch-retries=0');
expect(options.timeout).toBe(Number(scenario.timeout) * 1000 - elapsed);
expect(options.killSignal).toBe('SIGKILL');
const duration = elapsed >= (scenario.slowAt ?? Infinity) ? scenario.lookupDuration! : 0;
if (duration > options.timeout && !scenario.ignoreLookupTimeout) {
elapsed += options.timeout;
return { status: null, stdout: '', error: { code: 'ETIMEDOUT' } };
}
elapsed += duration;
return { status: elapsed >= scenario.visibleAt ? 0 : 1, stdout: elapsed >= scenario.visibleAt ? '3.5.0\n' : '' };
});
const execution = runInNewContext(`(async () => { ${availability.with.script} })()`, {
require: (name: string) => { expect(name).toBe('node:child_process'); return { spawnSync: lookup }; },
process: { env: { PACKAGE_NAME: '@vypdev/copilot', RELEASE_VERSION: '3.5.0', POLL_TIMEOUT: scenario.timeout, POLL_INTERVAL: scenario.interval } },
Date: { now: () => elapsed },
setTimeout: (resolve: () => void, delay: number) => { elapsed += delay; resolve(); },
core: { info: jest.fn(), setFailed: (message: string) => { failure = message; } },
});
const thrown = await execution.then(() => undefined, (error: unknown) => error);
expect(thrown === undefined && failure === undefined).toBe(scenario.success);
expect(elapsed).toBe(scenario.elapsed);
if (!scenario.success && scenario.elapsed === 0) expect(lookup).not.toHaveBeenCalled();
});
it('keeps npm publication between tag creation and release finalization', () => {
const { workflow } = loadMutationWorkflow('.github/workflows', 'release_workflow.yml');
expect(workflow.jobs['publish-npm']).toEqual(expect.objectContaining({
needs: 'tag',
environment: 'npm',
'runs-on': 'ubuntu-latest',
'timeout-minutes': NPM_PUBLISH_TIMEOUT_MINUTES,
permissions: { contents: 'read', 'id-token': 'write' },
}));
expect(workflow.jobs['finalize-release']).toEqual(expect.objectContaining({
needs: 'publish-npm',
'timeout-minutes': FINALIZE_RELEASE_TIMEOUT_MINUTES,
permissions: { contents: 'write', issues: 'write', 'pull-requests': 'write' },
}));
expect(workflow.jobs['publish-npm'].if).toBe("${{ inputs.mode == 'publish' }}");
expect(workflow.jobs['publish-npm'].steps).toEqual(expect.arrayContaining([
expect.objectContaining({ run: 'pnpm install --frozen-lockfile' }),
expect.objectContaining({ run: 'npm publish --access public' }),
expect.objectContaining({
name: 'Verify published package identity',
run: expect.stringContaining('"$registry_git_head" = "$local_git_head"'),
}),
expect.objectContaining({
name: 'Wait for npm registry visibility',
env: expect.objectContaining({
PACKAGE_NAME: '@vypdev/copilot',
RELEASE_VERSION: '${{ inputs.version }}',
POLL_INTERVAL: "${{ vars.NPM_VISIBILITY_POLL_INTERVAL_SECONDS || '20' }}",
}),
uses: 'actions/github-script@v9',
with: expect.objectContaining({ script: expect.stringContaining('timeout: remaining') }),
}),
]));
expect(JSON.stringify(workflow.jobs['publish-npm'])).not.toMatch(/NPM_TOKEN|NODE_AUTH_TOKEN/);
});
it.each([
['missing OIDC permission', (job: Record<string, any>) => { delete job.permissions['id-token']; }, 'id-token: write'],
['wrong environment', (job: Record<string, any>) => { job.environment = 'production'; }, 'npm environment'],
['wrong phase gate', (job: Record<string, any>) => { job.if = "${{ vars.NPM_PUBLISH_ENABLED == 'true' }}"; }, 'only in publish mode'],
['self-hosted npm runner', (job: Record<string, any>) => { job['runs-on'] = ['self-hosted', 'codex']; }, 'runs-on ubuntu-latest'],
['long-lived npm token', (job: Record<string, any>) => {
const publish = job.steps.find((step: Record<string, any>) => step.run === 'npm publish --access public');
publish.env = { NODE_AUTH_TOKEN: '${{ secrets.NPM_TOKEN }}' };
}, 'authenticate only through OIDC'],
])('rejects %s in the coordinated npm release job', (_reason, mutate, message) => {
expectMutationRejected('.github/workflows', 'release_workflow.yml', (workflow) => {
mutate(workflow.jobs['publish-npm']);
}, message);
});
it('keeps active tag jobs scoped to tag and issue writes', () => {
for (const fileName of mutationWorkflowNames) {
const { workflow } = loadMutationWorkflow('.github/workflows', fileName);
expect(workflow.jobs.tag.permissions).toEqual({ contents: 'write', issues: 'write' });
}
});
it.each([
['direct pre-validation mutation', (workflow: MutationWorkflow) => {
workflow.jobs['prepare-version-files'].needs = [];
}, 'job prepare-version-files must need exactly validate, candidate-preflight'],
['broken transitive edge', (workflow: MutationWorkflow) => {
workflow.jobs.promote.needs = ['validate'];
}, 'job promote must need exactly validate, candidate-preflight, prepare-compiled-files'],
['always bypass', (workflow: MutationWorkflow) => {
workflow.jobs['prepare-version-files'].if = '${{ always() }}';
}, 'must run only in the validated preparation phase'],
['validation write permission', (workflow: MutationWorkflow) => {
workflow.jobs.validate.permissions = { contents: 'write' };
}, 'validate must have no repository permissions'],
['validation secret', (workflow: MutationWorkflow) => {
workflow.jobs.validate.env = { PAT: '${{ secrets.PAT }}' };
}, 'must scope Secrets to the exact step'],
['validation bypass', (workflow: MutationWorkflow) => {
workflow.jobs.validate['continue-on-error'] = true;
}, 'validate must not receive job credentials'],
['validation token', (workflow: MutationWorkflow) => {
workflow.jobs.validate.steps[0].with['github-token'] = '${{ secrets.PAT }}';
}, 'default permissionless token'],
['empty validation token override', (workflow: MutationWorkflow) => {
workflow.jobs.validate.steps[0].with['github-token'] = '';
}, 'default permissionless token'],
['missing operation cross-field validation', (workflow: MutationWorkflow) => {
workflow.jobs.validate.steps[0].with.script = 'const issue = 1; Number.isSafeInteger(issue);';
}, 'bounded cross-field inputs'],
['wrong workflow mutex', (workflow: MutationWorkflow) => {
workflow.concurrency.group = 'unsafe';
}, 'exact issue-scoped deployment concurrency group'],
['single pending queue', (workflow: MutationWorkflow) => {
workflow.concurrency.queue = 'single';
}, 'queue: max'],
['cancel in progress', (workflow: MutationWorkflow) => {
workflow.concurrency['cancel-in-progress'] = true;
}, 'queue: max'],
['launcher issue default', (workflow: MutationWorkflow) => {
workflow.on.workflow_dispatch.inputs.issue.default = '-1';
}, 'launcher issue must be required and have no default'],
['job-level competing mutex', (workflow: MutationWorkflow) => {
workflow.jobs.tag.concurrency = { group: 'unsafe' };
}, 'must rely on the workflow deployment mutex'],
])('rejects isolated %s in a real release fixture', (_reason, mutate, message) => {
expectMutationRejected('.github/workflows', 'release_workflow.yml', mutate, message);
});
it.each([
['resolver write permission', (workflow: MutationWorkflow) => {
workflow.jobs['resolve-operation'].permissions.issues = 'write';
}, 'resolver must be read-only'],
['resolver secret', (workflow: MutationWorkflow) => {
workflow.jobs['resolve-operation'].env = { PAT: '${{ secrets.PAT }}' };
}, 'must scope Secrets to the exact step'],
['missing durable proof', (workflow: MutationWorkflow) => {
workflow.jobs['resolve-operation'].steps[0].with.script = 'core.setOutput("issue", "1")';
}, 'prove marker ownership'],
['unresolved mutation', (workflow: MutationWorkflow) => {
workflow.jobs.mutate.needs = [];
}, 'exact resolved issue deployment mutex'],
['wrong continuation mutex', (workflow: MutationWorkflow) => {
workflow.jobs.mutate.concurrency.group = 'unsafe';
}, 'exact resolved issue deployment mutex'],
])('rejects managed-PR %s', (_reason, mutate, message) => {
const file = path.join(process.cwd(), 'setup/workflows/copilot_deployment_orchestration.yml');
const workflow = JSON.parse(JSON.stringify(yaml.load(readFileSync(file, 'utf8')))) as MutationWorkflow;
mutate(workflow);
expect(() => validateWorkflow(file, workflow)).toThrow(message);
});
it.each([
['wrong workflow name', { ...validWorkflow, name: 'Wrong' }],
['missing timeout', { ...validWorkflow, jobs: { 'copilot-issues': { ...validWorkflow.jobs['copilot-issues'], 'timeout-minutes': undefined } } }],
['short timeout', { ...validWorkflow, jobs: { 'copilot-issues': { ...validWorkflow.jobs['copilot-issues'], 'timeout-minutes': 119 } } }],
['workflow concurrency', { ...validWorkflow, concurrency: { group: 'x' } }],
['job concurrency', { ...validWorkflow, jobs: { 'copilot-issues': { ...validWorkflow.jobs['copilot-issues'], concurrency: { group: 'x' } } } }],
['missing queue job', { ...validWorkflow, jobs: {} }],
['unmanifested action job', { ...validWorkflow, jobs: { ...validWorkflow.jobs, other: { steps: [{ uses: './' }] } } }],
])('rejects %s', (_reason, workflow) => {
expect(() => assertQueueWorkflow(queueFile, workflow)).toThrow();
});
it('rejects a queue job with the wrong runner', () => {
expect(() => assertRunner(queueFile, {
jobs: { 'copilot-issues': { 'runs-on': 'ubuntu-latest' } },
})).toThrow('runs-on self-hosted, codex');
expect(() => assertRunner(queueFile, {
jobs: { 'copilot-issues': { 'runs-on': ['self-hosted', 'codex', 'macOS'] } },
})).toThrow('runs-on self-hosted, codex');
});
it('accepts the setup-generated grouped provisioning route through the complete source validator', () => {
const { file, workflow } = loadMutationWorkflow('.github/workflows', 'agent-cli-provisioning.yml');
workflow.jobs['verify-agent-clis']['runs-on'] = selectedSetupRunsOn({
mode: 'manual-self-hosted', profileId: '', group: 'vypdev',
labels: ['self-hosted', 'codex', 'Linux'], validation: 'hosted',
}, 'agent');
expect(workflow.jobs['verify-agent-clis']['runs-on']).toEqual({ group: 'vypdev', labels: ['self-hosted', 'codex', 'Linux'] });
expect(() => validateWorkflow(file, workflow)).not.toThrow();
});
it.each([
{ group: 'vypdev', labels: ['self-hosted', 'codex'] },
{ labels: ['self-hosted', 'codex', 'Linux'] },
])('retains source queue contracts for literal object route %j', route => {
const { file, workflow } = loadMutationWorkflow('.github/workflows', 'copilot_issue.yml');
workflow.jobs['copilot-issues']['runs-on'] = route;
expect(() => validateWorkflow(file, workflow)).not.toThrow();
});
it.each([
['unknown field', { group: 'vypdev', labels: ['self-hosted', 'codex'], extra: true }],
['missing labels', { group: 'vypdev' }],
['empty labels', { labels: [] }],