pg-core 0.6.13

PostGuard core library for communication and bytestream operations.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
//! What CI's gates in `build.yml` are actually wired to (issue #272).
//!
//! Every gate in this repo lands in two halves: the code and tests go in a PR,
//! and the workflow YAML is applied by hand, because the `dobby-coder` App has
//! no `workflows: write`. **Nothing detected a missing second half.** It has
//! already happened twice (#265 merged `pg-compat` with no job calling it;
//! postguard-js#137 patched one workflow of two), and both times the PR was
//! green.
//!
//! `pg-pkg/tests/api_gate.rs` closed that hole for `api-diff.yml` by reading the
//! workflow back and asserting the inputs its verdicts depend on. This file is
//! the same instrument pointed at `build.yml`, which carries the three gates
//! nothing machine-read until now: `wire-compat-rust`, `wire-compat-js` and
//! `semver-checks`, plus the `wire-compat` job that aggregates the first two
//! into the repo's sole required check.
//!
//! Two failure classes, and they are not the same shape:
//!
//! 1. **The patch was never applied.** A step that does not exist runs nothing,
//!    a filter that lost a path never fires, and both report the same green as a
//!    gate that ran and passed. Everything below that pins a command, a filter
//!    path, or a step's guard is aimed here.
//!
//! 2. **The check was renamed out from under its enforcement (#299).** The
//!    ruleset `main: required checks` (`bypass_actors: []`) pins the literal
//!    context string `Wire compat`. A ruleset requiring a context that no job
//!    produces blocks nothing at all, so renaming the aggregator *disarms* the
//!    gate rather than breaking it. The other side of that link lives in
//!    GitHub's API and no test runner can read it; this side is one file away,
//!    which is what [`the_required_check_name_still_names_the_aggregator`]
//!    asserts.
//!
//! 3. **The required check stopped being able to fail.** Worse than either, and
//!    it looks like neither: an aggregator that keeps its name, keeps its
//!    `needs` and reads neither result reports success however its halves
//!    ended. `needs` makes results available; only the step that reads them
//!    turns a red half into a red check.
//!
//! This file therefore lives in `pg-core` rather than beside the crate each gate
//! guards, and specifically not in `pg-compat`: `pg-compat`'s tests run *inside*
//! `wire-compat-rust`, so a guard living there would be skipped by exactly the
//! deletion it exists to catch. `Test workspace (pg-core)` runs unconditionally
//! on every push and every PR, and `pg-core` is the crate whose wire format and
//! public API these gates protect.
//!
//! It reads YAML as text on purpose. The workspace has no YAML parser and this
//! needs none: the assertions are about literal commands and literal names, and
//! a shape change that defeats the reader fails loudly here rather than being
//! quietly skipped.
//!
//! ```text
//! cargo test --manifest-path pg-core/Cargo.toml --features test,rust,stream --test ci_wiring
//! ```

use std::collections::BTreeSet;
use std::fs;
use std::path::PathBuf;

/// The two workflow files this suite reads. Named rather than hardcoded
/// inside `workflow_path`/`workflow` (#412) so a second workflow -- first
/// `delivery.yml`, and whatever comes after it -- gets the same reader
/// instead of a copy of it.
const BUILD_WORKFLOW: &str = "build.yml";
const DELIVERY_WORKFLOW: &str = "delivery.yml";

/// The context string the `main: required checks` ruleset pins (#299). It is
/// the `name:` of the aggregator job, and the ruleset is the only thing on this
/// repo that `gh pr merge --admin` cannot walk past, so this string is load
/// bearing in a way the job id is not.
const REQUIRED_CHECK: &str = "Wire compat";

/// The two halves the aggregator exists to combine (#262). Pinned so the name
/// above cannot be moved onto a job that checks less: a `Wire compat` reporting
/// on one half, or on none, satisfies the ruleset just as well.
const AGGREGATED_HALVES: [&str; 2] = ["wire-compat-rust", "wire-compat-js"];

/// `wire-compat-rust`'s path filter. Each entry is a way the sealed bytes can
/// change, and dropping one silently narrows the gate rather than breaking it:
/// `pg-core` resolves from the *root* lockfile, so a `bincode-next`/`ibe`/serde
/// bump touches only `Cargo.lock` and `Cargo.toml`, and `build.yml` is here so
/// that editing the gate re-runs it.
const WIRE_FILTER: [&str; 7] = [
    "pg-core/**",
    "pg-wasm/**",
    "pg-compat/**",
    "pg-compat-js/**",
    "Cargo.lock",
    "Cargo.toml",
    ".github/workflows/build.yml",
];

/// `semver-checks`'s path filter, same reasoning: the two published surfaces,
/// the manifests that decide what they resolve to, and the gate's own files.
const SEMVER_FILTER: [&str; 7] = [
    "pg-core/**",
    "pg-wasm/**",
    "Cargo.toml",
    "Cargo.lock",
    "scripts/semver-checks.sh",
    "scripts/semver-checks-test.sh",
    ".github/workflows/build.yml",
];

/// The sealer the whole wire gate is built on. `--locked` is part of the
/// contract, not a nicety: the bytes HEAD produces are a function of the root
/// lockfile, so a run that silently re-resolved would be measuring a tree that
/// was never committed.
const SEAL_COMMAND: &str = "cargo run --locked -p pg-core --features stream --example seal-samples";

/// The reporter script `delivery.yml`'s `changelog-coverage` job must call, as
/// one bare command (#429). The job used to run the reporting loop -- reading
/// existing issue titles, iterating tags, filing issues -- inline in YAML, and
/// a `run:` block with no `shell:` key executes as `bash -e {0}`:
/// `code=$(scripts/changelog-coverage.sh ...); code=$?` is a plain assignment
/// whose exit status is the substitution's, so a non-zero exit there aborted
/// the step before `code=$?` was ever reached. That is why #412's first real
/// finding (`pg-core-v0.6.6` omitting #421) filed no issue. Pinned so a rename
/// of the script disarms the job -- an empty step that still runs and still
/// reports green -- rather than failing it, same reasoning as #412.
const CHANGELOG_COVERAGE_REPORT_COMMAND: &str = "scripts/changelog-coverage-report.sh";

/// What a reporting loop would look like if it moved back into a workflow's
/// YAML instead of staying inside its extracted script: the `gh issue create`
/// call and the `existing_titles` read that used to sit above it in
/// `delivery.yml`'s `changelog-coverage` job, before #429 moved them into
/// `scripts/changelog-coverage-report.sh`. Either one back in a step means the
/// hazard the extraction exists to remove -- a fallible read or write inside a
/// `run:` block nothing correctly branches on -- is back too, whatever the
/// reporter script itself still does.
///
/// Guards two jobs now, not one: `changelog-coverage` in `delivery.yml`
/// (#429) and `ruleset-drift` in `build.yml` (#422), the same extracted-script
/// shape applied a second time. One list rather than a second copy under a
/// second name, because the two markers are the same hazard pointed at a
/// second job.
const REPORTING_LOOP_MARKERS: [&str; 2] = ["gh issue create", "existing_titles"];

/// The line `publish-wasm`'s `Set version and publish` step must run (#419).
/// `pg-wasm/CHANGELOG.md` is a pointer document whose entire premise is that
/// the published npm version *is* `pg-core`'s -- that is the only reason
/// reading `pg-core`'s changelog at the same version number is a correct
/// answer for `@e4a/pg-wasm`. If someone changes how this step derives the
/// version -- a literal, a separate input, a computed bump -- the pointer
/// silently becomes a lie about every published version, and nothing else in
/// either repo would say so.
const WASM_PUBLISH_VERSION_COMMAND: &str =
    r#"npm version "${{ needs.release-plz-release.outputs.pg_core_version }}""#;

/// The coverage script's own regression suite. `build.yml`'s `ruleset-drift`
/// job must also run this (#412 review) -- see
/// [`the_changelog_coverage_checkers_self_test_runs_in_ci`].
const CHANGELOG_COVERAGE_TEST_COMMAND: &str = "scripts/changelog-coverage-test.sh";

/// The reporter script's own regression suite (#429), same reasoning as
/// [`CHANGELOG_COVERAGE_TEST_COMMAND`] one level up: a reporter nobody runs in
/// CI is indistinguishable from one that always exits 0. `build.yml`'s
/// `ruleset-drift` job must also run this -- see
/// [`the_changelog_coverage_reporters_self_test_runs_in_ci`].
const CHANGELOG_COVERAGE_REPORT_TEST_COMMAND: &str = "scripts/changelog-coverage-report-test.sh";

/// The reporter script `build.yml`'s `ruleset-drift` job must call in place of
/// `scripts/ruleset-drift.sh` directly (#422). Same shape as
/// [`CHANGELOG_COVERAGE_REPORT_COMMAND`] and the same reason: the job used to
/// run the checker bare, reddening on drift and filing nothing, and in this
/// fleet a red job has gone unread for 15 days without anyone noticing -- a
/// red is not a signal by itself here. Pinned so a rename of the reporter
/// disarms the filing half silently: the checker keeps running through
/// `scripts/ruleset-drift-test.sh`, so a job that lost this step would still
/// look wired.
const RULESET_DRIFT_REPORT_COMMAND: &str = "scripts/ruleset-drift-report.sh";

