Repository navigation
Expand file tree
/
Copy pathbehavior-gating.test.ts
More file actions
2142 lines (1985 loc) · 109 KB
/
Copy pathbehavior-gating.test.ts
File metadata and controls
2142 lines (1985 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
/**
* Anti-drift guard for the CI paths-filter gates.
*
* The extension's build inputs live once, in `.github/path-filters/extension-build.yml`, which
* every PR lane loads beside its own entries (CI.md "CI gating"). This test derives that set from
* the dependency graph in package.json and requires the source and every lane to hold exactly it,
* reviewed exceptions apart, so a new `@nulo/*` dependency left ungated, a path no graph names, or
* a re-introduced `!` negation (the dorny `some`-quantifier footgun) fails CI.
*
* Wired into CI via the root `test:ci-gating` script in `_unit-tests.yml` — without
* that step this guard would never run on a PR and the whole mechanism would be hollow.
*/
import { describe, expect, test } from "bun:test"
import { chmodSync, existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { MOVE_APPROVED_LABEL } from "../complexity-baseline/scan"
import { runStep } from "./gh-step-harness"
import { RENAMES } from "./required-checks"
const ROOT = join(import.meta.dir, "..", "..")
// apps/ vs packages/ split (FLAT layout): deployable leaves live under apps/, libs under packages/.
const APPS = new Set(["extension", "landing", "playground"])
const dirOf = (pkg: string): string => (APPS.has(pkg) ? "apps" : "packages")
/** Direct `@nulo/*` workspace deps of a package (runtime + dev — what it's built/tested from). */
function directDeps(pkg: string): string[] {
const p = JSON.parse(readFileSync(join(ROOT, dirOf(pkg), pkg, "package.json"), "utf8"))
return Object.keys({ ...p.dependencies, ...p.devDependencies })
.filter((k) => k.startsWith("@nulo/"))
.map((k) => k.slice("@nulo/".length))
}
/** Transitive `@nulo/*` dependency closure of a target (EXCLUDING the target itself). */
function transitiveDeps(target: string): string[] {
const seen = new Set<string>()
const walk = (pkg: string) => {
for (const d of directDeps(pkg))
if (!seen.has(d)) {
seen.add(d)
walk(d)
}
}
walk(target)
return [...seen].sort()
}
type GateStep = {
id?: string
if?: unknown
uses?: string
run?: string
env?: Record<string, string>
with?: Record<string, string>
"continue-on-error"?: unknown
}
type GateWorkflow = { jobs: Record<string, { outputs?: Record<string, string>; steps?: GateStep[] }> }
const PATHS_FILTER = "dorny/paths-filter@"
/** The extension's build inputs: one file every PR lane loads as a paths-filter source, and its one filter. */
const BUILD_SOURCE = ".github/path-filters/extension-build.yml"
const BUILD_FILTER = "extension-build"
/** The file a paths-filter `filters` value names: the action reads one with no newline and no colon as a path. */
const sourcePath = (filters: unknown): string | undefined => (typeof filters === "string" && !/[\n:]/.test(filters) ? filters : undefined)
/** A filters document by filter name, each list flattened as the action flattens an aliased one. */
function stepFilters(step: GateStep): Record<string, string[]> {
const filters = step.with?.filters ?? ""
const path = sourcePath(filters)
const doc = Bun.YAML.parse(path ? readFileSync(join(ROOT, path), "utf8") : filters) as Record<string, unknown>
return Object.fromEntries(Object.entries(doc).map(([name, patterns]) => [name, [patterns].flat(Infinity) as string[]]))
}
function filterSteps(wf: GateWorkflow): Record<string, GateStep> {
const steps = wf.jobs.changes?.steps ?? []
return Object.fromEntries(steps.filter((step) => step.uses?.includes(PATHS_FILTER)).map((step) => [step.id ?? "", step]))
}
/** The one shape a gate input may take: the dispatch override, else one filter step's output. */
const GATE_INPUT = /^\$\{\{ steps\.override\.outputs\.full \|\| steps\.([\w-]+)\.outputs\.([\w-]+) \}\}$/
/** The `<step>.<filter>` a gate input reads, or undefined when it reads no filter of a paths-filter step. */
function gateFilter(wf: GateWorkflow, value: string): string | undefined {
const [, id, name] = GATE_INPUT.exec(value) ?? []
const step = id === undefined ? undefined : filterSteps(wf)[id]
return step && name in stepFilters(step) ? `${id}.${name}` : undefined
}
function patternsOf(wf: GateWorkflow, names: string[]): string[] {
const steps = filterSteps(wf)
const patterns = names.flatMap((qualified) => {
const [id, name] = qualified.split(".")
return stepFilters(steps[id])[name]
})
return [...new Set(patterns)].sort()
}
const DECIDE_INPUTS = ["BUILD", "SURFACE"]
/** An e2e lane's effective filter: every pattern behind the verdicts its Decide step reads. */
function laneSet(wf: GateWorkflow, label: string): string[] {
const gate = wf.jobs.changes?.steps?.find((step) => step.id === "gate")
const names = DECIDE_INPUTS.map((key) => gateFilter(wf, gate?.env?.[key] ?? ""))
if (names.includes(undefined)) throw new Error(`${label}: a Decide input reads no paths filter`)
return patternsOf(wf, names as string[])
}
/** A gate's pattern set must whole-package the target and src+manifest every transitive dep lib. */
function assertGraphCovered(patterns: string[], target: string, label: string) {
expect(patterns, `${label}: target '${target}' must be whole-package gated`).toContain(`${dirOf(target)}/${target}/**`)
for (const dep of transitiveDeps(target)) {
expect(patterns, `${label}: dep lib '${dep}' src must be gated`).toContain(`packages/${dep}/src/**`)
expect(patterns, `${label}: dep lib '${dep}' package.json must be gated`).toContain(`packages/${dep}/package.json`)
}
}
/** A script's lines that run — comments cannot test a result or decide a gate. */
const commandLines = (run: unknown): string[] =>
String(run ?? "")
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0 && !line.startsWith("#"))
const FILTER_WORKFLOWS = [
"pr-quick.yml",
"pr-extension-smoke-e2e.yml",
"pr-extension-network-e2e.yml",
"pr-extension-smoke-e2e-firefox.yml",
"pr-extension-network-e2e-firefox.yml",
"actionlint.yml",
]
/**
* The check-run each PR workflow's aggregator job produces. Branch protection matches these BY
* NAME (CLAUDE.md § Branching), so a renamed job that isn't repointed there blocks every merge —
* this pin fails first. `required-checks.ts` renames the protection to the same names.
*/
const AGGREGATOR_CHECKS: Record<string, string> = {
"pr-quick.yml": "quality-status",
"pr-extension-smoke-e2e.yml": "extension-smoke-e2e-status",
"pr-extension-network-e2e.yml": "extension-network-e2e-status",
"pr-extension-smoke-e2e-firefox.yml": "extension-smoke-e2e-firefox-status",
"pr-extension-network-e2e-firefox.yml": "extension-network-e2e-firefox-status",
}
/** The four e2e lanes, each with the labels that force it to run (the second an alias). */
const E2E_LANES = {
"pr-extension-smoke-e2e.yml": ["e2e:extension-smoke", "e2e:smoke"],
"pr-extension-smoke-e2e-firefox.yml": ["e2e:extension-smoke", "e2e:smoke"],
"pr-extension-network-e2e.yml": ["e2e:extension-network", "e2e:network"],
"pr-extension-network-e2e-firefox.yml": ["e2e:extension-network", "e2e:network"],
}
/** The gate scripts every e2e lane runs; an edit to one runs the lanes, as an edit to the lane's own YAML does. */
const GATE_SCRIPTS = ["scripts/ci-cd/e2e-decide.sh", "scripts/ci-cd/e2e-aggregate.sh"]
describe("CI aggregator check names", () => {
test("each PR workflow's status job produces its documented check-run name", () => {
for (const [file, name] of Object.entries(AGGREGATOR_CHECKS)) {
// biome-ignore lint/suspicious/noExplicitAny: parsed-YAML shape is dynamic.
const wf = Bun.YAML.parse(readFileSync(join(ROOT, ".github/workflows", file), "utf8")) as any
expect(wf.jobs.status?.name, `${file}: jobs.status.name`).toBe(name)
expect(wf.jobs.status?.if, `${file}: the aggregator must always run`).toBe("always()")
}
})
test("the protection runbook renames onto exactly these names", () => {
for (const target of Object.values(RENAMES)) {
expect(Object.values(AGGREGATOR_CHECKS), `rename target '${target}' must be a produced check`).toContain(target)
}
})
})
// biome-ignore lint/suspicious/noExplicitAny: parsed-YAML shape is dynamic.
const workflowOf = (file: string): any => Bun.YAML.parse(readFileSync(join(ROOT, ".github/workflows", file), "utf8"))
const NETWORK_SUITE = "_extension-network-e2e.yml"
const NETWORK_LANE = "_extension-network-e2e-lane.yml"
/** Nightly's advisory rerun of the canary files on the in-browser prover; it belongs to no lane. */
const WASM_LEG = "network-e2e-canary-wasm"
/** Nightly's advisory run of the rpc failover chaos file at one fixed seed; it belongs to no lane. */
const RPC_CHAOS_LEG = "network-e2e-rpc-chaos"
type CallerJob = {
name?: string
uses?: string
if?: unknown
needs?: unknown
strategy?: { "fail-fast"?: unknown; matrix?: Record<string, unknown> }
with?: Record<string, unknown>
secrets?: unknown
}
/** One run of the network suite: the top-level job it comes from, its name down to the suite's, its inputs. */
type SuiteCall = { job: string; name: string; inputs: Record<string, unknown> }
type Scope = { inputs?: Record<string, unknown>; matrix?: Record<string, unknown> }
/**
* The lane's complementary chaos jobs, the only lane jobs with an `if`, and that `if` evaluated on
* the bound `chaos_seed`. A caller's expression counts as non-empty: nightly's ends in
* `github.run_id`, which never is.
*/
const CHAOS_PAIR: Record<string, { if: string; runs: (seed: unknown) => boolean }> = {
"network-e2e-chaos": { if: "inputs.chaos_seed == ''", runs: (seed) => seed === "" },
"network-e2e-chaos-seeded": { if: "inputs.chaos_seed != ''", runs: (seed) => seed !== "" },
}
const REFERENCE = /\$\{\{ (inputs|matrix)\.(\w+)(?:\.(\w+))? \}\}/g
/**
* Binds each `${{ inputs.<k> }}` and `${{ matrix.<k>[.<f>] }}` of a context the scope defines: a
* value that is one whole reference takes the bound value and its type, a reference inside text
* is spliced in as a string, and every other expression stays opaque text. A key the scope's
* context lacks throws.
*/
function bind(value: unknown, scope: Scope, at: string): unknown {
if (typeof value !== "string") return value
const lookup = (match: string, context: "inputs" | "matrix", key: string, field?: string): unknown => {
const values = scope[context]
if (values === undefined) return match
if (!(key in values)) throw new Error(`${at}: ${match} names nothing in scope`)
const bound = values[key]
if (field === undefined) return bound
if (typeof bound !== "object" || bound === null || !(field in bound)) throw new Error(`${at}: ${match} names nothing in scope`)
return (bound as Record<string, unknown>)[field]
}
const whole = new RegExp(`^${REFERENCE.source}$`).exec(value)
if (whole) return lookup(whole[0], whole[1] as "inputs" | "matrix", whole[2], whole[3])
return value.replace(REFERENCE, (match, context, key, field) => String(lookup(match, context, key, field)))
}
/** A job's matrix legs: one per value of its one literal key, or a single leg without a matrix. */
function legsOf(job: CallerJob, at: string): (Record<string, unknown> | undefined)[] {
const matrix = job.strategy?.matrix
if (matrix === undefined) return [undefined]
const axes = Object.entries(matrix)
if (axes.length !== 1 || !Array.isArray(axes[0][1])) throw new Error(`${at}: the matrix is not one literal key`)
const [key, values] = axes[0]
return values.map((value) => ({ [key]: value }))
}
/**
* The suite calls one job makes: itself when it calls the suite, every job of the lane bound to
* what it hands the lane (an input it omits takes the lane's default) when it calls the lane.
*/
function callsOf(id: string, job: CallerJob, inputs?: Record<string, unknown>, prefix = ""): Omit<SuiteCall, "job">[] {
return legsOf(job, id).flatMap((matrix) => {
const scope = { inputs, matrix }
const name = `${prefix}${String(bind(job.name ?? id, scope, id))}`
const handed = Object.fromEntries(Object.entries(job.with ?? {}).map(([key, value]) => [key, bind(value, scope, id)]))
if (job.uses === `./.github/workflows/${NETWORK_SUITE}`) return [{ name, inputs: handed }]
if (job.uses === `./.github/workflows/${NETWORK_LANE}`) return laneCalls(handed, `${name} / `)
return []
})
}
function laneCalls(handed: Record<string, unknown>, prefix: string): Omit<SuiteCall, "job">[] {
const lane = workflowOf(NETWORK_LANE)
const declared = lane.on.workflow_call.inputs as Record<string, { required?: boolean; default?: unknown }>
for (const key of Object.keys(handed)) if (!(key in declared)) throw new Error(`the lane declares no input ${key}`)
for (const [key, spec] of Object.entries(declared))
if (spec.required && !(key in handed)) throw new Error(`the lane's required input ${key} is not handed`)
const inputs = Object.fromEntries(Object.entries(declared).map(([key, spec]) => [key, key in handed ? handed[key] : spec.default]))
return (Object.entries(lane.jobs) as [string, CallerJob][]).flatMap(([id, job]) => {
if (job.if === undefined) return callsOf(id, job, inputs, prefix)
const pair = CHAOS_PAIR[id]
if (pair?.if !== job.if) throw new Error(`${NETWORK_LANE} → ${id}: an if the expander does not evaluate`)
return pair.runs(inputs.chaos_seed) ? callsOf(id, job, inputs, prefix) : []
})
}
/** Every network suite call a workflow makes, directly or through a lane call. */
const suiteCalls = (file: string): SuiteCall[] =>
(Object.entries(workflowOf(file).jobs) as [string, CallerJob][]).flatMap(([id, job]) =>
callsOf(id, job).map((call) => ({ job: id, ...call })),
)
const PR_DISABLE_PRESTO = "${{ github.event.inputs.disable_presto == 'true' || vars.NULO_E2E_DISABLE_PRESTO == '1' }}"
const NIGHTLY_IF = "always() && needs.resolve.result == 'success' && needs.resolve.outputs.skip != 'true'"
const NIGHTLY_WITH = {
ref: "${{ needs.resolve.outputs.sha }}",
disable_presto: "${{ vars.NULO_E2E_DISABLE_PRESTO == '1' }}",
chaos_seed: "${{ github.event.inputs.chaos_seed || github.run_id }}",
}
/** Every call of the network lane: the caller's job id, name, `needs` and `if` (whitespace folded), and what it hands the lane. */
const LANE_CALLERS = [
{
file: "pr-extension-network-e2e.yml",
job: "network-e2e",
name: "Run",
needs: "changes",
if: "needs.changes.outputs.run == 'true'",
with: { ref: "${{ github.event.pull_request.head.sha || github.ref }}", retry: "0", disable_presto: PR_DISABLE_PRESTO },
},
{
file: "pr-extension-network-e2e-firefox.yml",
job: "network-e2e",
name: "Run",
needs: "changes",
if: "needs.changes.outputs.run == 'true'",
with: {
ref: "${{ github.event.pull_request.head.sha || github.ref }}",
browser: "firefox",
retry: "0",
disable_presto: PR_DISABLE_PRESTO,
},
},
{ file: "nightly.yml", job: "network-e2e", name: "Run", needs: "resolve", if: NIGHTLY_IF, with: NIGHTLY_WITH },
{
file: "nightly.yml",
job: "network-e2e-firefox",
name: "Firefox / Run",
needs: "resolve",
if: NIGHTLY_IF,
with: { ...NIGHTLY_WITH, browser: "firefox" },
},
{
file: "release.yml",
job: "network-e2e",
name: "Run",
needs: "resolve",
if: "always() && needs.resolve.result == 'success' && github.event.inputs.run_network_e2e == 'true'",
with: { ref: "${{ needs.resolve.outputs.sha }}", retry: "0", disable_presto: "${{ vars.NULO_E2E_DISABLE_PRESTO == '1' }}" },
},
] as const
const foldSpace = (text: unknown): string => String(text).split(/\s+/).join(" ").trim()
/**
* verify-cert-run.sh certifies a head only when every network suite job ran green, matched by its
* full name: the caller's job name, the lane's, then the suite's. A rename at any level that the
* script does not follow fails every certification, so its list is derived here from the workflows.
*/
describe("network suite job names", () => {
const PR_LANE = "pr-extension-network-e2e.yml"
const LEAF = "network suite"
const leaf = (shard: unknown): string => (shard ? `${LEAF} (shard ${shard})` : LEAF)
test("the reusable workflow's job is the network suite, named with its shard when it has one", () => {
expect(workflowOf(NETWORK_SUITE).jobs["network-e2e"].name).toBe(
`\${{ inputs.shard && format('${LEAF} (shard {0})', inputs.shard) || '${LEAF}' }}`,
)
})
test("verify-cert-run.sh expects exactly the jobs the PR lane's network workflow produces", () => {
const produced = suiteCalls(PR_LANE).map(({ name, inputs }) => `${name} / ${leaf(inputs.shard)}`)
const script = readFileSync(join(ROOT, "scripts/ci-cd/verify-cert-run.sh"), "utf8")
const block = /^EXPECTED_NETWORK_JOBS=\(\n([\s\S]*?)\n\)$/m.exec(script)?.[1]
expect(block, "verify-cert-run.sh declares EXPECTED_NETWORK_JOBS").toBeDefined()
const expected = String(block)
.split("\n")
.map((line) => line.trim().replace(/^"(.*)"$/, "$1"))
.filter(Boolean)
expect(produced.length, "the PR lane calls the suite").toBeGreaterThan(0)
expect([...expected].sort()).toEqual([...produced].sort())
expect(script, "the list is checked against the PR lane's runs").toContain(`if [ "$WF" = "${workflowOf(PR_LANE).name}" ]; then`)
})
test("verify-cert-run.sh's workload jobs are the names Quality and smoke produce, every leg of each", () => {
type Shard = string | { id: string } | undefined
type Job = { name: string; uses?: string; strategy?: { matrix?: { shard?: Shard[] } } }
const legs = (job: Job, name: string): string[] =>
(job.strategy?.matrix?.shard ?? [undefined]).map((shard) =>
typeof shard === "object"
? name.replace("${{ matrix.shard.id }}", shard.id)
: name.replace("${{ matrix.shard }}", String(shard)),
)
const produced = (file: string, jobs: string[]): string[] =>
jobs.flatMap((key) => {
const caller: Job = workflowOf(file).jobs[key]
const called = Object.values(workflowOf(String(caller.uses).replace("./.github/workflows/", "")).jobs) as Job[]
expect(called, `${file} → ${key} calls a one-job workflow`).toHaveLength(1)
return legs(caller, caller.name).flatMap((outer) => legs(called[0], called[0].name).map((inner) => `${outer} / ${inner}`))
})
const script = readFileSync(join(ROOT, "scripts/ci-cd/verify-cert-run.sh"), "utf8")
const required = (workflow: string): string[] =>
String(new RegExp(`^\\t\\["${workflow}"\\]="(.+)"$`, "m").exec(script)?.[1])
.split("|")
.sort()
expect(required(workflowOf("pr-quick.yml").name)).toEqual(produced("pr-quick.yml", ["unit-tests", "lint-and-typecheck"]).sort())
expect(required(workflowOf("pr-extension-smoke-e2e.yml").name)).toEqual(produced("pr-extension-smoke-e2e.yml", ["smoke"]).sort())
})
})
/** gh 2.103 and later refuse every coloured job log without the flag, so certification never passes. */
describe("verify-cert-run.sh job logs", () => {
test("the log fetch passes --allow-escape-sequences when this gh's help lists it", () => {
const script = readFileSync(join(ROOT, "scripts/ci-cd/verify-cert-run.sh"), "utf8")
expect(script).toContain('case "$(gh api --help 2>&1)" in\n\t*--allow-escape-sequences*) LOG_ESCAPES=--allow-escape-sequences ;;')
expect(script).toContain('gh api ${LOG_ESCAPES:+"$LOG_ESCAPES"} "repos/$REPO/actions/jobs/$JOB_ID/logs" >"$L"')
})
})
describe("commitlint", () => {
const step = workflowOf("pr-quick.yml").jobs.commitlint.steps.find((s: { name?: string }) => s.name === "Lint PR commits")
// A failing lint, so a PR that reaches it goes red and one that skips it stays green.
const LOG_AND_FAIL = `#!/bin/sh\necho "$(basename "$0") $*" >> "$(dirname "$0")/calls"\nexit 1\n`
const run = (base: string, head: string, author: string) =>
runStep(step, {
shim: LOG_AND_FAIL,
bound: {
"${{ github.base_ref }}": base,
"${{ github.head_ref }}": head,
"${{ github.event.pull_request.base.sha }}": "base-sha",
"${{ github.event.pull_request.head.sha }}": "head-sha",
"${{ github.event.pull_request.user.login }}": author,
},
setup: (dir) => {
writeFileSync(join(dir, "bunx"), LOG_AND_FAIL)
chmodSync(join(dir, "bunx"), 0o755)
},
})
test.each([
["a human's PR into dev", "dev", "feat/x", "alice"],
["a human's PR from a branch named like Dependabot's", "dev", "dependabot/github_actions/actions-1", "alice"],
])("%s lints every commit in base..head", (_, base, head, author) => {
const { code, calls } = run(base, head, author)
expect(calls).toEqual(["bunx commitlint --from base-sha --to head-sha --verbose"])
expect(code).toBe(1)
})
test.each([
["Dependabot's PR", "dev", "dependabot/github_actions/actions-1", "dependabot[bot]"],
["a PR into main", "main", "dev", "alice"],
["the main → dev sync PR", "dev", "sync/main-to-dev-1.2.0", "nulo-release[bot]"],
])("%s is not linted", (_, base, head, author) => {
const { code, calls } = run(base, head, author)
expect(calls).toEqual([])
expect(code).toBe(0)
})
})
describe("PR concurrency", () => {
// biome-ignore lint/suspicious/noExplicitAny: parsed-YAML shape is dynamic.
const workflow = (file: string): any => Bun.YAML.parse(readFileSync(join(ROOT, ".github/workflows", file), "utf8"))
const PR_WORKFLOWS = [...Object.keys(AGGREGATOR_CHECKS), "actionlint.yml"]
const workflowFiles = (): string[] =>
readdirSync(join(ROOT, ".github/workflows"))
.filter((name) => name.endsWith(".yml"))
.sort()
// The number keeps same-named branches of two forks apart; the head commit keeps two heads of one
// pull request apart, so a late run of an older push can neither cancel nor replace the current
// head's run, whatever order GitHub admits them in.
test("each PR workflow queues per pull request and head commit, and only a dispatch cancels", () => {
for (const file of PR_WORKFLOWS) {
const { group, "cancel-in-progress": cancel } = workflow(file).concurrency ?? {}
expect(String(group), `${file}: concurrency.group`).toEndWith(
"-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ github.event.pull_request.head.sha || github.sha }}",
)
expect(String(group), `${file}: concurrency.group`).not.toContain("head_ref")
expect(cancel, `${file}: concurrency.cancel-in-progress`).toBe("${{ github.event_name != 'pull_request' }}")
}
})
// One of the two jobs in the repository that may cancel runs: it runs nothing it fetched, reads every
// input from env, and skips the tokens that could not cancel anyway.
test("pr-supersede.yml cancels from one script-only job with exactly the scope it needs", () => {
const wf = workflow("pr-supersede.yml")
expect(wf.on).toEqual({ pull_request: { types: ["synchronize"] } })
expect(wf.permissions).toEqual({})
expect(Object.keys(wf.jobs)).toEqual(["cancel-superseded"])
const job = wf.jobs["cancel-superseded"]
expect(job.permissions).toEqual({ actions: "write", "pull-requests": "read" })
expect(job.if).toBe("github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]'")
// A shared group would let a late-admitted older sweep cancel the newer one.
expect(wf.concurrency).toBeUndefined()
expect(job.concurrency).toBeUndefined()
expect(job.steps).toHaveLength(1)
const [step] = job.steps
expect(step.uses).toBeUndefined()
expect(step.run).not.toContain("${{")
const listed = /WORKFLOWS=\(\n([\s\S]*?)\n\s*\)/.exec(step.run)?.[1]
expect(
String(listed)
.split("\n")
.map((line) => line.trim())
.sort(),
).toEqual(PR_WORKFLOWS.map((file) => `.github/workflows/${file}`).sort())
})
test("pr-retarget.yml re-runs the e2e lanes from one script-only job with exactly the scope it needs", () => {
const wf = workflow("pr-retarget.yml")
expect(wf.on).toEqual({ pull_request: { types: ["edited"] } })
expect(wf.permissions).toEqual({})
expect(Object.keys(wf.jobs)).toEqual(["rerun-e2e"])
const job = wf.jobs["rerun-e2e"]
expect(job.permissions).toEqual({ actions: "write" })
expect(job.if).toBe(
"github.event.changes.base && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]'",
)
// A concurrency group would let a title edit's run replace a waiting retarget run.
expect(wf.concurrency).toBeUndefined()
expect(job.concurrency).toBeUndefined()
expect(job.steps).toHaveLength(1)
const [step] = job.steps
expect(step.uses).toBeUndefined()
expect(step.run).not.toContain("${{")
const listed = /WORKFLOWS=\(\n([\s\S]*?)\n\s*\)/.exec(step.run)?.[1]
expect(
String(listed)
.split("\n")
.map((line) => line.trim())
.sort(),
).toEqual(Object.keys(E2E_LANES).sort())
})
// Every title or body edit fires `edited` as well, so a lane listening to it would re-run its
// suites on each one.
test("only pr-retarget.yml subscribes to `edited`", () => {
const listeners = workflowFiles().filter((file) => {
const on = workflow(file).on
return ["pull_request", "pull_request_target"].some((event) => on?.[event]?.types?.includes("edited"))
})
expect(listeners).toEqual(["pr-retarget.yml"])
})
test("no other workflow can cancel or re-run a run", () => {
const writers = workflowFiles().filter((file) => {
const wf = workflow(file)
const scopes = [wf.permissions, ...Object.values(wf.jobs ?? {}).map((job) => (job as { permissions?: unknown }).permissions)]
return scopes.some(
(scope) =>
scope === "write-all" ||
(typeof scope === "object" &&
scope !== null &&
"actions" in scope &&
(scope as Record<string, unknown>).actions === "write"),
)
})
expect(writers).toEqual(["pr-retarget.yml", "pr-supersede.yml"])
})
})
/**
* Each e2e lane decides from the labels the pull request carries when its `changes` job runs, and
* the complexity ratchet from those it carries when the unit-tests job runs. An event's own label
* list is a snapshot that a late run of an older event would decide from, so no workflow or action
* may read it, and a run whose head the pull request has moved past stops itself.
*/
describe("live labels", () => {
// biome-ignore lint/suspicious/noExplicitAny: parsed-YAML shape is dynamic.
const workflow = (file: string): any => Bun.YAML.parse(readFileSync(join(ROOT, ".github/workflows", file), "utf8"))
const SCRIPT = "bash scripts/ci-cd/live-labels.sh"
const snapshotReads = (text: string): string[] =>
text.split("\n").filter((line) => /github\.event\.(pull_request\.labels|label)\b/.test(line))
const ciFiles = (): string[] =>
[".github/workflows", ".github/actions"].flatMap((dir) =>
(readdirSync(join(ROOT, dir), { recursive: true }) as string[])
.filter((name) => /\.ya?ml$/.test(name))
.map((name) => join(dir, name)),
)
test("no workflow or action reads an event's label snapshot", () => {
const planted = " LABEL_HIT: ${{ contains(github.event.pull_request.labels.*.name, 'e2e:smoke') }}"
expect(snapshotReads(`run: echo\n${planted}`)).toEqual([planted])
const files = ciFiles()
expect(files.length).toBeGreaterThan(10)
for (const file of files) expect(snapshotReads(readFileSync(join(ROOT, file), "utf8")), file).toEqual([])
})
test("every lane reads its own two labels live and decides from that output alone", () => {
for (const [file, labels] of Object.entries(E2E_LANES)) {
const { changes } = workflow(file).jobs
const live = changes.steps.find((step: { id?: string }) => step.id === "live")
expect(live?.run, file).toBe(`${SCRIPT} ${labels.join(" ")}`)
expect(live?.if, `${file}: runs on every event`).toBeUndefined()
expect(live?.["continue-on-error"], file).toBeUndefined()
expect(live?.env, file).toEqual({
GH_TOKEN: "${{ github.token }}",
EVENT: "${{ github.event_name }}",
REPO: "${{ github.repository }}",
PR: "${{ github.event.pull_request.number }}",
HEAD_SHA: "${{ github.event.pull_request.head.sha }}",
})
expect(changes.outputs, `${file}: the gate's verdict and the attempt it read in, with no fallback`).toEqual({
run: "${{ steps.gate.outputs.run }}",
"read-attempt": "${{ steps.live.outputs.read-attempt }}",
})
// The gate is the last step, so it reads the live labels, both filters and the dispatch override.
const steps = filterSteps(workflow(file))
expect(Object.keys(steps), `${file}: the shared build inputs, then the lane's own filter`).toEqual(["build", "filter"])
const [surface, ...others] = Object.keys(stepFilters(steps.filter))
expect(others, `${file}: one lane filter`).toEqual([])
const gate = changes.steps.at(-1)
expect(gate, `${file}: the gate step`).toEqual({
name: "Decide",
id: "gate",
env: {
EVENT: "${{ github.event_name }}",
BASE: "${{ steps.live.outputs.base }}",
LABEL_HIT: "${{ steps.live.outputs.label-hit }}",
BUILD: `\${{ steps.override.outputs.full || steps.build.outputs.${BUILD_FILTER} }}`,
SURFACE: `\${{ steps.override.outputs.full || steps.filter.outputs.${surface} }}`,
},
run: "bash scripts/ci-cd/e2e-decide.sh",
})
expect(workflow(file).jobs.decide, `${file}: no separate decide job`).toBeUndefined()
}
})
test("the unit-tests job reads the move-approval label live, directly before the ratchet runs", () => {
const { steps } = workflow("_unit-tests.yml").jobs["unit-tests"]
const at = steps.findIndex((step: { id?: string }) => step.id === "live")
const live = steps[at]
expect(live?.run).toBe(
[
"if [ -f scripts/ci-cd/live-labels.sh ]; then",
` ${SCRIPT} ${MOVE_APPROVED_LABEL}`,
"else",
' echo "scripts/ci-cd/live-labels.sh not present on this ref — skipping."',
"fi",
"",
].join("\n"),
)
expect(live.if).toBe("matrix.shard == '3/3' && github.event_name == 'pull_request'")
expect(live["continue-on-error"]).toBeUndefined()
expect(live.env).toEqual({
GH_TOKEN: "${{ github.token }}",
EVENT: "${{ github.event_name }}",
REPO: "${{ github.repository }}",
PR: "${{ github.event.pull_request.number }}",
HEAD_SHA: "${{ github.event.pull_request.head.sha }}",
})
const ratchet = steps[at + 1]
expect(ratchet.run).toContain("bun run test:ci-gating")
expect(ratchet.if).toBe("matrix.shard == '3/3'")
expect(ratchet.env).toEqual({ BASELINE_MOVE_APPROVED: "${{ steps.live.outputs.label-hit }}" })
const quick = workflow("pr-quick.yml")
expect(quick.jobs["unit-tests"].uses).toBe("./.github/workflows/_unit-tests.yml")
expect((quick.jobs["unit-tests"].permissions ?? quick.permissions)["pull-requests"]).toBe("read")
})
/**
* Runs the live step's script under a `gh` that records its calls and answers with `bodies` in
* order (the last one repeats), or fails with `failure`.
*/
function runLive(args: string[], env: Record<string, string>, gh: { bodies?: unknown[]; failure?: string }) {
const dir = mkdtempSync(join(tmpdir(), "live-labels-"))
try {
const log = join(dir, "calls")
const output = join(dir, "output")
const bodies = gh.bodies ?? [{}]
for (const [i, body] of bodies.entries()) writeFileSync(join(dir, `body-${i + 1}.json`), JSON.stringify(body))
writeFileSync(log, "")
writeFileSync(output, "")
const shim = gh.failure
? `echo "$*" >> "${log}"; echo "gh: ${gh.failure}" >&2; exit 1`
: `echo "$*" >> "${log}"; n=$(wc -l < "${log}"); [ "$n" -gt ${bodies.length} ] && n=${bodies.length}; cat "${dir}/body-$n.json"`
writeFileSync(join(dir, "gh"), `#!/usr/bin/env bash\n${shim}\n`)
chmodSync(join(dir, "gh"), 0o755)
const run = Bun.spawnSync(["bash", "scripts/ci-cd/live-labels.sh", ...args], {
cwd: ROOT,
env: { PATH: `${dir}:${process.env.PATH}`, GITHUB_OUTPUT: output, GITHUB_RUN_ATTEMPT: "2", RETRY_PAUSE: "0", ...env },
})
return {
code: run.exitCode,
stdout: run.stdout.toString(),
output: readFileSync(output, "utf8").trim(),
calls: readFileSync(log, "utf8").split("\n").filter(Boolean),
}
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
const HEAD = "a".repeat(40)
const pr = { EVENT: "pull_request", REPO: "nulo-sh/nulo", PR: "7", HEAD_SHA: HEAD, GH_TOKEN: "t" }
const body = (labels: string[], head = HEAD) => ({
head: { sha: head },
base: { ref: "main" },
labels: labels.map((name) => ({ name })),
})
const outputs = (hit: boolean, base: string) => `label-hit=${hit}\nbase=${base}\nread-attempt=2`
test.each(Object.entries(E2E_LANES))("%s: the live labels and base decide, read once from the pull request", (_, labels) => {
const alias = runLive(labels, pr, { bodies: [body(["docs", labels[1]])] })
expect([alias.code, alias.output, alias.calls]).toEqual([0, outputs(true, "main"), ["api repos/nulo-sh/nulo/pulls/7"]])
const unrelated = runLive(labels, pr, { bodies: [body(["docs", "e2e:other"])] })
expect([unrelated.code, unrelated.output]).toEqual([0, outputs(false, "main")])
const dispatch = runLive(labels, { ...pr, EVENT: "workflow_dispatch", PR: "", HEAD_SHA: "" }, { failure: "unused" })
expect([dispatch.code, dispatch.output, dispatch.calls]).toEqual([0, outputs(false, ""), []])
})
test("a run whose head the pull request moved past stops, whatever its labels, after one late read", () => {
const labels = E2E_LANES["pr-extension-smoke-e2e.yml"]
const moved = runLive(labels, pr, { bodies: [body(["e2e:smoke"], "b".repeat(40))] })
expect([moved.code === 0, moved.output, moved.calls.length]).toEqual([false, "", 2])
expect(moved.stdout).toContain(`superseded by ${"b".repeat(40)}`)
const lagging = runLive(labels, pr, { bodies: [body([], "c".repeat(40)), body(["e2e:smoke"])] })
expect([lagging.code, lagging.output, lagging.calls.length], "an endpoint that trailed the push").toEqual([
0,
outputs(true, "main"),
2,
])
})
test("an unreadable pull request fails closed: one retry for a rate limit or server error, none for a refusal", () => {
const labels = E2E_LANES["pr-extension-network-e2e.yml"]
for (const failure of ["API rate limit exceeded (HTTP 403)", "HTTP 502: Bad Gateway", "connection reset by peer"]) {
const run = runLive(labels, pr, { failure })
expect([run.code === 0, run.output, run.calls.length], failure).toEqual([false, "", 2])
}
const missing = runLive(labels, pr, { failure: "Not Found (HTTP 404)" })
expect([missing.code === 0, missing.output, missing.calls.length]).toEqual([false, "", 1])
for (const malformed of [
{ head: { sha: HEAD }, base: { ref: "dev" } },
{ head: { sha: HEAD }, labels: [] },
]) {
const run = runLive(labels, pr, { bodies: [malformed] })
expect([run.code === 0, run.output], JSON.stringify(malformed)).toEqual([false, ""])
}
})
})
describe("CI behavior-gating guard", () => {
const quickWorkflow: GateWorkflow = workflowOf("pr-quick.yml")
const quick = stepFilters(filterSteps(quickWorkflow).filter)
test("NO `!` negation patterns anywhere (the dorny some-quantifier footgun)", () => {
for (const wf of FILTER_WORKFLOWS) {
const steps = Object.entries(filterSteps(workflowOf(wf)))
expect(steps.length, wf).toBeGreaterThan(0)
for (const [id, step] of steps) {
for (const [name, pats] of Object.entries(stepFilters(step))) {
for (const p of pats) {
expect(p.startsWith("!"), `${wf} → filter '${id}.${name}' has a forbidden negation: ${p}`).toBe(false)
}
}
}
}
})
test("a notices-generator change rebuilds both targets, and every build asserts the file shipped", () => {
const inputs = ["src/**", "package.json", "texts/**", "bin/**", "expected-minimum.txt"].map(
(path) => `packages/third-party-notices/${path}`,
)
// Beyond src + manifest: the licence texts and the expected-minimum list are build inputs too.
const extensionBuild = patternsOf(quickWorkflow, extensionBuildFilters(quickWorkflow).filters)
for (const input of inputs) {
expect(extensionBuild, `extension build: ${input}`).toContain(input)
}
// biome-ignore lint/suspicious/noExplicitAny: parsed-YAML shape is dynamic.
const wf = Bun.YAML.parse(readFileSync(join(ROOT, ".github/workflows/_build-extension.yml"), "utf8")) as any
const steps: { name?: string; run?: string }[] = wf.jobs.build.steps
const assertion = steps.findIndex((step) => step.run?.includes("third-party-notices/bin/check-minimum.ts"))
const firstUpload = steps.findIndex((step) => step.name?.startsWith("Upload"))
expect(assertion, "the assertion step exists").toBeGreaterThan(-1)
expect(assertion, "an artifact without notices is never uploaded").toBeLessThan(firstUpload)
})
test("an extension build builds both targets, so the preview comment links both", () => {
// biome-ignore lint/suspicious/noExplicitAny: parsed-YAML shape is dynamic.
const wf = Bun.YAML.parse(readFileSync(join(ROOT, ".github/workflows/pr-quick.yml"), "utf8")) as any
expect(wf.jobs["build-chrome"].if).toBe("needs.changes.outputs.needs-extension-build == 'true'")
expect(wf.jobs["build-firefox"].if).toBe(wf.jobs["build-chrome"].if)
})
test("Storybook builds wherever the extension does, and reports nothing to Storybook", () => {
// biome-ignore lint/suspicious/noExplicitAny: parsed-YAML shape is dynamic.
const wf = Bun.YAML.parse(readFileSync(join(ROOT, ".github/workflows/pr-quick.yml"), "utf8")) as any
const job = wf.jobs["build-storybook"]
expect(job.if).toBe(wf.jobs["build-chrome"].if)
const build = job.steps.find((step: { run?: string }) => step.run?.includes("build-storybook"))
expect(build?.env?.STORYBOOK_DISABLE_TELEMETRY).toBe("1")
})
test("every pull request into main runs the launch check with its live assertion switched on", () => {
// biome-ignore lint/suspicious/noExplicitAny: parsed-YAML shape is dynamic.
const wf = Bun.YAML.parse(readFileSync(join(ROOT, ".github/workflows/pr-quick.yml"), "utf8")) as any
const job = wf.jobs["launch-legal"]
expect(job.if).toBe("github.event_name == 'pull_request' && github.base_ref == 'main'")
const check = job.steps.find((step: { run?: string }) => step.run?.includes("launch.test.ts"))
expect(check?.["working-directory"]).toBe("packages/legal")
expect(check?.env?.NULO_LAUNCH_GATE, "without it the live assertion skips and the job passes").toBe("1")
expect(readFileSync(join(ROOT, "packages/legal/src/launch.test.ts"), "utf8")).toContain("process.env.NULO_LAUNCH_GATE")
const notice = job.steps.find((step: { run?: string }) => step.run?.includes("legal-pages.test.ts"))
expect(notice?.["working-directory"]).toBe("apps/landing")
expect(notice?.env?.NULO_LAUNCH_GATE, "the website notice is outside the wallet's launch check").toBe("1")
const notes = job.steps.find((step: { run?: string }) => step.run?.includes("release-notes-run.ts"))
expect(notes?.run, "the Release PR cannot merge without its release notes").toBe("bun scripts/release/release-notes-run.ts check")
expect(notes?.["working-directory"], "the check reads the root package.json").toBeUndefined()
expect(readFileSync(join(ROOT, "apps/landing/scripts/legal-pages.test.ts"), "utf8")).toContain("process.env.NULO_LAUNCH_GATE")
expect(wf.jobs.status.needs).toContain("launch-legal")
})
test("landing build covers the landing graph and the documents it renders, and is wired into the aggregator", () => {
assertGraphCovered(quick.landing, "landing", "landing")
expect(quick.landing, "a Terms edit must rebuild the pages generated from it").toContain("legal/**")
expect(quick.landing, "a release-notes edit must rebuild the changelog generated from it").toContain("release-notes/**")
// biome-ignore lint/suspicious/noExplicitAny: parsed-YAML shape is dynamic.
const wf = Bun.YAML.parse(readFileSync(join(ROOT, ".github/workflows/pr-quick.yml"), "utf8")) as any
expect(wf.jobs["build-landing"].if).toContain("needs-landing-build")
expect(wf.jobs.changes.outputs["needs-landing-build"]).toBeDefined()
expect(wf.jobs.status.needs, "a red landing build must red quality-status").toContain("build-landing")
expect(JSON.stringify(wf.jobs.status.steps)).toContain("needs.build-landing.result")
})
// The repo-wide inputs also sit in the shared extension source, so a root-config that lost one
// would still build the extension and skip only the landing.
test("the landing builds on every repo-wide build input", () => {
const landingBuild = patternsOf(quickWorkflow, buildFilters(quickWorkflow, LANDING_FLAG).filters)
for (const input of REPO_WIDE_INPUTS) expect(landingBuild, input).toContain(input)
})
// The shard pool / dedicated-job partition of the network suite is pinned on the lane under
// "network lane" below.
// The self-pay phase gate — the wallet simulating and sending as the account a dApp names,
// with the node's setup allow-list enforced — must keep running on every PR: the matrix in a
// dedicated heavy job at retry 0 (a retry would re-mask an intermittent wallet regression),
// the cheap two-account simulate in the shard pool (never excluded, so it cannot drop out).
test("network-e2e keeps the self-pay phase gate in place at retry 0", () => {
const words = (v: unknown): string[] => (typeof v === "string" ? v.split(/\s+/).filter(Boolean) : [])
const calls = suiteCalls("pr-extension-network-e2e.yml")
const matrix = calls.filter(({ inputs }) => words(inputs.test_files).includes("tests/e2e/network/selfpay-phase.test.ts"))
expect(
matrix.map(({ inputs }) => [inputs.retry, inputs.proverless]),
"selfpay-phase runs in one dedicated job, proverless like the other heavy fee flows, at retry 0",
).toEqual([["0", true]])
const pool = calls.filter(({ inputs }) => inputs.exclude_files)
expect(pool.length, "the shard pool").toBeGreaterThan(0)
for (const { name, inputs } of pool) {
expect(words(inputs.exclude_files), `${name}: sim-from-selfpay stays in the shard pool`).not.toContain(
"tests/e2e/network/sim-from-selfpay.test.ts",
)
expect(inputs.retry, `${name} runs at retry 0`).toBe("0")
}
expect(existsSync(join(ROOT, "apps/extension/tests/e2e/network/sim-from-selfpay.test.ts")), "sim-from-selfpay exists").toBe(true)
expect(existsSync(join(ROOT, "apps/extension/tests/e2e/network/selfpay-phase.test.ts")), "selfpay-phase exists").toBe(true)
})
test("both reusable suites take their retry count from one input, empty by default, as NULO_E2E_RETRY", () => {
// biome-ignore lint/suspicious/noExplicitAny: parsed-YAML shape is dynamic.
const reusable = (file: string): any => Bun.YAML.parse(readFileSync(join(ROOT, ".github/workflows", file), "utf8"))
const smoke = reusable("_extension-smoke-e2e.yml")
const network = reusable("_extension-network-e2e.yml")
for (const wf of [smoke, network]) expect(wf.on.workflow_call.inputs.retry).toMatchObject({ type: "string", default: "" })
// biome-ignore lint/suspicious/noExplicitAny: parsed-YAML shape is dynamic.
const run = smoke.jobs.smoke.steps.find((step: any) => step.name === "Run smoke e2e")
expect(run.env.NULO_E2E_RETRY).toBe("${{ inputs.retry }}")
expect(network.jobs["network-e2e"].env.NULO_E2E_RETRY).toBe("${{ inputs.retry }}")
})
})
const NO_GH = "#!/bin/sh\nexit 1\n"
const EXTENSION_FLAG = "needs-extension-build"
const LANDING_FLAG = "needs-landing-build"
/** Runs pr-quick's compute step with each input bound to `true` when `on` names it, else `false`, then `overrides`. */
function runCompute(step: GateStep, on?: string, overrides: Record<string, string> = {}): { code: number; writes: string[] } {
const dir = mkdtempSync(join(tmpdir(), "compute-"))
try {
const output = join(dir, "output")
writeFileSync(output, "")
const env = step.env ?? {}
const bound = Object.fromEntries(Object.entries(env).map(([key, value]) => [value, String(key === on)]))
const run = runStep({ run: step.run ?? "", env }, { shim: NO_GH, bound, overrides: { ...overrides, GITHUB_OUTPUT: output } })
return { code: run.code, writes: readFileSync(output, "utf8").split("\n") }
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
/**
* What pr-quick's compute step, given only `on` true (no input, for `undefined`), sets `flag` to.
* `undefined` unless it writes the flag exactly once, as a boolean: the runner keeps the last write.
*/
function computeFlag(step: GateStep, flag: string, on?: string): "true" | "false" | undefined {
const { code, writes } = runCompute(step, on)
if (code !== 0) throw new Error("compute step failed")
const values = writes.filter((line) => line.startsWith(`${flag}=`)).map((line) => line.slice(flag.length + 1))
const value = values.length === 1 ? values[0] : undefined
return value === "true" || value === "false" ? value : undefined
}
/** The compute step must always run, and the job must publish its flag as the one the builds read. */
function computeWiringFindings(wf: GateWorkflow, step: GateStep, flag: string): string[] {
const published = wf.jobs.changes.outputs?.[flag]
return [
...(step.id === "compute" ? [] : ["no compute step in the changes job"]),
...(step.if === undefined ? [] : [`the compute step runs only if ${step.if}`]),
...(published === `\${{ steps.compute.outputs.${flag} }}` ? [] : [`changes publishes the flag as ${published}`]),
]
}
/**
* The `<step>.<filter>` names whose change sets pr-quick's `flag`, read off its compute step by
* running it with each input alone true. An input in any other shape is refused: bound to a plain
* boolean, it would credit a filter the real expression might not pass on.
*/
function buildFilters(wf: GateWorkflow, flag: string): { filters: string[]; findings: string[] } {
const step = wf.jobs.changes.steps?.find((candidate) => candidate.id === "compute") ?? {}
const inputs = Object.entries(step.env ?? {}).map(([key, value]) => ({ key, value, name: gateFilter(wf, value) }))
const findings = [
...computeWiringFindings(wf, step, flag),
...inputs
.filter(({ name }) => name === undefined)
.map(({ key, value }) => `compute input ${key} reads ${value}, not the override or one defined filter`),
]
if (findings.length > 0) return { filters: [], findings }
const probes = [undefined, ...inputs.map(({ key }) => key)].map((on) => ({ on, value: computeFlag(step, flag, on) }))
findings.push(
...probes.filter(({ value }) => value === undefined).map(({ on }) => `with ${on ?? "no input"} true, the flag is not one boolean`),
)
if (probes[0].value === "true") findings.push(`the compute step sets ${flag} with every input false`)
const builds = new Set(probes.filter(({ value }) => value === "true").map(({ on }) => on))
return { filters: inputs.filter(({ key }) => builds.has(key)).map(({ name }) => name ?? ""), findings }
}
const extensionBuildFilters = (wf: GateWorkflow) => buildFilters(wf, EXTENSION_FLAG)
const QUICK = "pr-quick.yml"
const [SMOKE, SMOKE_FIREFOX, NETWORK, NETWORK_FIREFOX] = [
"pr-extension-smoke-e2e.yml",
"pr-extension-smoke-e2e-firefox.yml",
"pr-extension-network-e2e.yml",
"pr-extension-network-e2e-firefox.yml",
]
/**
* Entries naming the CI files a lane runs differ by lane by design and stay out of the comparison;
* "each e2e lane's filter names the CI files it runs" derives them instead.
*/
const LANE_INFRASTRUCTURE = /^(\.github|scripts\/ci-cd)\//
const PR_QUICK_ROOT_CONFIG = "root config that no build reads; pr-quick's `root-config` filter is one net over the root files"
const POST_BUILD_CHECK = "read only by `_build-extension.yml`'s post-build check, and on a pull request only pr-quick's builds run it"
/** The build-surface patterns that only some PR lanes hold: which ones, and why. */
const SURFACE_EXCEPTIONS: Record<string, { holders: string[]; reason: string }> = {
"packages/third-party-notices/bin/**": { holders: [QUICK], reason: POST_BUILD_CHECK },
"packages/third-party-notices/expected-minimum.txt": { holders: [QUICK], reason: POST_BUILD_CHECK },
"biome.json": { holders: [QUICK], reason: PR_QUICK_ROOT_CONFIG },
".commitlintrc.json": { holders: [QUICK], reason: PR_QUICK_ROOT_CONFIG },
".githooks/**": { holders: [QUICK], reason: PR_QUICK_ROOT_CONFIG },
"apps/playground/**": { holders: [NETWORK, NETWORK_FIREFOX], reason: "the dApp the network suite drives" },
}
/** Every build reads these, and no package graph names them. */
const REPO_WIDE_INPUTS = ["package.json", "bun.lock", "bunfig.toml", "tsconfig.json", "tsconfig.base.json", "patches/**"]
/** The licence texts every extension build reads: a library's one consumed input outside its src and manifest. */
const NOTICE_TEXTS = "packages/third-party-notices/texts/**"
/** The extension's build surface as its graph gives it: the target whole, each library it builds from by src and manifest, and the inputs no graph names. */
function derivedSurface(): string[] {
const libraries = transitiveDeps("extension").flatMap((dep) => [`packages/${dep}/src/**`, `packages/${dep}/package.json`])
return ["apps/extension/**", ...libraries, NOTICE_TEXTS, ...REPO_WIDE_INPUTS].sort()
}
/** Each PR lane's build surface: the patterns that start its extension build, lane infrastructure aside. */
function buildSurfaces(quick: GateWorkflow): Record<string, string[]> {
const surfaceOf = (patterns: string[]) => patterns.filter((pattern) => !LANE_INFRASTRUCTURE.test(pattern))
const lanes = [SMOKE, SMOKE_FIREFOX, NETWORK, NETWORK_FIREFOX].map((file) => [file, surfaceOf(laneSet(workflowOf(file), file))])
return {
[QUICK]: surfaceOf(patternsOf(quick, extensionBuildFilters(quick).filters)),
...Object.fromEntries(lanes),
}
}
/** Every pattern not held by exactly its exception's lanes, else by every lane when derived and by none when not. */
function surfaceFindings(surfaces: Record<string, string[]>, exceptions = SURFACE_EXCEPTIONS, derived = derivedSurface()): string[] {
const lanes = Object.keys(surfaces)
const patterns = new Set([...Object.values(surfaces).flat(), ...Object.keys(exceptions), ...derived])
return [...patterns].flatMap((pattern) => {
const held = lanes.filter((lane) => surfaces[lane].includes(pattern))
const expected = exceptions[pattern]?.holders ?? (derived.includes(pattern) ? lanes : [])
const agree = held.length === expected.length && expected.every((lane) => held.includes(lane))
return agree ? [] : [`${pattern}: held by ${held.join(", ") || "no lane"}; expected ${expected.join(", ") || "no lane"}`]
})
}
/** Every paths-filter step's `ref`; on `pull_request` the action ignores it and lists the PR's files. */
const FILTER_REF = "${{ github.event.pull_request.head.sha || github.ref }}"
/**
* A pattern set is only as good as the step that matches it: each paths-filter step must run
* unconditionally in the `changes` job, on the shared pin, with the default quantifier and diff
* (inputs `ref` and `filters` only), and the `build` step must read the shared source.
*/
function filterStepFindings(wf: GateWorkflow, label: string): string[] {
const steps = Object.entries(filterSteps(wf))
const pins = [...new Set(steps.map(([, step]) => step.uses))]
const elsewhere = Object.entries(wf.jobs).filter(
([name, job]) => name !== "changes" && (job.steps ?? []).some((step) => step.uses?.includes(PATHS_FILTER)),
)
const stepFaults = ([id, step]: [string, GateStep]): string[] => [
...(Object.keys(step.with ?? {})
.sort()
.join() === "filters,ref"
? []
: [`${id} takes ${Object.keys(step.with ?? {}).join(", ")}`]),
...(step.with?.ref === FILTER_REF ? [] : [`${id} compares ${step.with?.ref}`]),
...(step.if === undefined && step["continue-on-error"] === undefined ? [] : [`${id} is conditional`]),
]
return [
...(filterSteps(wf).build?.with?.filters === BUILD_SOURCE ? [] : [`no build step reads ${BUILD_SOURCE}`]),
...(pins.length === 1 ? [] : [`paths-filter pins ${pins.join(", ")}`]),
...elsewhere.map(([name]) => `a paths filter in ${name}`),
...steps.flatMap(stepFaults),
].map((finding) => `${label}: ${finding}`)
}