/// The reporter's own regression suite (#422), same reasoning as
/// [`CHANGELOG_COVERAGE_REPORT_TEST_COMMAND`] one level up: a reporter nobody
/// runs in CI is indistinguishable from one that always exits 0.
const RULESET_DRIFT_REPORT_TEST_COMMAND: &str = "scripts/ruleset-drift-report-test.sh";

/// A marker unique to the `node -e` heredoc `Assemble package` used to write
/// (#427). If this string is still in the step, the manifest is still being
/// authored inline instead of copied from the committed `pg-wasm/package.json`
/// -- the two can coexist (a copy added without the heredoc removed), and this
/// is what would say so.
const WASM_ASSEMBLE_MANIFEST_HEREDOC_MARKER: &str = "const pkg = {";

/// The two copies `Assemble package` must make instead of writing JSON by hand
/// or leaving the README out (#427): `pg-wasm/package.json` and
/// `pg-wasm/README.md`, committed one level up from the `pkg/` working
/// directory the step runs in.
const WASM_ASSEMBLE_COPY_MANIFEST: &str = "cp ../package.json package.json";
const WASM_ASSEMBLE_COPY_README: &str = "cp ../README.md README.md";

/// The pre-publish gate on the assembled directory (#427): a package missing
/// its README or its manifest fields has been publishable-by-CI's-standards
/// since this package's first release, because nothing between "wasm-pack
/// built it" and "npm accepted it" ever looked at what was actually in
/// `pkg/`. `scripts/wasm-package-check-test.sh` pins the script's own 0/1/2
/// exit contract; this only asserts the workflow still calls it, and calls it
/// early enough to matter.
const WASM_PACKAGE_CHECK_COMMAND: &str = "scripts/wasm-package-check.sh pg-wasm/pkg";

/// The checker's own regression suite, same reasoning as
/// [`CHANGELOG_COVERAGE_TEST_COMMAND`]: a checker nobody runs is
/// indistinguishable from a checker that passes.
const WASM_PACKAGE_CHECK_TEST_COMMAND: &str = "scripts/wasm-package-check-test.sh";

/// The map-budget checker's own regression suite (#445), same reasoning as
/// [`WASM_PACKAGE_CHECK_TEST_COMMAND`] just above: a checker nobody runs in
/// CI is indistinguishable from one that always exits 0. `build.yml`'s
/// `ruleset-drift` job must also run this -- see
/// [`the_map_budget_checkers_self_test_runs_in_ci`].
const MAP_BUDGET_TEST_COMMAND: &str = "scripts/map-budget-test.sh";

/// The path filter's own regression suite. `scripts/changed-paths.sh` decides
/// whether the wire, pg-compat and semver gates do their work on a pull
/// request, so a wrong `false` from it skips a gate while the job reports
/// green. `build.yml`'s `ruleset-drift` job must also run this -- see
/// [`the_changed_paths_scripts_self_test_runs_in_ci`].
const CHANGED_PATHS_TEST_COMMAND: &str = "scripts/changed-paths-test.sh";

/// `test-wasm-browsers`'s corrected step (#416): a bare `run:` invoking
/// `wasm-pack test` directly, with the browser flag intact and no backslash
/// ahead of it. The backslash at `build.yml:107` was an artifact of
/// `nick-fields/retry@v3`'s `command:` input needing it escaped, and it only
/// ever worked because the action handed the string to a shell that stripped
/// it before `wasm-pack` saw it -- a bare `run:` gets no such stripping, so
/// this exact line is what the fix has to produce, not just "no backslash
/// somewhere".
const WASM_BROWSER_TEST_RUN_COMMAND: &str =
    "run: wasm-pack test --release --headless --${{ matrix.browser }} ./pg-wasm";

/// The pre-#416 hazard itself, checked for separately from
/// [`WASM_BROWSER_TEST_RUN_COMMAND`] so a step that grew a second, backslashed
/// copy alongside the corrected one -- which would still satisfy the positive
/// check above -- fails here instead of passing silently.
const WASM_BROWSER_TEST_BACKSLASH_MARKER: &str = "--\\${{ matrix.browser }}";

/// The three browsers #416 decided `test-wasm-browsers`' matrix keeps,
/// `safari` included -- the one leg that actually wedged. Pinned so quietly
/// narrowing the matrix fails loudly instead of just shrinking it.
const WASM_BROWSER_MATRIX: [&str; 3] = ["chrome", "firefox", "safari"];

/// The Rust reader half: `pg-compat` builds against crates.io `pg-core`, which
/// is what makes opening the sealed set mean anything. It has its own lockfile,
/// hence `--locked` again.
const OPEN_COMMAND: &str = "cargo test --manifest-path pg-compat/Cargo.toml --locked";

/// The one decision every conditional step in `wire-compat-rust` reads, so the
/// `push` override cannot be applied to the seal and forgotten on the open.
const GATE_CONDITION: &str = "steps.gate.outputs.run == 'true'";

/// The `push` override itself (#299). On a push the path filter answers the
/// wrong question -- it diffs only the push that triggered it, so a commit that
/// reached `main` without the gate ever running is never re-checked, and the job
/// still reports green because "filter said no" and "gate passed" are the same
/// `success`. Measured on #297, which merged with no run at all and was then
/// reported green three times.
const PUSH_OVERRIDE: &str = r#""$GITHUB_EVENT_NAME" == "push""#;

/// What `wire-compat-js` keys off instead of a second copy of the path filter,
/// so the two halves cannot drift into disagreeing about whether to run.
const SEALED_OUTPUT: &str = "needs.wire-compat-rust.outputs.sealed == 'success'";

/// The `pull_request` types the gates' verdicts depend on. Only `edited` is not
/// a default, and it is the load-bearing one: see
/// [`a_retitled_or_retargeted_pr_still_re_runs_the_gates`].
const PULL_REQUEST_TYPES: [&str; 4] = ["opened", "synchronize", "reopened", "edited"];

fn workflow_path(file: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("..")
        .join(".github/workflows")
        .join(file)
}

/// The named workflow, with line endings normalised.
///
/// `read_to_string` keeps whatever git wrote, and `core.autocrlf=true` is the
/// Git for Windows default, so on a Windows checkout the `\njobs:\n` anchor
/// below is looking for bytes the file does not contain. Every reader here is
/// line-oriented and line endings carry no meaning in YAML, so normalising once
/// is cheaper and more durable than a `.gitattributes` entry: it holds however
/// the tree was checked out. (`pg-pkg/api-description.yaml` needs the
/// `.gitattributes` route because its anchors are multi-line *content*, which
/// cannot be normalised away without changing what is being matched.)
fn workflow(file: &str) -> String {
    let path = workflow_path(file);
    fs::read_to_string(&path)
        .unwrap_or_else(|e| panic!("read {}: {e}", path.display()))
        .replace("\r\n", "\n")
}

/// The body of the top-level job `id`: every line indented past the job's own
/// key, with the key line itself dropped.
///
/// Scanning starts after `jobs:` because `on:`'s own keys (`push:`,
/// `pull_request:`) sit at the same indent as a job id and would otherwise match.
/// A missing job panics rather than returning an empty block, so a deleted job
/// fails here instead of vacuously satisfying every assertion about it.
fn job(workflow: &str, id: &str, file: &str) -> String {
    let body = workflow
        .split_once("\njobs:\n")
        .unwrap_or_else(|| panic!("no top-level `jobs:` in {}", workflow_path(file).display()))
        .1;

    let needle = format!("  {id}:");
    let mut lines = body.lines().skip_while(|line| line.trim_end() != needle);
    assert!(
        lines.next().is_some(),
        "{} has no job `{id}:`, so whatever this test asserts about it is vacuous",
        workflow_path(file).display(),
    );

    lines
        .take_while(|line| line.trim().is_empty() || line.starts_with("    "))
        .collect::<Vec<_>>()
        .join("\n")
}

/// The ids of every top-level job, in file order.
fn job_ids(workflow: &str) -> Vec<String> {
    let body = workflow
        .split_once("\njobs:\n")
        .expect("no top-level `jobs:`")
        .1;
    body.lines()
        .filter_map(|line| {
            let rest = line.strip_prefix("  ")?;
            if rest.starts_with(char::is_whitespace) || rest.starts_with('#') {
                return None;
            }
            rest.strip_suffix(':').map(str::to_owned)
        })
        .collect()
}

/// The value of a job-level `key:`, i.e. one at exactly four spaces of indent.
/// Step-level keys sit at six and behind a `- `, so `name:` here is the job's
/// display name and never a step's.
fn field(job: &str, key: &str) -> Option<String> {
    let needle = format!("{key}:");
    job.lines()
        .filter_map(|line| line.strip_prefix("    "))
        .filter(|rest| !rest.starts_with(char::is_whitespace) && !rest.starts_with('-'))
        .find_map(|rest| rest.strip_prefix(&needle))
        .map(|value| value.trim().to_owned())
}

/// A job's steps, one block of text each.
fn steps(job: &str) -> Vec<String> {
    let mut steps: Vec<String> = Vec::new();
    for line in job.lines().skip_while(|line| line.trim() != "steps:") {
        if line.starts_with("      - ") {
            steps.push(String::new());
        }
        if let Some(step) = steps.last_mut() {
            step.push_str(line);
            step.push('\n');
        }
    }
    steps
}

/// The single step containing `needle`, or a panic naming what was looked for.
/// Requiring exactly one match is what stops a duplicated step from letting one
/// of two copies drift unchecked.
fn step_with<'a>(steps: &'a [String], needle: &str, file: &str) -> &'a str {
    let found: Vec<&String> = steps.iter().filter(|step| step.contains(needle)).collect();
    assert_eq!(
        found.len(),
        1,
        "expected exactly one step containing {needle:?} in {}, found {}",
        workflow_path(file).display(),
        found.len(),
    );
    found[0]
}

/// The paths of the single path filter in a job: the `FILTERS` block its
/// `scripts/changed-paths.sh` step reads.
///
/// Read from the `FILTERS: |` block literal rather than from the job at large,
/// so a quoted list elsewhere in the job cannot pad the set and make a narrowed
/// filter look intact.
fn filter_paths(job: &str) -> BTreeSet<String> {
    let mut lines = job.lines().skip_while(|line| line.trim() != "FILTERS: |");
    let header = lines.next().expect("no `FILTERS: |` block in the job");
    let indent = header.len() - header.trim_start().len();

    lines
        .take_while(|line| line.trim().is_empty() || line.len() - line.trim_start().len() > indent)
        .map(str::trim)
        .filter_map(|line| line.strip_prefix("- "))
        .map(|path| path.trim_matches('\'').to_owned())
        .collect()
}

fn expected(paths: &[&str]) -> BTreeSet<String> {
    paths.iter().map(|p| (*p).to_owned()).collect()
}

/// The `#299` half: the ruleset pins a *name*, so the name has to keep pointing
/// at the job that aggregates both halves.
///
/// Asserted from the name inwards rather than from the job id outwards, because
/// the dangerous edit is not "the aggregator lost its name" but "the name now
/// belongs to something weaker". A `Wire compat` that needs one half, or none,
/// satisfies the ruleset exactly as well as the real one and certifies almost
/// nothing.
#[test]
fn the_required_check_name_still_names_the_aggregator() {
    let workflow = workflow(BUILD_WORKFLOW);

    let named: Vec<String> = job_ids(&workflow)
        .into_iter()
        .filter(|id| {
            field(&job(&workflow, id, BUILD_WORKFLOW), "name").as_deref() == Some(REQUIRED_CHECK)
        })
        .collect();

    assert_eq!(
        named.len(),
        1,
        "the `main: required checks` ruleset (bypass_actors: []) requires the context \
         {REQUIRED_CHECK:?}, and {} jobs in {} carry that name: {named:?}. A ruleset \
         requiring a context no job produces blocks nothing, so renaming this job disarms \
         the gate instead of breaking it -- rename the ruleset's context in the same change \
         (`gh api repos/privacybydesign/postguard/rules/branches/main`).",
        named.len(),
        workflow_path(BUILD_WORKFLOW).display(),
    );

    let aggregator = job(&workflow, &named[0], BUILD_WORKFLOW);
    let needs: BTreeSet<String> = field(&aggregator, "needs")
        .expect("the aggregator has no `needs:`")
        .trim_matches(['[', ']'].as_slice())
        .split(',')
        .map(|need| need.trim().to_owned())
        .collect();

    assert_eq!(
        needs,
        expected(&AGGREGATED_HALVES),
        "the job named {REQUIRED_CHECK:?} does not aggregate both halves of the wire gate, \
         so the repo's sole required check would go green on a run where one half never \
         passed",
    );

    // Without this the aggregator *skips* when a half fails, and a skipped
    // required check sits pending forever rather than turning red -- the one
    // outcome that looks like neither pass nor fail from the merge button.
    assert_eq!(
        field(&aggregator, "if").as_deref(),
        Some("${{ !cancelled() }}"),
        "the job named {REQUIRED_CHECK:?} must run even when an upstream half failed, or a \
         red half leaves the required check pending instead of failing it",
    );

    // `needs` only makes the halves' results *available*. What turns a red half
    // into a red required check is the step that reads them, and everything
    // above holds just as well for an aggregator that needs both and reads
    // neither: same name, same `needs`, same `if:`, green however the halves
    // ended. That is worse than the #299 rename this test was written for -- a
    // rename disarms one ruleset, this certifies a failure as a pass.
    for half in AGGREGATED_HALVES {
        assert!(
            aggregator.contains(&format!(r#""${{{{ needs.{half}.result }}}}" != "success""#)),
            "the job named {REQUIRED_CHECK:?} never reads `{half}`'s result, so it reports \
             success however that half ended",
        );
    }
    assert!(
        aggregator.contains("exit 1"),
        "the job named {REQUIRED_CHECK:?} reads both halves' results and then exits zero \
         regardless, so the repo's sole required check can never go red",
    );
}

/// The `on:` block is wiring too, and every test above reads jobs rather than
/// triggers.
///
/// `edited` is not a default `pull_request` type (the defaults are `opened`,
/// `synchronize` and `reopened`), and dropping it back to a bare `on:
/// pull_request:` leaves two verdicts attached to inputs they were not computed
/// from. Retitling a PR from `feat!:` to `fix(pg-core):` fires only `edited`, so
/// the semver gate's green -- earned with `release_type=major`, which skips
/// every lint -- stays on the unchanged head sha, and release-plz then cuts a
/// patch release of the break. A base retarget fires only `edited` too, so
/// the path filter's "nothing relevant changed" survives against a base it never
/// compared.
#[test]
fn a_retitled_or_retargeted_pr_still_re_runs_the_gates() {
    let workflow = workflow(BUILD_WORKFLOW);
    let triggers = workflow
        .split_once("\njobs:\n")
        .expect("no top-level `jobs:`")
        .0;

    let types: BTreeSet<String> = triggers
        .lines()
        .map(str::trim)
        .find_map(|line| line.strip_prefix("types:"))
        .expect("the `pull_request` trigger declares no `types:`")
        .trim()
        .trim_matches(['[', ']'].as_slice())
        .split(',')
        .map(|kind| kind.trim().to_owned())
        .collect();

    assert_eq!(
        types,
        expected(&PULL_REQUEST_TYPES),
        "the `pull_request` trigger no longer re-runs on the events these gates' verdicts \
         depend on. `edited` is the one that is not a default: without it a retitle leaves \
         the semver gate's verdict attached to the title it was computed from, and a base \
         retarget leaves the path filter's attached to the old base",
    );
}

/// The seal half: the filter that decides when it runs, the `push` override
/// that stops the filter answering the wrong question, and the two commands
/// that are the gate.
#[test]
fn the_rust_wire_gate_still_seals_and_opens_what_it_claims_to() {
    let job = job(
        &workflow(BUILD_WORKFLOW),
        "wire-compat-rust",
        BUILD_WORKFLOW,
    );
    let steps = steps(&job);

    assert_eq!(
        filter_paths(&job),
        expected(&WIRE_FILTER),
        "wire-compat-rust's path filter and this test disagree about what can change the \
         sealed bytes. A path dropped here does not fail the gate, it silently stops it \
         firing; if the filter was widened on purpose, widen WIRE_FILTER with it",
    );

    let gate = step_with(&steps, "id: gate", BUILD_WORKFLOW);
    assert!(
        gate.contains(PUSH_OVERRIDE),
        "wire-compat-rust's gate step no longer bypasses the path filter on `push`. On a \
         push the filter diffs only the push that triggered it, so a commit that reached \
         `main` without this gate running is never re-checked -- and the job still reports \
         green, because \"filter said no\" and \"gate passed\" are the same success (#299)",
    );

    let seal = step_with(&steps, "id: seal", BUILD_WORKFLOW);
    assert!(
        seal.contains(SEAL_COMMAND),
        "wire-compat-rust does not seal with `{SEAL_COMMAND}`, so the bytes the published \
         readers open are not the ones this tree produces",
    );
    assert!(
        seal.contains(GATE_CONDITION),
        "wire-compat-rust's seal step is not behind `{GATE_CONDITION}`, so it no longer \
         shares one decision with the open step and the `push` override can be applied to \
         one and forgotten on the other",
    );

    let open = step_with(&steps, OPEN_COMMAND, BUILD_WORKFLOW);
    assert!(
        open.contains(GATE_CONDITION),
        "wire-compat-rust's open step is not behind `{GATE_CONDITION}`, so it no longer \
         shares one decision with the seal step",
    );

    assert!(
        job.contains("sealed: ${{ steps.seal.outcome }}"),
        "wire-compat-rust no longer publishes `sealed` from the seal step's outcome, which is \
         the only thing wire-compat-js gates on -- without it the Node half runs on nothing, \
         or not at all",
    );
}

/// The Node half: it must open the *same* bytes, which is what makes a
/// non-deterministic sealer unable to hide between the two readers.
#[test]
fn the_js_wire_gate_still_opens_the_bytes_the_rust_half_sealed() {
    let job = job(&workflow(BUILD_WORKFLOW), "wire-compat-js", BUILD_WORKFLOW);
    let steps = steps(&job);

    assert_eq!(
        field(&job, "needs").as_deref(),
        Some("wire-compat-rust"),
        "wire-compat-js no longer depends on wire-compat-rust, so it cannot be holding both \
         readers to the same bytes",
    );
    assert_eq!(
        field(&job, "if").as_deref(),
        Some("${{ !cancelled() }}"),
        "wire-compat-js must still run when the Rust half failed: a red seal is exactly when \
         it is worth knowing whether the JS readers broke the same way, and the artifact is \
         uploaded before that job's read step for this reason",
    );

    let download = step_with(&steps, "actions/download-artifact", BUILD_WORKFLOW);
    assert!(
        download.contains(SEALED_OUTPUT),
        "wire-compat-js's download is not gated on `{SEALED_OUTPUT}`, so it no longer keys \
         off the same outcome the seal did and the two halves can drift over whether to run",
    );

    // `ci`, not `install`: the readers are pinned by pg-compat-js's lockfile, so
    // a gate that quietly resolved a different reader would still run, still
    // report, and be measuring a support window COMPATIBILITY.md never declared.
    // Same silent-narrowing class as a dropped filter path.
    let install = step_with(&steps, "run: npm ci", BUILD_WORKFLOW);
    assert!(
        install.contains("working-directory: pg-compat-js"),
        "wire-compat-js no longer installs the pinned readers with `npm ci` in pg-compat-js, \
         so the gate measures whatever npm resolves rather than the declared support window",
    );

    let open = step_with(&steps, "run: npm test", BUILD_WORKFLOW);
    assert!(
        open.contains(SEALED_OUTPUT) && open.contains("working-directory: pg-compat-js"),
        "wire-compat-js does not run `npm test` in pg-compat-js behind `{SEALED_OUTPUT}`, so \
         the published npm readers are not being pointed at the sealed set",
    );
}

/// The semver gate: it is a shell script in this repo, so the half that can
/// drift is the workflow's -- whether the script is still called, on what, and
/// whether the breaking-change declaration still comes off the PR title.
/// `release-plz.toml`'s `semver_check = false` is safe only while this test
/// stays green; `pg-core/tests/release_config.rs` pins that setting.
#[test]
fn the_semver_gate_still_calls_the_script_this_repo_pins() {
    let job = job(&workflow(BUILD_WORKFLOW), "semver-checks", BUILD_WORKFLOW);
    let steps = steps(&job);

    assert_eq!(
        filter_paths(&job),
        expected(&SEMVER_FILTER),
        "semver-checks's path filter and this test disagree about which changes can break a \
         published API. A path dropped here silently stops the gate firing; if the filter \
         was widened on purpose, widen SEMVER_FILTER with it",
    );

    step_with(&steps, "./scripts/semver-checks-test.sh", BUILD_WORKFLOW);

    let check = step_with(&steps, "./scripts/semver-checks.sh", BUILD_WORKFLOW);
    assert!(
        check.contains("SEMVER_RELEASE_TYPE: ${{ steps.declared.outputs.release_type }}"),
        "semver-checks no longer passes SEMVER_RELEASE_TYPE from the declaration step, so \
         either every breaking change fails the gate or none of them do",
    );

    // The `!` in the PR *title* is the only accepted declaration, and this is
    // where that is enforced. A body-only `BREAKING CHANGE:` footer must never
    // be honoured: this repo squash-merges with COMMIT_MESSAGES, so the body
    // never reaches the commit release-plz reads, and a `fix(pg-core):` subject
    // would then cut a patch release of a break the gate had waved through.
    let declared = step_with(&steps, "id: declared", BUILD_WORKFLOW);
    assert!(
        declared.contains("PR_TITLE: ${{ github.event.pull_request.title }}"),
        "the breaking-change declaration is no longer read off the PR title. It cannot be \
         read from the PR body: squash_merge_commit_message is COMMIT_MESSAGES, so the body \
         never reaches the commit release-plz reads",
    );
    assert!(
        declared.contains("release_type=major"),
        "the declaration step no longer emits `release_type=major`, so the `!` in a PR title \
         grants nothing and a declared break fails the gate anyway",
    );
}

/// The registry gate (#318): the job that reads the live ruleset back and
/// compares it against [`REQUIRED_CHECK`].
///
/// This file pins the name a job in `build.yml` produces; the ruleset pins the
/// name it requires; and until #318 nothing compared the two, because both
/// #272 and postguard-js#222 assumed an API read needed a credential CI could
/// not have. It does not, on a public repo. So the link is now closed from both
/// ends, and what can drift has moved: the workflow can stop calling the script.
///
/// The script's own behaviour -- drift is 1, undetermined is 2, and they are
/// never conflated -- is pinned by `scripts/ruleset-drift-test.sh`, which the
/// same job runs. This asserts only that the job still calls both.
///
/// #422 put a reporting script in front of the checker, the same shape as
/// #429's `scripts/changelog-coverage-report.sh`: the job now calls
/// [`RULESET_DRIFT_REPORT_COMMAND`] rather than `scripts/ruleset-drift.sh`
/// directly, so this file no longer names the checker anywhere. The
/// checker->reporter link -- that the reporter's default
/// `RULESET_DRIFT_CHECKER` still resolves to a real, executable
/// `scripts/ruleset-drift.sh` -- is pinned by case 11 of
/// `scripts/ruleset-drift-report-test.sh` instead of from the YAML here, the
/// same division #429 left between `delivery.yml` and
/// `scripts/changelog-coverage.sh`.
#[test]
fn the_registry_gate_still_reads_the_ruleset_back() {
    let job = job(&workflow(BUILD_WORKFLOW), "ruleset-drift", BUILD_WORKFLOW);
    let steps = steps(&job);

    step_with(&steps, RULESET_DRIFT_REPORT_COMMAND, BUILD_WORKFLOW);
    step_with(&steps, "scripts/ruleset-drift-test.sh", BUILD_WORKFLOW);

    // Without a checkout there is no script to run, and the job fails in a way
    // that reads like drift rather than like a broken job.
    assert!(
        job.contains("actions/checkout"),
        "the registry gate no longer checks the repo out, so the script it runs is not there",
    );

    // The gate reads a live third-party API. If it were ever aggregated into
    // `Wire compat` -- the one context the ruleset requires and `--admin`
    // cannot bypass -- a GitHub API outage would become an unmergeable repo.
    let aggregator = self::job(&workflow(BUILD_WORKFLOW), "wire-compat", BUILD_WORKFLOW);
    assert!(
        !aggregator.contains("ruleset-drift"),
        "the registry gate has been wired into the sole required check. It reads a live API, \
         so an outage there would block every merge; keep it a separate, non-required context",
    );
}

/// The reader above is line-oriented, so a reformat of `build.yml` could leave
/// it matching nothing while every assertion still passed. This is the check
/// that the instrument itself still works: the jobs the other tests read must
/// be found, distinct, and non-empty.
#[test]
fn every_job_this_test_reads_is_still_found() {
    let workflow = workflow(BUILD_WORKFLOW);
    let ids = job_ids(&workflow);

    for id in [
        "wire-compat-rust",
        "wire-compat-js",
        "semver-checks",
        "wire-compat",
        "ruleset-drift",
    ] {
        assert!(
            ids.contains(&id.to_owned()),
            "{} has no job `{id}`, and this test is what was supposed to notice",
            workflow_path(BUILD_WORKFLOW).display(),
        );
        let body = job(&workflow, id, BUILD_WORKFLOW);
        assert!(
            field(&body, "name").is_some() && !steps(&body).is_empty(),
            "job `{id}` read back as {} lines with no name or no steps, so the reader in \
             this file no longer understands {}",
            body.lines().count(),
            workflow_path(BUILD_WORKFLOW).display(),
        );
    }

    // `wire-compat` is a prefix of the other two ids: if the reader ever stops
    // distinguishing them, the aggregator test would read the seal job and pass
    // for the wrong reason.
    assert_ne!(
        job(&workflow, "wire-compat", BUILD_WORKFLOW),
        job(&workflow, "wire-compat-rust", BUILD_WORKFLOW),
        "the job reader is matching on a prefix, so `wire-compat` and `wire-compat-rust` \
         read back as the same block",
    );
}

/// The delivery workflow's coverage half (#412, #429): a released tag's
/// changelog entry has twice fallen silently short of the commits the tag
/// actually contains (cryptify-v0.1.36, pg-core-v0.6.5), and nothing caught
/// either time -- every check stayed green because nothing compared a tag's
/// contents against its own entry. This is the same instrument the tests
/// above point at `build.yml`, pointed at `delivery.yml` instead: read the job
/// back and assert what it runs, rather than trust that a posted patch was
/// applied.
///
/// #429 moved the reporting loop that used to live in this step's YAML into
/// scripts/changelog-coverage-report.sh -- see
/// [`CHANGELOG_COVERAGE_REPORT_COMMAND`] for why. So this now asserts two
/// things: that the step is the bare reporter invocation, and that the loop
/// has not crept back into the YAML alongside it. A step that both calls the
/// reporter *and* still contains `gh issue create` or `existing_titles` has
/// the hazard back, whatever the reporter script itself does.
///
/// This assertion is RED on this branch, and that is correct. The
/// `dobby-coder` App has no `workflows: write`, so the `changelog-coverage`
/// job it looks for is posted as a patch for a maintainer to apply, not pushed
/// here. A workflow patch that is posted and never applied has already merged
/// silently twice on this repo (#272, #324) -- do not weaken, `#[ignore]`, or
/// delete this assertion to make CI green before that patch lands.
#[test]
fn the_delivery_workflow_still_checks_changelog_coverage() {
    let job = job(
        &workflow(DELIVERY_WORKFLOW),
        "changelog-coverage",
        DELIVERY_WORKFLOW,
    );
    let steps = steps(&job);

    let check = step_with(&steps, CHANGELOG_COVERAGE_REPORT_COMMAND, DELIVERY_WORKFLOW);

    for marker in REPORTING_LOOP_MARKERS {
        assert!(
            !check.contains(marker),
            "the `changelog-coverage` step contains {marker:?} -- the reporting loop is back \
             in the YAML instead of staying inside scripts/changelog-coverage-report.sh, which \
             is the defect #429 exists to remove",
        );
    }
}

/// The shape underneath #429, generalized (decision 2): a `run:` block with no
/// `shell:` key executes as `bash -e {0}`, so `x=$(cmd); code=$?` aborts the
/// step at `cmd`'s non-zero exit, before `code=$?` is ever reached -- the
/// exact defect that made #412's first finding (`pg-core-v0.6.6` omitting
/// #421) file no issue. `delivery.yml:118`'s `code=$?` was the sole
/// occurrence of this shape anywhere in `.github/workflows/` before #429
/// moved the reporting loop it belonged to into a script. This is what stops
/// the shape growing back, in that job or any other, in either workflow.
///
/// This does **not** catch `delivery.yml:111`'s shape --
/// `existing_titles=$(gh issue list ...)`, a bare assignment from a fallible
/// command that nothing ever branches on at all. That is a different failure
/// than capturing `$?` and losing the branch to `-e`: there is no `$?`
/// capture to grep for, only a command substitution nothing reads the status
/// of. #429 moved that read into scripts/changelog-coverage-report.sh, where
/// it is branched on explicitly (see [`CHANGELOG_COVERAGE_REPORT_COMMAND`]);
/// nothing in this suite catches the bare-fallible-assignment shape anywhere
/// else in the tree, and a future reader should know that is this gate's edge
/// rather than assume it covers the class.
#[test]
fn no_workflow_step_captures_dollar_question_mark() {
    for file in [BUILD_WORKFLOW, DELIVERY_WORKFLOW] {
        let workflow = workflow(file);
        for id in job_ids(&workflow) {
            let job = job(&workflow, &id, file);
            for step in steps(&job) {
                assert!(
                    !step.contains("=$?"),
                    "job `{id}` in {} has a step that captures `$?`. A `run:` block with no \
                     `shell:` key executes as `bash -e {{0}}`, so a non-zero exit from the \
                     command immediately before the capture aborts the step before the capture \
                     is ever reached -- see #429, which removed the one occurrence this repo \
                     had (delivery.yml's old inline changelog-coverage loop)",
                    workflow_path(file).display(),
                );
            }
        }
    }
}

/// `pg-wasm/CHANGELOG.md` (#419) is a pointer document, not a per-version
/// record: it tells a reader to look up `pg-core`'s changelog entry for the
/// same version number, because `@e4a/pg-wasm` is published to npm on every
/// `pg-core` release *at `pg-core`'s version*. That premise lives in exactly
/// one place -- this step's `npm version` call -- and nowhere else in either
/// repo checks it. If the derivation ever changes to a literal, a separate
/// input, or a computed bump, the pointer silently becomes a lie about every
/// version published from that point on, and this is the only thing that
/// would say so.
#[test]
fn the_wasm_publish_still_takes_its_version_from_pg_core() {
    let job = job(
        &workflow(DELIVERY_WORKFLOW),
        "publish-wasm",
        DELIVERY_WORKFLOW,
    );
    let steps = steps(&job);

    let publish = step_with(&steps, "Set version and publish", DELIVERY_WORKFLOW);
    assert!(
        publish.contains(WASM_PUBLISH_VERSION_COMMAND),
        "publish-wasm's `Set version and publish` step no longer sets the npm version from \
         `pg_core_version`, so `pg-wasm/CHANGELOG.md`'s pointer to pg-core's changelog is no \
         longer true for versions published from here on",
    );
}

/// The release PR has to be opened by the org's release App, not by
/// `GITHUB_TOKEN`: privacybydesign forbids `GITHUB_TOKEN` to open a pull
/// request, and one it did open would start no workflows and so carry none of
/// its required checks (#334). `release-plz-pr` therefore hands release-plz
/// the App token when one was minted, and falls back to `GITHUB_TOKEN` only so
/// the job keeps working in a fork or before the secrets exist. Dropping the
/// App half of that expression fails nothing here until the next release PR
/// silently does not appear.
#[test]
fn the_release_pr_is_opened_with_the_release_app_token() {
    let job = job(
        &workflow(DELIVERY_WORKFLOW),
        "release-plz-pr",
        DELIVERY_WORKFLOW,
    );
    let steps = steps(&job);

    let mint = step_with(
        &steps,
        "actions/create-github-app-token@",
        DELIVERY_WORKFLOW,
    );
    for secret in ["secrets.RELEASE_APP_ID", "secrets.RELEASE_APP_PRIVATE_KEY"] {
        assert!(
            mint.contains(secret),
            "release-plz-pr's App-token step no longer reads `{secret}`",
        );
    }
    assert!(
        mint.contains("id: token"),
        "the App-token step lost `id: token`, which the release-plz step reads its token from",
    );

    let run = step_with(&steps, "command: release-pr", DELIVERY_WORKFLOW);
    assert!(
        run.contains("GITHUB_TOKEN: ${{ steps.token.outputs.token || secrets.GITHUB_TOKEN }}"),
        "release-plz-pr no longer gives release-plz the release App's token first, so the \
         release PR is opened by GITHUB_TOKEN again",
    );
}

/// Both image manifests are published by a job that runs under `always()`,
/// because `release-plz-release` is skipped on a pull request and a skipped
/// need would skip the job with it. Under `always()` a need gates nothing by
/// being listed: only a result named in the `if:` does. The scan was listed
/// and not named, so a scan that failed on a fixable critical still published
/// the image (#462). This holds each manifest job to its scan's result.
#[test]
fn an_image_manifest_is_not_published_past_a_failed_scan() {
    let delivery = workflow(DELIVERY_WORKFLOW);
    for (finalize, scan) in [
        ("finalize-docker", "scan-docker"),
        ("finalize-cryptify", "scan-cryptify"),
    ] {
        let job = job(&delivery, finalize, DELIVERY_WORKFLOW);
        let condition = job
            .lines()
            .map(str::trim)
            .find(|line| line.starts_with("if:"))
            .unwrap_or_else(|| panic!("{finalize} has no job-level `if:`"));
        let gate = format!("needs.{scan}.result == 'success'");
        assert!(
            condition.contains(&gate),
            "{finalize}'s condition is `{condition}`, which does not require `{gate}`: under \
             `always()` a failed scan no longer stops the manifest from being published",
        );
    }
}

/// `@e4a/pg-wasm` is published through npm trusted publishing: npm trades the
/// job's OIDC identity for a short-lived credential, so there is no
/// `NPM_TOKEN` to leak, rotate, or forget to copy when the repo changes owner
/// (which is how the 0.6.11 publish failed with `ENEEDAUTH`). Two things make
/// that work and both are easy to undo without noticing: the job must be
/// allowed to mint the OIDC token, and it must not hand npm a token of its
/// own, because a set `NODE_AUTH_TOKEN` is what npm uses instead.
#[test]
fn the_wasm_publish_authenticates_by_oidc_and_carries_no_token() {
    let job = job(
        &workflow(DELIVERY_WORKFLOW),
        "publish-wasm",
        DELIVERY_WORKFLOW,
    );

    assert!(
        job.lines().any(|line| line.trim() == "id-token: write"),
        "publish-wasm no longer has `id-token: write`, so npm cannot get the OIDC token trusted \
         publishing exchanges for a publish credential",
    );
    for token in ["NPM_TOKEN", "NODE_AUTH_TOKEN"] {
        assert!(
            !job.lines()
                .filter(|line| !line.trim_start().starts_with('#'))
                .any(|line| line.contains(token)),
            "publish-wasm references `{token}`: a long-lived npm token is back, and npm will use \
             it instead of the trusted publisher",
        );
    }
    assert!(
        !job.lines()
            .any(|line| line.trim_start().starts_with("environment:")),
        "publish-wasm has an `environment:`; the trusted publisher on npmjs.com is configured \
         without one, so the OIDC claim no longer matches and the publish is refused",
    );
}

/// The npm page has served the literal placeholder `ERROR: No README data
/// found!` since this package's first release (#427), because `Assemble
/// package` never copied one in and always wrote its manifest from a
/// `node -e` heredoc instead of the committed file. This asserts the fix
/// actually replaced that step rather than growing a copy alongside it: a
/// step that copies the committed files *and* still runs the heredoc leaves
/// whichever runs last as the one that decides what gets published, silently.
///
/// This assertion is RED on this branch, and that is correct -- see the
/// module doc and [`the_delivery_workflow_still_checks_changelog_coverage`]
/// for why: the `dobby-coder` App cannot push `.github/workflows/*.yml`, so
/// the patch this looks for is posted on the issue for a maintainer to apply,
/// not pushed here.
#[test]
fn the_wasm_assemble_step_copies_the_committed_manifest_and_readme() {
    let job = job(
        &workflow(DELIVERY_WORKFLOW),
        "publish-wasm",
        DELIVERY_WORKFLOW,
    );
    let steps = steps(&job);

    let assemble = step_with(&steps, "Assemble package", DELIVERY_WORKFLOW);

    assert!(
        assemble.contains(WASM_ASSEMBLE_COPY_MANIFEST)
            && assemble.contains(WASM_ASSEMBLE_COPY_README),
        "publish-wasm's `Assemble package` step no longer copies both the committed \
         `pg-wasm/package.json` and `pg-wasm/README.md` into the assembled directory, so the \
         published package is still missing whichever copy is gone",
    );
    assert!(
        !assemble.contains(WASM_ASSEMBLE_MANIFEST_HEREDOC_MARKER),
        "publish-wasm's `Assemble package` step still writes the manifest from a `node -e` \
         heredoc alongside the copy of the committed `pg-wasm/package.json` -- whichever runs \
         last silently decides what actually gets published",
    );
}

/// The pre-publish gate (#427): the assembled directory has to pass
/// `scripts/wasm-package-check.sh` before `npm publish` runs, not after. A
/// check that runs after publish protects nothing -- the broken package is
/// already on the registry by the time it would fail.
///
/// `steps()` returns the job's steps in file order, so the ordering itself --
/// not just the presence of both steps -- is what `iter().position` below is
/// for: a check step present anywhere *after* `Set version and publish` would
/// satisfy every other assertion in this file while checking a package that
/// is already published.
///
/// Same RED-on-this-branch reasoning as
/// [`the_wasm_assemble_step_copies_the_committed_manifest_and_readme`].
#[test]
fn the_wasm_package_is_checked_before_it_is_published() {
    let job = job(
        &workflow(DELIVERY_WORKFLOW),
        "publish-wasm",
        DELIVERY_WORKFLOW,
    );
    let steps = steps(&job);

    // Requiring exactly one match for each (via `step_with`) before comparing
    // positions rules out the case a plain `position()` search would miss: a
    // second, duplicate check step added after publish while the first stays
    // before it.
    step_with(&steps, WASM_PACKAGE_CHECK_COMMAND, DELIVERY_WORKFLOW);
    step_with(&steps, "Set version and publish", DELIVERY_WORKFLOW);

    let check_pos = steps
        .iter()
        .position(|step| step.contains(WASM_PACKAGE_CHECK_COMMAND))
        .expect("just asserted this step exists");
    let publish_pos = steps
        .iter()
        .position(|step| step.contains("Set version and publish"))
        .expect("just asserted this step exists");

    assert!(
        check_pos < publish_pos,
        "publish-wasm runs {WASM_PACKAGE_CHECK_COMMAND:?} at step {check_pos} but publishes at \
         step {publish_pos} -- a check that runs after `npm publish` protects nothing",
    );
}

/// The checker's own regression suite (#412 review): until this step exists,
/// `scripts/changelog-coverage-test.sh` -- which pins the 0/1/2 exit contract
/// against fixtures already in this repo's tag history -- runs nowhere in CI.
/// That is the same defect the gate itself exists to catch, one level up: a
/// checker nobody runs is indistinguishable from a checker that passes.
///
/// Hosted in `ruleset-drift` rather than a new job: that job already pairs a
/// drift check with an offline self-test of the script behind it
/// (`scripts/ruleset-drift-test.sh`), so this is the established pattern, not
/// a new one. Its fixtures are real tags, so the job needs full history and
/// tags, not the default shallow checkout -- without `fetch-depth: 0` the
/// checker reports exit 2 (undetermined) on every fixture, which
/// `changelog-coverage-test.sh` reads as a failure, not a pass.
///
/// This assertion is RED on this branch, same reason and same fix path as
/// [`the_delivery_workflow_still_checks_changelog_coverage`]: the
/// `dobby-coder` App cannot push `.github/workflows/*.yml`, so the `build.yml`
/// patch that adds this step is posted for a maintainer to apply, not pushed
/// here.
#[test]
fn the_changelog_coverage_checkers_self_test_runs_in_ci() {
    let job = job(&workflow(BUILD_WORKFLOW), "ruleset-drift", BUILD_WORKFLOW);
    let steps = steps(&job);

    step_with(&steps, CHANGELOG_COVERAGE_TEST_COMMAND, BUILD_WORKFLOW);

    let checkout = step_with(&steps, "actions/checkout", BUILD_WORKFLOW);
    assert!(
        checkout.contains("fetch-depth: 0"),
        "ruleset-drift's checkout no longer fetches full history and tags, so \
         changelog-coverage-test.sh's fixtures -- real tags in this repo's \
         history -- make changelog-coverage.sh report exit 2 (undetermined) \
         on every one of them instead of exercising the case",
    );
}

/// The reporter's own regression suite (#429), same reasoning as
/// [`the_changelog_coverage_checkers_self_test_runs_in_ci`] just above: a
/// reporter nobody runs in CI is indistinguishable from one that always
/// exits 0. Hosted in the same `ruleset-drift` job, the established home for
/// an offline script self-test, and it depends on that job's
/// `fetch-depth: 0` for the same reason its sibling does:
/// scripts/changelog-coverage-report-test.sh stubs only `gh` and drives the
/// real scripts/changelog-coverage.sh over real tags in this repo's history,
/// so a shallow checkout makes every one of those fixtures report exit 2
/// instead of exercising the case.
///
/// This assertion is RED on this branch, same reason and same fix path as
/// [`the_delivery_workflow_still_checks_changelog_coverage`]: the
/// `dobby-coder` App cannot push `.github/workflows/*.yml`, so the `build.yml`
/// patch that adds this step is posted for a maintainer to apply, not pushed
/// here.
#[test]
fn the_changelog_coverage_reporters_self_test_runs_in_ci() {
    let job = job(&workflow(BUILD_WORKFLOW), "ruleset-drift", BUILD_WORKFLOW);
    let steps = steps(&job);

    step_with(
        &steps,
        CHANGELOG_COVERAGE_REPORT_TEST_COMMAND,
        BUILD_WORKFLOW,
    );

    let checkout = step_with(&steps, "actions/checkout", BUILD_WORKFLOW);
    assert!(
        checkout.contains("fetch-depth: 0"),
        "ruleset-drift's checkout no longer fetches full history and tags, so \
         changelog-coverage-report-test.sh's fixtures -- real tags in this \
         repo's history, driven through the real scripts/changelog-coverage.sh \
         -- make it report exit 2 (undetermined) on every one of them instead \
         of exercising the case",
    );
}

/// The filing half of the registry gate (#422): until this lands, `build.yml`'s
/// `ruleset-drift` job reddens on drift and files nothing, and in this fleet a
/// red job has gone unread for 15 days without anyone noticing -- a red is
/// not a signal by itself here, so the filing step is the load-bearing part
/// of this gate, not a nicety.
///
/// This is the only thing that would notice a partially-applied patch, or
/// `issues: write` dropped later while tidying permissions -- either turns
/// `gh issue create` into a 403 at the exact moment the gate finally has
/// something to say, and the job would otherwise look identical to a working
/// one: the reporter step still runs, still calls the same script, and still
/// reports the same result on every push and pull request that finds no
/// drift.
///
/// Does **not** assert the push-to-`main` guard: under this shape that guard
/// lives inside `scripts/ruleset-drift-report.sh`, not in the YAML at all, by
/// design (see that script's header comment) -- cases 4 through 6 of
/// `scripts/ruleset-drift-report-test.sh` are what pin it. Its absence from
/// this test is not the oversight the original ticket's section 1 would have
/// made it; asserting it here too would just be reading the same absence
/// twice.
///
/// This assertion is RED on this branch, and that is correct. The
/// `dobby-coder` App has no `workflows: write`, so the `build.yml` patch this
/// looks for is posted for a maintainer to apply, not pushed here -- do not
/// weaken, `#[ignore]`, or delete this assertion to make CI green before that
/// patch lands.
#[test]
fn the_ruleset_drift_gate_files_what_it_finds() {
    let job = job(&workflow(BUILD_WORKFLOW), "ruleset-drift", BUILD_WORKFLOW);
    let steps = steps(&job);

    assert!(
        job.contains("issues: write"),
        "the `ruleset-drift` job no longer declares `issues: write`, so its reporter's \
         `gh issue create` would 403 at the exact moment the gate has something to say",
    );

    let report = step_with(&steps, RULESET_DRIFT_REPORT_COMMAND, BUILD_WORKFLOW);
    assert!(
        report
            .lines()
            .any(|line| line.trim() == format!("run: {RULESET_DRIFT_REPORT_COMMAND}")),
        "the `ruleset-drift` job's reporter step is no longer a bare invocation of \
         {RULESET_DRIFT_REPORT_COMMAND:?} on its own `run:` line",
    );

    for marker in REPORTING_LOOP_MARKERS {
        assert!(
            !report.contains(marker),
            "the reporter step contains {marker:?} -- the filing loop has crept back into the \
             YAML instead of staying inside {RULESET_DRIFT_REPORT_COMMAND}, the defect this \
             gate exists to remove",
        );
    }

    assert!(
        report.contains("GH_TOKEN"),
        "the reporter step no longer passes `GH_TOKEN`, so both its dedupe read and any \
         `gh issue create` it attempts would run unauthenticated against the runner's shared \
         60/hour budget",
    );
}

/// The reporter's own regression suite (#422), same reasoning as
/// [`the_changelog_coverage_reporters_self_test_runs_in_ci`] just above: a
/// reporter nobody runs in CI is indistinguishable from one that always exits
/// 0. Hosted in the same `ruleset-drift` job, the established home for an
/// offline script self-test, not a new one.
///
/// Needs no `fetch-depth: 0` clause of its own, unlike its changelog-coverage
/// sibling above: `scripts/ruleset-drift-report-test.sh` stubs both `gh` and
/// the checker it drives (through `RULESET_DRIFT_CHECKER`), and builds every
/// fixture it needs in a temp directory rather than reading this repo's own
/// tag history. The omission is deliberate, not a copy-paste slip against the
/// changelog reporter's version.
///
/// This assertion is RED on this branch, same reason and same fix path as
/// [`the_delivery_workflow_still_checks_changelog_coverage`]: the
/// `dobby-coder` App cannot push `.github/workflows/*.yml`, so the `build.yml`
/// patch that adds this step is posted for a maintainer to apply, not pushed
/// here.
#[test]
fn the_ruleset_drift_reporters_self_test_runs_in_ci() {
    let job = job(&workflow(BUILD_WORKFLOW), "ruleset-drift", BUILD_WORKFLOW);
    let steps = steps(&job);

    step_with(&steps, RULESET_DRIFT_REPORT_TEST_COMMAND, BUILD_WORKFLOW);
}

/// The wasm-package checker's own regression suite (#427), same reasoning as
/// [`the_changelog_coverage_checkers_self_test_runs_in_ci`] one level up: a
/// checker nobody runs in CI is indistinguishable from one that always
/// passes. Hosted in the same `ruleset-drift` job for the same reason --
/// that job is already the established home for an offline script self-test,
/// not a new one -- and it needs no `fetch-depth: 0` of its own, since
/// `scripts/wasm-package-check-test.sh` builds every fixture it needs in a
/// temp dir rather than reading this repo's history.
///
/// This assertion is RED on this branch, same reason and same fix path as
/// [`the_changelog_coverage_checkers_self_test_runs_in_ci`]: the
/// `dobby-coder` App cannot push `.github/workflows/*.yml`, so the `build.yml`
/// patch that adds this step is posted for a maintainer to apply, not pushed
/// here.
#[test]
fn the_wasm_package_checkers_self_test_runs_in_ci() {
    let job = job(&workflow(BUILD_WORKFLOW), "ruleset-drift", BUILD_WORKFLOW);
    let steps = steps(&job);

    step_with(&steps, WASM_PACKAGE_CHECK_TEST_COMMAND, BUILD_WORKFLOW);
}

/// The map-budget checker's own regression suite (#445), same reasoning as
/// [`the_wasm_package_checkers_self_test_runs_in_ci`] just above: a checker
/// nobody runs in CI is indistinguishable from one that always exits 0.
/// Hosted in the same `ruleset-drift` job for the same reason -- that job is
/// already the established home for an offline script self-test, not a new
/// one -- and it needs no `fetch-depth: 0` of its own, since
/// `scripts/map-budget-test.sh` builds every fixture it needs in a temp dir
/// (plus one committed snapshot read straight off disk) rather than reading
/// this repo's history.
///
/// This assertion is RED on this branch, same reason and same fix path as
/// [`the_wasm_package_checkers_self_test_runs_in_ci`]: the `dobby-coder` App
/// cannot push `.github/workflows/*.yml`, so the `build.yml` patch that adds
/// this step is posted for a maintainer to apply, not pushed here.
#[test]
fn the_map_budget_checkers_self_test_runs_in_ci() {
    let job = job(&workflow(BUILD_WORKFLOW), "ruleset-drift", BUILD_WORKFLOW);
    let steps = steps(&job);

    step_with(&steps, MAP_BUDGET_TEST_COMMAND, BUILD_WORKFLOW);
}

/// The path filter's own regression suite, same reasoning as
/// [`the_map_budget_checkers_self_test_runs_in_ci`] just above. The script
/// replaced `dorny/paths-filter` when the repository moved to an organization
/// that does not run that action, and it is deliberately narrower: it refuses
/// any pattern that is not a path or a `dir/**`. Its suite is what pins that
/// refusal, and the exit code 2 that keeps "could not find out" from being
/// read as "nothing changed".
#[test]
fn the_changed_paths_scripts_self_test_runs_in_ci() {
    let job = job(&workflow(BUILD_WORKFLOW), "ruleset-drift", BUILD_WORKFLOW);
    let steps = steps(&job);

    step_with(&steps, CHANGED_PATHS_TEST_COMMAND, BUILD_WORKFLOW);
}

/// #416, implemented: `test-wasm-browsers` gets an honest job-level timeout
/// instead of the `nick-fields/retry@v3` wrapper that inverted its own
/// failure handling.
///
/// On 2026-09-03 a wedged safari session ran three times -- once on a push to
/// `main`, twice on PRs -- each burning ~22 minutes with ~17 of them in total
/// silence, because `retry_on: error` never engaged `max_attempts: 2`: a
/// timeout is not `error` in that action's taxonomy. (A chrome run the wrapper
/// did retry correctly, `Child_process exited with error code 1`, shows the
/// other half of the inversion -- it re-rolls a genuine failure it should
/// have just reported.) The fix is a job-level `timeout-minutes` a maintainer
/// applies directly (`dobby-coder` has no `workflows: write`) and a bare
/// `run:` in place of the action, which needs no backslash ahead of
/// `${{ matrix.browser }}` because there is no longer a shell-stripped action
/// input for the backslash to survive as an artifact of.
///
/// This assertion is RED on this branch, same reason and same fix path as
/// [`the_wasm_assemble_step_copies_the_committed_manifest_and_readme`]: the
/// workflow patch is posted on the issue for a maintainer to apply, not
/// pushed here.
#[test]
fn the_wasm_browser_job_has_an_honest_timeout_and_no_retry_wrapper() {
    let job = job(
        &workflow(BUILD_WORKFLOW),
        "test-wasm-browsers",
        BUILD_WORKFLOW,
    );

    assert!(
        field(&job, "timeout-minutes").is_some(),
        "test-wasm-browsers has no job-level `timeout-minutes`, so a wedged browser session \
         runs to GitHub's 6-hour default -- the pre-#416 failure amplified roughly 18x over \
         even the retry wrapper's own 20-minute budget",
    );

    assert!(
        !job.contains("uses: nick-fields/retry"),
        "test-wasm-browsers still uses `nick-fields/retry`, which re-rolls a genuine test \
         failure (`retry_on: error`) but never retries the one failure shape this job has \
         actually hit -- a timeout is not `error` in that action's taxonomy, so \
         `max_attempts: 2` never engaged on 2026-09-03's three wedged safari runs",
    );

    let steps = steps(&job);
    let run = step_with(&steps, "wasm-pack test", BUILD_WORKFLOW);

    assert!(
        run.contains(WASM_BROWSER_TEST_RUN_COMMAND),
        "test-wasm-browsers no longer runs {WASM_BROWSER_TEST_RUN_COMMAND:?} as a bare `run:` \
         step -- either the browser flag changed or the step is wrapped in an action again",
    );
    assert!(
        !run.contains(WASM_BROWSER_TEST_BACKSLASH_MARKER),
        "test-wasm-browsers' `wasm-pack test` step still carries the literal backslash from \
         build.yml:107 ({WASM_BROWSER_TEST_BACKSLASH_MARKER:?}) -- it only ever worked because \
         `nick-fields/retry`'s `command:` input handed the string to a shell that stripped it \
         before `wasm-pack` saw it, and a bare `run:` gets no such stripping",
    );

    for browser in WASM_BROWSER_MATRIX {
        assert!(
            job.contains(&format!("browser: {browser}")),
            "test-wasm-browsers' matrix no longer includes `{browser}` -- #416 decided all \
             three browsers stay, `safari` included, the one that actually wedged",
        );
    }
}

/// #453 established that `WASM_BINDGEN_TEST_TIMEOUT` is a timer over the
/// whole `wasm-pack test` run, not a per-test one: wasm-bindgen's
/// `headless.rs` (identical at 0.2.121 and 0.2.128) starts the clock after
/// `goto` returns and waits, in one loop, for `test result: ` to appear in
/// the page's output. #432's "~6x the slowest single test" reasoning sized a
/// per-test clock that was never running.
///
/// Safari's green suite takes 18.7-30.9s (median 27.4s, n=22, #453's
/// measurement). Four red Safari runs since 2026-09-10 each cut off 26-28s
/// in, with 8-12 of 16 tests passed -- one deadline crossed mid-suite, not a
/// hung test. 30 clips that tail. 70 is ~2x the observed max, plus the few
/// seconds the clock can run before `running 16 tests` even prints.
///
/// A value planted near the suite's real duration does not fail every run --
/// it fails the unlucky ones, so a green CI run proves nothing about the
/// margin left. That is why the gate here is the literal number, not a
/// passing job: only the literal check catches a later edit drifting it back
/// toward 30.
///
/// This assertion is RED on this branch, same reason and same fix path as
/// [`the_wasm_browser_job_has_an_honest_timeout_and_no_retry_wrapper`]: the
/// workflow patch is posted on the issue for a maintainer to apply, not
/// pushed here.
#[test]
fn the_wasm_browser_timeout_is_pinned_above_safaris_observed_tail() {
    let job = job(
        &workflow(BUILD_WORKFLOW),
        "test-wasm-browsers",
        BUILD_WORKFLOW,
    );

    let line = job
        .lines()
        .find(|line| line.trim_start().starts_with("WASM_BINDGEN_TEST_TIMEOUT:"))
        .unwrap_or_else(|| {
            panic!(
                "test-wasm-browsers sets no `WASM_BINDGEN_TEST_TIMEOUT` in {}",
                workflow_path(BUILD_WORKFLOW).display(),
            )
        });
    let value = line
        .trim()
        .strip_prefix("WASM_BINDGEN_TEST_TIMEOUT:")
        .unwrap()
        .trim();

    assert_eq!(
        value, "70",
        "test-wasm-browsers' WASM_BINDGEN_TEST_TIMEOUT is {value}, not 70 -- #453 measured \
         Safari's green suite at up to 30.9s against a whole-run clock, so a value near that \
         duration (30 clipped four real runs) fails intermittently rather than every time, and \
         only a check on the literal value catches a later edit drifting it back down",
    );
}

/// The fold's whole point (#256): `E4A.PostGuard` is packed around the
/// `pg-ffi` libraries built in the same workflow run, so the package cannot
/// carry a native library from any commit but its own. Before the fold the SDK
/// downloaded a pinned `pg-ffi` release, and the pin sat eight `pg-core` patch
/// releases behind `main` with every check green.
///
/// What would undo that is small and would look reasonable in review: a
/// `gh release download` to "reuse the released binaries", or a pack job that
/// no longer waits for `build-ffi`. Either brings back a lookup by tag, and
/// with it the question of which tag.
#[test]
fn the_dotnet_package_is_packed_from_this_runs_native_libraries() {
    let workflow = workflow(DELIVERY_WORKFLOW);

    let pack = job(&workflow, "pack-dotnet", DELIVERY_WORKFLOW);
    assert_eq!(
        field(&pack, "needs").as_deref(),
        Some("build-ffi"),
        "pack-dotnet no longer takes its native libraries from this run's build-ffi matrix",
    );
    step_with(&steps(&pack), "scripts/nupkg-check.sh", DELIVERY_WORKFLOW);

    let publish = job(&workflow, "publish-dotnet", DELIVERY_WORKFLOW);
    let needs = field(&publish, "needs").unwrap_or_default();
    assert!(
        needs.contains("pack-dotnet") && needs.contains("release-plz-release"),
        "publish-dotnet needs {needs:?}; it must publish the package pack-dotnet built in \
         this run, on the release release-plz made in this run",
    );

    for (id, body) in [("pack-dotnet", &pack), ("publish-dotnet", &publish)] {
        assert!(
            !body.contains("gh release download"),
            "{id} downloads a released pg-ffi again instead of using this run's (#256)",
        );
    }
    assert!(
        !publish.contains("dotnet pack"),
        "publish-dotnet packs a package of its own instead of publishing the one \
         pack-dotnet built and checked",
    );
}

/// `E4A.PostGuard` has no version of its own: `pg-dotnet/CHANGELOG.md` and its
/// README send a reader to `pg-core`'s changelog for the same number. Same
/// premise, same reason to pin it, as
/// [`the_wasm_publish_still_takes_its_version_from_pg_core`]. The csproj reads
/// the version from `pg-core/Cargo.toml`; this is the check, immediately
/// before the publish, that the package it produced is at the version
/// release-plz released.
///
/// The `environment:` is pinned with it because the trusted-publishing policy
/// on nuget.org names it. Without it the policy would have to name the
/// workflow file alone, and every job in `delivery.yml` with `id-token: write`
/// could mint a NuGet publish key.
#[test]
fn the_dotnet_publish_is_held_to_the_pg_core_release() {
    let publish = job(
        &workflow(DELIVERY_WORKFLOW),
        "publish-dotnet",
        DELIVERY_WORKFLOW,
    );

    assert_eq!(
        field(&publish, "if").as_deref(),
        Some("needs.release-plz-release.outputs.pg_core_version != ''"),
        "publish-dotnet no longer runs on exactly the pg-core releases",
    );
    assert_eq!(
        field(&publish, "environment").as_deref(),
        Some("nuget"),
        "publish-dotnet lost its `environment: nuget`, which the nuget.org \
         trusted-publishing policy is scoped to",
    );

    let steps = steps(&publish);
    let check = step_with(&steps, "scripts/nupkg-check.sh", DELIVERY_WORKFLOW);
    assert!(
        check.contains("needs.release-plz-release.outputs.pg_core_version")
            && check.contains(r#"scripts/nupkg-check.sh "$RUNNER_TEMP/nupkg" "$PG_CORE_VERSION""#),
        "publish-dotnet no longer checks the package's version against the pg-core release \
         before pushing it",
    );

    let position = |needle: &str| {
        steps
            .iter()
            .position(|step| step.contains(needle))
            .unwrap_or_else(|| panic!("publish-dotnet has no step containing {needle:?}"))
    };
    assert!(
        position("scripts/nupkg-check.sh") < position("dotnet nuget push"),
        "publish-dotnet pushes the package before checking it",
    );
}

/// The .NET lane (#256): `pg-dotnet` is not a cargo crate, so the per-crate
/// matrices never reach it. The job builds `pg-ffi` from the checkout before
/// it tests, which is what lets `NativeLibraryTests` hold the binding against
/// the native library of the same commit.
#[test]
fn the_dotnet_lane_tests_against_the_native_library_it_just_built() {
    let job = job(&workflow(BUILD_WORKFLOW), "dotnet", BUILD_WORKFLOW);
    let steps = steps(&job);

    let position = |needle: &str| {
        steps
            .iter()
            .position(|step| step.contains(needle))
            .unwrap_or_else(|| panic!("the dotnet job has no step containing {needle:?}"))
    };
    assert!(
        position("pg-ffi/build.sh") < position("dotnet test pg-dotnet/E4A.PostGuard.slnx"),
        "the dotnet job must build pg-ffi from this checkout before it runs the .NET tests",
    );
}

/// The two scripts the NuGet publish runs only on a release, same reasoning as
/// [`the_wasm_package_checkers_self_test_runs_in_ci`]: a release is the wrong
/// moment to learn that a branch of either was never exercised.
#[test]
fn the_dotnet_publish_scripts_self_tests_run_in_ci() {
    let job = job(&workflow(BUILD_WORKFLOW), "ruleset-drift", BUILD_WORKFLOW);
    let steps = steps(&job);

    step_with(&steps, "scripts/nuget-login-test.sh", BUILD_WORKFLOW);
    step_with(&steps, "scripts/nupkg-check-test.sh", BUILD_WORKFLOW);
}