anodizer 0.7.0

A Rust-native release automation tool inspired by GoReleaser
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
//! Pipeline-construction functions for each entry point: full release,
//! split (build-only), publish, publish-only, announce-only, and merge.
//!
//! Each `build_*_pipeline` assembles a [`super::Pipeline`] by pushing the
//! stages for that command in dependency order. The ordering invariants
//! (blob before snapcraft-publish, sign before release in publish-only,
//! announce/verify terminal) are asserted by the tests at the foot of this
//! module.

use super::Pipeline;

/// Build the full release pipeline with all stages in order
pub fn build_release_pipeline() -> Pipeline {
    use anodizer_stage_announce::AnnounceStage;
    use anodizer_stage_appbundle::AppBundleStage;
    use anodizer_stage_appimage::AppImageStage;
    use anodizer_stage_archive::ArchiveStage;
    use anodizer_stage_attest::AttestStage;
    use anodizer_stage_blob::BlobStage;
    use anodizer_stage_build::BuildStage;
    use anodizer_stage_changelog::ChangelogStage;
    use anodizer_stage_checksum::ChecksumStage;
    use anodizer_stage_dmg::DmgStage;
    use anodizer_stage_docker::DockerStage;
    use anodizer_stage_flatpak::FlatpakStage;
    use anodizer_stage_makeself::MakeselfStage;
    use anodizer_stage_msi::MsiStage;
    use anodizer_stage_nfpm::NfpmStage;
    use anodizer_stage_notarize::NotarizeStage;
    use anodizer_stage_nsis::NsisStage;
    use anodizer_stage_pkg::PkgStage;
    use anodizer_stage_prepublish_guard::PrePublishGuardStage;
    use anodizer_stage_publish::{EmissionValidateStage, PublishStage};
    use anodizer_stage_release::ReleaseStage;
    use anodizer_stage_sbom::SbomStage;
    use anodizer_stage_sign::{DockerSignStage, SignStage};
    use anodizer_stage_snapcraft::{SnapcraftPublishStage, SnapcraftStage};
    use anodizer_stage_source::SourceStage;
    use anodizer_stage_srpm::SrpmStage;
    use anodizer_stage_templatefiles::TemplateFilesStage;
    use anodizer_stage_upx::UpxStage;
    use anodizer_stage_verify_release::VerifyReleaseStage;

    // Canonical stage order.
    // Anodizer-specific stages (appbundle, dmg, msi, pkg, nsis, templatefiles,
    // release, snapcraft-publish, blob) are interleaved at logical positions.
    let mut p = Pipeline::new();
    p.expect_binaries();

    // ── Build ────────────────────────────────────────────────────────────
    p.add(Box::new(BuildStage));
    p.add(Box::new(UpxStage));
    // AppBundle → DMG → PKG must run before Notarize (macOS signing).
    // MSI and NSIS are Windows equivalents at the same pipeline phase.
    p.add(Box::new(AppBundleStage));
    p.add(Box::new(DmgStage));
    p.add(Box::new(MsiStage));
    p.add(Box::new(PkgStage));
    p.add(Box::new(NsisStage));
    p.add(Box::new(NotarizeStage));

    // ── Changelog ────────────────────────────────────────────────────────
    p.add(Box::new(ChangelogStage));

    // ── Packaging ────────────────────────────────────────────────────────
    p.add(Box::new(ArchiveStage));
    p.add(Box::new(SourceStage));
    p.add(Box::new(NfpmStage));
    p.add(Box::new(SrpmStage));
    p.add(Box::new(MakeselfStage));
    p.add(Box::new(AppImageStage));
    p.add(Box::new(SnapcraftStage));
    p.add(Box::new(FlatpakStage));
    p.add(Box::new(SbomStage));
    p.add(Box::new(TemplateFilesStage));

    // ── Integrity ────────────────────────────────────────────────────────
    p.add(Box::new(ChecksumStage));
    // AttestStage runs after Checksum (so subject digests reuse the computed
    // sha256) and before Sign: in `emit` mode it registers the in-toto
    // statement as an UploadableFile, which the following SignStage then signs
    // and ReleaseStage uploads — no new signing path.
    p.add(Box::new(AttestStage));
    p.add(Box::new(SignStage));

    // ── Publish ──────────────────────────────────────────────────────────
    // EmissionValidateStage is a no-op in a real release; in snapshot/dry-run
    // it validates the binstall/nix/version-sync emissions (which the real
    // stages mutate/push but snapshot skips) against the produced asset set.
    // Runs after ChecksumStage so the archive cross-checks see every asset.
    p.add(Box::new(EmissionValidateStage));
    // BeforePublishStage runs user-defined `before_publish:` hooks here so a
    // non-zero hook can abort the release before any publisher writes to a
    // registry — last gate for smoke-tests / scanners against the staged dist.
    p.add(Box::new(anodizer_core::hooks::BeforePublishStage));
    p.add(Box::new(ReleaseStage));
    // PrePublishGuardStage runs immediately after ReleaseStage — once the
    // release exists, `ensure_release_url` has put the (real or derived)
    // `ReleaseURL` in ctx — and BEFORE any irreversible publisher
    // (chocolatey/winget moderation, AUR push) or announcer fires, so a broken
    // publisher-manifest or announce template aborts with no one-way door
    // already through.
    p.add(Box::new(PrePublishGuardStage));
    p.add(Box::new(DockerStage::new()));
    // DockerSignStage runs after DockerStage so docker image artifacts exist.
    p.add(Box::new(DockerSignStage));
    p.add(Box::new(PublishStage));
    // BlobStage runs before SnapcraftPublishStage so a required-blob
    // failure can short-circuit the snapcraft upload via the same
    // `any_failed(Assets, required_only=true)` check that already gates
    // every other Submitter publisher.
    p.add(Box::new(BlobStage));
    p.add(Box::new(SnapcraftPublishStage));
    p.add(Box::new(AnnounceStage));

    // ── Post-publish verification ────────────────────────────────────────
    // VerifyReleaseStage runs LAST — after the release exists and every
    // publisher has run — because it needs the published release to verify
    // against. A no-op unless `verify_release.enabled`; on a detected defect
    // it reports + exits non-zero but never undoes the (already-live) release.
    p.add(Box::new(VerifyReleaseStage));
    p
}

/// Build a pipeline that only runs the build stage (for --split mode).
pub fn build_split_pipeline() -> Pipeline {
    use anodizer_stage_build::BuildStage;
    use anodizer_stage_upx::UpxStage;

    let mut p = Pipeline::new();
    p.add(Box::new(BuildStage));
    p.add(Box::new(UpxStage));
    p
}

/// Build a publish-only pipeline: release, publish, blob, snapcraft-publish stages.
///
/// **Note**: this is the pipeline consumed by the LEGACY `anodize
/// publish` subcommand, which assumes the input dist was produced by
/// a full `anodize release` whose own SignStage already fired. Adding
/// a head SignStage here would silently introduce a new credential
/// requirement to the existing surface. The
/// `anodize release --publish-only` path uses
/// [`build_publish_only_pipeline`] instead, which DOES prepend
/// SignStage for the determinism-preserved-dist re-sign pass.
pub fn build_publish_pipeline() -> Pipeline {
    use anodizer_stage_blob::BlobStage;
    use anodizer_stage_prepublish_guard::PrePublishGuardStage;
    use anodizer_stage_publish::PublishStage;
    use anodizer_stage_release::ReleaseStage;
    use anodizer_stage_snapcraft::SnapcraftPublishStage;

    let mut p = Pipeline::new();
    p.add(Box::new(anodizer_core::hooks::BeforePublishStage));
    p.add(Box::new(ReleaseStage));
    // Guard the (legacy) publish path too: a broken publisher-manifest or
    // announce template must abort after the release exists but before any
    // irreversible publisher fires.
    p.add(Box::new(PrePublishGuardStage));
    p.add(Box::new(PublishStage));
    // BlobStage before SnapcraftPublishStage so the snapcraft submitter
    // gate sees blob's outcome via `ctx.publish_report`.
    p.add(Box::new(BlobStage));
    p.add(Box::new(SnapcraftPublishStage));
    p
}

/// Build the pipeline for `anodize release --publish-only`:
/// `[ChangelogStage, SignStage, ReleaseStage, PublishStage,
/// BlobStage, SnapcraftPublishStage, AnnounceStage]`. The head
/// `SignStage` is the production-keys re-sign pass — the preserved
/// dist's archive bytes are byte-stable (the determinism check
/// verified that) but their `.sig`/`.asc` signatures are either
/// missing entirely (harness skips Sign when prod keys are exported
/// on the runner) or ephemeral (harness ran without prod keys).
///
/// **Ordering invariants**:
/// - `ChangelogStage` runs first. It is a pure GitHub API call with
///   no artifact dependency, and `ReleaseStage::build_release_json`
///   reads `ctx.stage_outputs.changelogs` to populate the GitHub
///   release body — so it MUST land before `ReleaseStage`. Placing
///   it at the head also means a GitHub API failure aborts before
///   any signing work is performed.
/// - `AnnounceStage` runs last, matching `build_merge_pipeline` and
///   `build_release_pipeline`. The stage's internal
///   `required_publishers` gate then sees the final publish report
///   and only fires notifications on a green publish.
///
/// **Idempotence requirement on SignStage**: must be safe to re-run
/// on a dist whose existing `.sig`/`.asc` files are already
/// production signatures (gpg/cosign `--output` semantics overwrite
/// in place; `helpers::should_sign_artifact` excludes
/// `Signature`/`Certificate` artifact kinds from the `all`/`any`
/// filters so re-running can't produce `*.sig.sig` chains). The
/// publish-only entry point ALSO strips any *ephemeral* harness
/// signature/certificate artifacts up-front in
/// `commands/release/publish_only::strip_ephemeral_signatures` so
/// the head SignStage only sees the underlying archives.
///
/// Cross-platform packagers (msi/nsis/dmg/pkg/appbundle/flatpak/etc.)
/// that the harness's default stage list doesn't cover are expected
/// to have run in the upstream harness pipeline before preserve-dist
/// captured the tree — those stages are added to the harness's stage
/// list in CI and their outputs land under `dist/`. The publish-only
/// pipeline therefore consumes the full artifact set as-is and does
/// not re-run any artifact-producing stages.
pub(crate) fn build_publish_only_pipeline() -> Pipeline {
    use anodizer_stage_announce::AnnounceStage;
    use anodizer_stage_attest::AttestStage;
    use anodizer_stage_blob::BlobStage;
    use anodizer_stage_changelog::ChangelogStage;
    use anodizer_stage_checksum::ChecksumStage;
    use anodizer_stage_docker::DockerStage;
    use anodizer_stage_prepublish_guard::PrePublishGuardStage;
    use anodizer_stage_publish::PublishStage;
    use anodizer_stage_release::ReleaseStage;
    use anodizer_stage_sign::{DockerSignStage, SignStage};
    use anodizer_stage_snapcraft::SnapcraftPublishStage;
    use anodizer_stage_verify_release::VerifyReleaseStage;

    let mut p = Pipeline::new();
    p.add(Box::new(ChangelogStage));
    p.add(Box::new(SignStage));
    // ChecksumStage between SignStage and PublishStage hashes the
    // production-signed bytes and backfills `sha256` onto every
    // artifact so each publisher sees the metadata its manifest
    // schema requires. The recompute is byte-deterministic, so this
    // is idempotent across re-runs.
    p.add(Box::new(ChecksumStage));
    // AttestStage re-derives the subjects manifest from the recomputed
    // digests and re-registers the emit-mode in-toto statement (byte-stable,
    // so its preserved upstream signature still matches) so ReleaseStage
    // uploads both. The emit-mode statement is signed in the upstream harness
    // run that produced the preserved dist; no re-sign happens here.
    p.add(Box::new(AttestStage));
    p.add(Box::new(anodizer_core::hooks::BeforePublishStage));
    p.add(Box::new(ReleaseStage));
    // Abort before any irreversible publisher / announcer if a manifest or
    // announce template fails to render — the release exists by now, so
    // `ReleaseURL` is in ctx for the announce dry-render.
    p.add(Box::new(PrePublishGuardStage));
    // Docker build+sign land between the GitHub release and PublishStage:
    // the mcp publisher (inside PublishStage) validates that the OCI image
    // its manifest references already exists in the registry, so the image
    // must be built and pushed first.
    p.add(Box::new(DockerStage::new()));
    p.add(Box::new(DockerSignStage));
    p.add(Box::new(PublishStage));
    p.add(Box::new(BlobStage));
    p.add(Box::new(SnapcraftPublishStage));
    p.add(Box::new(AnnounceStage));
    // Post-publish verification runs LAST here too: `release --publish-only`
    // creates a real release + publishes, so the same gate applies.
    p.add(Box::new(VerifyReleaseStage));
    p
}

/// Build an announce-only pipeline.
pub fn build_announce_pipeline() -> Pipeline {
    use anodizer_stage_announce::AnnounceStage;

    let mut p = Pipeline::new();
    p.add(Box::new(AnnounceStage));
    p
}

/// Build a pipeline for --merge mode: all post-build stages.
pub fn build_merge_pipeline() -> Pipeline {
    use anodizer_stage_announce::AnnounceStage;
    use anodizer_stage_appbundle::AppBundleStage;
    use anodizer_stage_appimage::AppImageStage;
    use anodizer_stage_archive::ArchiveStage;
    use anodizer_stage_attest::AttestStage;
    use anodizer_stage_blob::BlobStage;
    use anodizer_stage_changelog::ChangelogStage;
    use anodizer_stage_checksum::ChecksumStage;
    use anodizer_stage_dmg::DmgStage;
    use anodizer_stage_docker::DockerStage;
    use anodizer_stage_flatpak::FlatpakStage;
    use anodizer_stage_makeself::MakeselfStage;
    use anodizer_stage_msi::MsiStage;
    use anodizer_stage_nfpm::NfpmStage;
    use anodizer_stage_notarize::NotarizeStage;
    use anodizer_stage_nsis::NsisStage;
    use anodizer_stage_pkg::PkgStage;
    use anodizer_stage_prepublish_guard::PrePublishGuardStage;
    use anodizer_stage_publish::{EmissionValidateStage, PublishStage};
    use anodizer_stage_release::ReleaseStage;
    use anodizer_stage_sbom::SbomStage;
    use anodizer_stage_sign::{DockerSignStage, SignStage};
    use anodizer_stage_snapcraft::{SnapcraftPublishStage, SnapcraftStage};
    use anodizer_stage_source::SourceStage;
    use anodizer_stage_srpm::SrpmStage;
    use anodizer_stage_templatefiles::TemplateFilesStage;
    use anodizer_stage_verify_release::VerifyReleaseStage;

    // Merge pipeline: same order as build_release_pipeline minus Build/UPX.
    let mut p = Pipeline::new();
    p.expect_binaries();
    p.add(Box::new(AppBundleStage));
    p.add(Box::new(DmgStage));
    p.add(Box::new(MsiStage));
    p.add(Box::new(PkgStage));
    p.add(Box::new(NsisStage));
    p.add(Box::new(NotarizeStage));
    p.add(Box::new(ChangelogStage));
    p.add(Box::new(ArchiveStage));
    p.add(Box::new(SourceStage));
    p.add(Box::new(NfpmStage));
    p.add(Box::new(SrpmStage));
    p.add(Box::new(MakeselfStage));
    p.add(Box::new(AppImageStage));
    p.add(Box::new(SnapcraftStage));
    p.add(Box::new(FlatpakStage));
    p.add(Box::new(SbomStage));
    p.add(Box::new(TemplateFilesStage));
    p.add(Box::new(ChecksumStage));
    p.add(Box::new(AttestStage));
    p.add(Box::new(SignStage));
    // Snapshot/dry-run emission validation; no-op in a real release.
    p.add(Box::new(EmissionValidateStage));
    p.add(Box::new(anodizer_core::hooks::BeforePublishStage));
    p.add(Box::new(ReleaseStage));
    // Same one-way-door guard as build_release_pipeline: abort on a broken
    // publisher-manifest or announce template before any irreversible
    // publisher fires, with `ReleaseURL` already in ctx post-Release.
    p.add(Box::new(PrePublishGuardStage));
    p.add(Box::new(DockerStage::new()));
    p.add(Box::new(DockerSignStage));
    p.add(Box::new(PublishStage));
    // BlobStage before SnapcraftPublishStage — mirrors
    // `build_release_pipeline`'s swap so merge-mode runs share the same
    // submitter-gate semantics.
    p.add(Box::new(BlobStage));
    p.add(Box::new(SnapcraftPublishStage));
    p.add(Box::new(AnnounceStage));
    // Merge mode produces + publishes a real release, so the post-publish
    // gate runs last here too.
    p.add(Box::new(VerifyReleaseStage));
    p
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    // sh -c mangles backslashes; feed it a forward-slash path so the redirect
    // target resolves on Windows (no-op on Linux where the path has none).
    fn sh_path(p: &std::path::Path) -> String {
        p.to_string_lossy().replace('\\', "/")
    }

    // -----------------------------------------------------------------------
    // Stage-order invariants
    //
    // BlobStage must run BEFORE SnapcraftPublishStage in every pipeline
    // variant so a required-blob failure can short-circuit the
    // (irreversible) snapcraft upload via the same
    // `any_failed(Assets, required_only=true)` gate that already
    // protects every other Submitter publisher.
    // -----------------------------------------------------------------------

    fn assert_blob_before_snapcraft(names: &[&str], pipeline: &str) {
        let blob_idx = names
            .iter()
            .position(|n| *n == "blob")
            .unwrap_or_else(|| panic!("{pipeline}: missing blob stage; got {names:?}"));
        let snap_idx = names
            .iter()
            .position(|n| *n == "snapcraft-publish")
            .unwrap_or_else(|| panic!("{pipeline}: missing snapcraft-publish; got {names:?}"));
        assert!(
            blob_idx < snap_idx,
            "{pipeline}: blob (idx {blob_idx}) must precede snapcraft-publish (idx {snap_idx}); got {names:?}"
        );
    }

    #[test]
    fn release_pipeline_runs_blob_before_snapcraft_publish() {
        let p = build_release_pipeline();
        let names = p.stage_names();
        assert_blob_before_snapcraft(&names, "build_release_pipeline");
    }

    // -----------------------------------------------------------------------
    // PrePublishGuardStage ordering
    //
    // The guard must sit AFTER ReleaseStage (so `ReleaseURL` is in ctx for the
    // announce dry-render) and BEFORE every irreversible publisher
    // (PublishStage, SnapcraftPublishStage) and before DockerStage, so a broken
    // publisher-manifest or announce template aborts with no one-way door
    // already through.
    // -----------------------------------------------------------------------

    fn idx(names: &[&str], stage: &str, pipeline: &str) -> usize {
        names
            .iter()
            .position(|n| *n == stage)
            .unwrap_or_else(|| panic!("{pipeline}: missing {stage} stage; got {names:?}"))
    }

    fn assert_guard_after_release_before_publishers(names: &[&str], pipeline: &str) {
        let release = idx(names, "release", pipeline);
        let guard = idx(names, "prepublish-guard", pipeline);
        let publish = idx(names, "publish", pipeline);
        assert!(
            release < guard,
            "{pipeline}: release ({release}) must precede prepublish-guard ({guard}); {names:?}"
        );
        assert!(
            guard < publish,
            "{pipeline}: prepublish-guard ({guard}) must precede publish ({publish}); {names:?}"
        );
        // Docker and snapcraft-publish are present only in some pipelines; when
        // present they must follow the guard (docker pushes an image; snapcraft
        // uploads to the store — both fire publishers/registries).
        if let Some(docker) = names.iter().position(|n| *n == "docker") {
            assert!(
                guard < docker,
                "{pipeline}: prepublish-guard ({guard}) must precede docker ({docker}); {names:?}"
            );
        }
        if let Some(snap) = names.iter().position(|n| *n == "snapcraft-publish") {
            assert!(
                guard < snap,
                "{pipeline}: prepublish-guard ({guard}) must precede snapcraft-publish ({snap}); {names:?}"
            );
        }
    }

    #[test]
    fn release_pipeline_runs_guard_after_release_before_publishers() {
        let p = build_release_pipeline();
        let names = p.stage_names();
        assert_guard_after_release_before_publishers(&names, "build_release_pipeline");
    }

    #[test]
    fn merge_pipeline_runs_guard_after_release_before_publishers() {
        let p = build_merge_pipeline();
        let names = p.stage_names();
        assert_guard_after_release_before_publishers(&names, "build_merge_pipeline");
    }

    #[test]
    fn publish_pipeline_runs_guard_after_release_before_publishers() {
        let p = build_publish_pipeline();
        let names = p.stage_names();
        assert_guard_after_release_before_publishers(&names, "build_publish_pipeline");
    }

    #[test]
    fn publish_only_pipeline_runs_guard_after_release_before_publishers() {
        let p = build_publish_only_pipeline();
        let names = p.stage_names();
        assert_guard_after_release_before_publishers(&names, "build_publish_only_pipeline");
    }

    #[test]
    fn publish_pipeline_runs_blob_before_snapcraft_publish() {
        let p = build_publish_pipeline();
        let names = p.stage_names();
        assert_blob_before_snapcraft(&names, "build_publish_pipeline");
    }

    #[test]
    fn merge_pipeline_runs_blob_before_snapcraft_publish() {
        let p = build_merge_pipeline();
        let names = p.stage_names();
        assert_blob_before_snapcraft(&names, "build_merge_pipeline");
    }

    #[test]
    fn publish_only_pipeline_runs_blob_before_snapcraft_publish() {
        // The `--publish-only` pipeline must honor the same
        // blob-before-snapcraft-publish ordering as every other
        // variant so a required-blob failure can short-circuit the
        // (irreversible) snapcraft upload via the
        // `any_failed(Assets, required_only=true)` gate.
        let p = build_publish_only_pipeline();
        let names = p.stage_names();
        assert_blob_before_snapcraft(&names, "build_publish_only_pipeline");
    }

    #[test]
    fn publish_only_pipeline_runs_sign_before_release() {
        // SignStage must be at the HEAD of the publish-only pipeline
        // so production signatures land on the preserved archives
        // BEFORE ReleaseStage uploads them.
        let p = build_publish_only_pipeline();
        let names = p.stage_names();
        let sign_idx = names
            .iter()
            .position(|n| *n == "sign")
            .expect("publish-only pipeline must include sign stage");
        let release_idx = names
            .iter()
            .position(|n| *n == "release")
            .expect("publish-only pipeline must include release stage");
        assert!(
            sign_idx < release_idx,
            "sign (idx {sign_idx}) must precede release (idx {release_idx}); got {names:?}"
        );
    }

    #[test]
    fn publish_only_pipeline_runs_docker_after_release_before_publish() {
        // Docker build+sign must sit between the GitHub release and the
        // publish stage: the mcp publisher (inside PublishStage) validates
        // that the OCI image its manifest references already exists, so the
        // image must be built and pushed before publish runs.
        let p = build_publish_only_pipeline();
        let names = p.stage_names();
        let release_idx = names
            .iter()
            .position(|n| *n == "release")
            .expect("publish-only pipeline must include release stage");
        let docker_idx = names
            .iter()
            .position(|n| *n == "docker")
            .expect("publish-only pipeline must include docker stage");
        let docker_sign_idx = names
            .iter()
            .position(|n| *n == "docker-sign")
            .expect("publish-only pipeline must include docker-sign stage");
        let publish_idx = names
            .iter()
            .position(|n| *n == "publish")
            .expect("publish-only pipeline must include publish stage");
        assert!(
            release_idx < docker_idx,
            "docker (idx {docker_idx}) must follow release (idx {release_idx}); got {names:?}"
        );
        assert!(
            docker_idx < docker_sign_idx,
            "docker-sign (idx {docker_sign_idx}) must follow docker (idx {docker_idx}); got {names:?}"
        );
        assert!(
            docker_sign_idx < publish_idx,
            "docker-sign (idx {docker_sign_idx}) must precede publish (idx {publish_idx}); got {names:?}"
        );
    }

    #[test]
    fn publish_only_pipeline_runs_changelog_before_release() {
        // ReleaseStage::build_release_json reads ctx.stage_outputs.changelogs;
        // without ChangelogStage ahead of it the GitHub release body would
        // be empty even though the project configures `changelog.use:
        // github-native`. ChangelogStage at the head also costs no signing
        // work if its GitHub API call fails.
        let p = build_publish_only_pipeline();
        let names = p.stage_names();
        let changelog_idx = names
            .iter()
            .position(|n| *n == "changelog")
            .expect("publish-only pipeline must include changelog stage");
        let release_idx = names
            .iter()
            .position(|n| *n == "release")
            .expect("publish-only pipeline must include release stage");
        assert!(
            changelog_idx < release_idx,
            "changelog (idx {changelog_idx}) must precede release (idx {release_idx}); got {names:?}"
        );
    }

    /// Stage order: SignStage → ChecksumStage → PublishStage.
    /// ChecksumStage must follow Sign so signed bytes are what get
    /// hashed, and must precede Publish so every publisher
    /// (winget, chocolatey, scoop, krew, …) sees per-artifact
    /// `sha256` metadata its manifest schema requires.
    #[test]
    fn publish_only_pipeline_runs_checksum_before_publish_after_sign() {
        let p = build_publish_only_pipeline();
        let names = p.stage_names();
        let checksum_idx = names
            .iter()
            .position(|n| *n == "checksum")
            .expect("publish-only pipeline must include checksum stage");
        let sign_idx = names
            .iter()
            .position(|n| *n == "sign")
            .expect("publish-only pipeline must include sign stage");
        let publish_idx = names
            .iter()
            .position(|n| *n == "publish")
            .expect("publish-only pipeline must include publish stage");
        assert!(
            sign_idx < checksum_idx,
            "checksum (idx {checksum_idx}) must follow sign (idx {sign_idx}) so production-signed bytes get hashed; got {names:?}"
        );
        assert!(
            checksum_idx < publish_idx,
            "checksum (idx {checksum_idx}) must precede publish (idx {publish_idx}) so publishers see sha256 metadata; got {names:?}"
        );
    }

    /// Assert the terminal-stage invariant shared by every publishing
    /// pipeline (release / merge / publish-only): AnnounceStage follows the
    /// publisher chain so it only fires on a green release and the
    /// `required_publishers` gate sees the final publish report, and it is the
    /// last stage of the *publish phase* — immediately before the terminal
    /// `verify-release` post-publish report. `verify-release` runs AFTER
    /// announce (it needs the live release to verify against), so it, not
    /// announce, is the absolute final stage.
    fn assert_announce_then_verify_release_terminal(names: &[&str], label: &str) {
        let announce_idx = names
            .iter()
            .position(|n| *n == "announce")
            .unwrap_or_else(|| panic!("{label} must include announce stage"));
        let publish_idx = names
            .iter()
            .position(|n| *n == "publish")
            .unwrap_or_else(|| panic!("{label} must include publish stage"));
        let verify_release_idx = names
            .iter()
            .position(|n| *n == "verify-release")
            .unwrap_or_else(|| panic!("{label} must include verify-release stage"));
        assert!(
            announce_idx > publish_idx,
            "{label}: announce (idx {announce_idx}) must follow publish (idx {publish_idx}); got {names:?}"
        );
        assert_eq!(
            verify_release_idx,
            names.len() - 1,
            "{label}: verify-release must be the terminal post-publish stage; got {names:?}"
        );
        assert_eq!(
            announce_idx,
            verify_release_idx - 1,
            "{label}: announce must be the final publish-phase stage, immediately before the terminal verify-release report; got {names:?}"
        );
    }

    #[test]
    fn publish_only_pipeline_runs_announce_after_publish() {
        let p = build_publish_only_pipeline();
        let names = p.stage_names();
        assert_announce_then_verify_release_terminal(&names, "build_publish_only_pipeline");
    }

    #[test]
    fn release_pipeline_runs_announce_after_publish() {
        let p = build_release_pipeline();
        let names = p.stage_names();
        assert_announce_then_verify_release_terminal(&names, "build_release_pipeline");
    }

    #[test]
    fn merge_pipeline_runs_announce_after_publish() {
        let p = build_merge_pipeline();
        let names = p.stage_names();
        assert_announce_then_verify_release_terminal(&names, "build_merge_pipeline");
    }

    // -----------------------------------------------------------------------
    // before_publish: hooks
    // -----------------------------------------------------------------------

    /// Register a single sentinel archive artifact on the context. The
    /// before-publish stage runs once per matching artifact, so any test
    /// that asserts the hook executed (rather than asserting it didn't
    /// because of a filter / `if:` gate / dry-run) must seed at least
    /// one artifact for the per-artifact iteration to fire against.
    fn add_sentinel_archive(ctx: &mut anodizer_core::context::Context) {
        use anodizer_core::artifact::{Artifact, ArtifactKind};
        use std::collections::HashMap;
        use std::path::PathBuf;
        ctx.artifacts.add(Artifact {
            kind: ArtifactKind::Archive,
            path: PathBuf::from("dist/myapp_linux_amd64.tar.gz"),
            name: "myapp_linux_amd64.tar.gz".to_string(),
            target: Some("x86_64-unknown-linux-gnu".to_string()),
            crate_name: "myapp".to_string(),
            metadata: HashMap::new(),
            size: None,
        });
    }

    /// `release` pipeline: BeforePublishStage runs AFTER sign/checksum (the
    /// integrity stages) and BEFORE release/publish (the publish phase),
    /// so a non-zero hook can abort the release before any publisher writes
    /// to a registry.
    #[test]
    fn before_publish_runs_after_sbom_before_publish_dispatch() {
        let p = build_release_pipeline();
        let names = p.stage_names();
        let sbom_idx = names
            .iter()
            .position(|n| *n == "sbom")
            .expect("release pipeline must include sbom stage");
        let sign_idx = names
            .iter()
            .position(|n| *n == "sign")
            .expect("release pipeline must include sign stage");
        let checksum_idx = names
            .iter()
            .position(|n| *n == "checksum")
            .expect("release pipeline must include checksum stage");
        let before_publish_idx = names
            .iter()
            .position(|n| *n == "before-publish")
            .expect("release pipeline must include before-publish stage");
        let release_idx = names
            .iter()
            .position(|n| *n == "release")
            .expect("release pipeline must include release stage");
        let publish_idx = names
            .iter()
            .position(|n| *n == "publish")
            .expect("release pipeline must include publish stage");

        assert!(
            sbom_idx < before_publish_idx,
            "before-publish ({before_publish_idx}) must follow sbom ({sbom_idx}); got {names:?}"
        );
        assert!(
            sign_idx < before_publish_idx,
            "before-publish ({before_publish_idx}) must follow sign ({sign_idx}); got {names:?}"
        );
        assert!(
            checksum_idx < before_publish_idx,
            "before-publish ({before_publish_idx}) must follow checksum ({checksum_idx}); got {names:?}"
        );
        assert!(
            before_publish_idx < release_idx,
            "before-publish ({before_publish_idx}) must precede release ({release_idx}); got {names:?}"
        );
        assert!(
            before_publish_idx < publish_idx,
            "before-publish ({before_publish_idx}) must precede publish ({publish_idx}); got {names:?}"
        );
    }

    /// A hook exiting non-zero must surface as Err from the pipeline so the
    /// PublishStage never gets to dispatch. Verified by building a pipeline
    /// of `[BeforePublishStage, RecordingStage]` and asserting that
    /// RecordingStage never ran.
    #[test]
    fn before_publish_hook_failure_aborts_release_before_publish_dispatch() {
        use anodizer_core::config::{HookEntry, HooksConfig, StructuredHook};
        use anodizer_core::context::ContextOptions;
        use anodizer_core::hooks::BeforePublishStage;
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering};

        struct RecordingStage(Arc<AtomicBool>);
        impl anodizer_core::stage::Stage for RecordingStage {
            fn name(&self) -> &str {
                "publish"
            }
            fn run(&self, _ctx: &mut anodizer_core::context::Context) -> anyhow::Result<()> {
                self.0.store(true, Ordering::SeqCst);
                Ok(())
            }
        }

        let publish_ran = Arc::new(AtomicBool::new(false));

        let mut p = Pipeline::new();
        p.add(Box::new(BeforePublishStage));
        p.add(Box::new(RecordingStage(publish_ran.clone())));

        let mut config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        config.before_publish = Some(HooksConfig {
            hooks: Some(vec![HookEntry::Structured(StructuredHook {
                cmd: "exit 1".to_string(),
                ..Default::default()
            })]),
            post: None,
        });
        let mut ctx = anodizer_core::context::Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");
        add_sentinel_archive(&mut ctx);

        let log = ctx.logger("pipeline-test");
        let result = p.run(&mut ctx, &log);

        assert!(
            result.is_err(),
            "non-zero before_publish hook must abort the pipeline; got Ok",
        );
        assert!(
            !publish_ran.load(Ordering::SeqCst),
            "publish stage must NOT run after a failed before_publish hook",
        );
    }

    /// `--skip=before-publish` short-circuits the stage (the pipeline's
    /// generic skip handling fires before stage.run is invoked) AND lets
    /// every subsequent stage continue.
    #[test]
    fn before_publish_skip_via_cli_flag_logs_and_continues() {
        use anodizer_core::config::{HookEntry, HooksConfig, StructuredHook};
        use anodizer_core::context::ContextOptions;
        use anodizer_core::hooks::BeforePublishStage;
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering};

        struct SentinelStage(Arc<AtomicBool>);
        impl anodizer_core::stage::Stage for SentinelStage {
            fn name(&self) -> &str {
                "publish"
            }
            fn run(&self, _ctx: &mut anodizer_core::context::Context) -> anyhow::Result<()> {
                self.0.store(true, Ordering::SeqCst);
                Ok(())
            }
        }

        let publish_ran = Arc::new(AtomicBool::new(false));

        let mut p = Pipeline::new();
        p.add(Box::new(BeforePublishStage));
        p.add(Box::new(SentinelStage(publish_ran.clone())));

        let mut config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        // Configure a hook that would FAIL — `--skip` must prevent it from
        // running so subsequent stages still execute.
        config.before_publish = Some(HooksConfig {
            hooks: Some(vec![HookEntry::Structured(StructuredHook {
                cmd: "exit 1".to_string(),
                ..Default::default()
            })]),
            post: None,
        });

        let opts = ContextOptions {
            skip_stages: vec!["before-publish".to_string()],
            ..ContextOptions::default()
        };
        let mut ctx = anodizer_core::context::Context::new(config, opts);
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");

        let log = ctx.logger("pipeline-test");
        p.run(&mut ctx, &log)
            .expect("pipeline must succeed when before-publish is skipped");

        assert!(
            publish_ran.load(Ordering::SeqCst),
            "publish stage must run when before-publish is operator-skipped",
        );
    }

    /// Dry-run shape: the hook runner logs `[dry-run] before-publish hook: ...`
    /// instead of spawning the subprocess. Verified by asking the stage to
    /// run with a `exit 1` hook under dry-run; if the subprocess actually
    /// fired the pipeline would Err.
    #[test]
    fn before_publish_skip_via_cli_flag_via_dry_run() {
        use anodizer_core::config::{HookEntry, HooksConfig, StructuredHook};
        use anodizer_core::context::ContextOptions;
        use anodizer_core::hooks::BeforePublishStage;

        let mut p = Pipeline::new();
        p.add(Box::new(BeforePublishStage));

        let mut config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        config.before_publish = Some(HooksConfig {
            hooks: Some(vec![HookEntry::Structured(StructuredHook {
                cmd: "exit 1".to_string(),
                ..Default::default()
            })]),
            post: None,
        });

        let opts = ContextOptions {
            dry_run: true,
            ..ContextOptions::default()
        };
        let mut ctx = anodizer_core::context::Context::new(config, opts);
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");
        add_sentinel_archive(&mut ctx);

        let log = ctx.logger("pipeline-test");
        p.run(&mut ctx, &log)
            .expect("dry-run before_publish hook must NOT execute the subprocess");
    }

    /// `if: "{{ IsSnapshot }}"` skips when not a snapshot. Mirrors the shared
    /// `evaluate_if_condition` behavior exercised by build / archive / sign
    /// hooks — pinning the contract for before-publish too.
    #[test]
    fn before_publish_hook_if_condition_skip_when_falsy() {
        use anodizer_core::config::{HookEntry, HooksConfig, StructuredHook};
        use anodizer_core::context::ContextOptions;
        use anodizer_core::hooks::BeforePublishStage;

        let mut p = Pipeline::new();
        p.add(Box::new(BeforePublishStage));

        let mut config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        config.before_publish = Some(HooksConfig {
            hooks: Some(vec![HookEntry::Structured(StructuredHook {
                cmd: "exit 1".to_string(),
                if_condition: Some("{{ IsSnapshot }}".to_string()),
                ..Default::default()
            })]),
            post: None,
        });
        let mut ctx = anodizer_core::context::Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");
        ctx.template_vars_mut().set("IsSnapshot", "false");
        add_sentinel_archive(&mut ctx);

        let log = ctx.logger("pipeline-test");
        p.run(&mut ctx, &log)
            .expect("falsy `if:` must skip the hook so the exit-1 cmd never spawns");
    }

    /// `output: true` streams stdout to the StageLogger so operators see
    /// hook progress in real time. Verified by capturing tracing output.
    #[test]
    fn before_publish_hook_output_true_streams_logs() {
        use anodizer_core::config::{HookEntry, HooksConfig, StructuredHook};
        use anodizer_core::context::ContextOptions;
        use anodizer_core::hooks::BeforePublishStage;

        let mut p = Pipeline::new();
        p.add(Box::new(BeforePublishStage));

        let mut config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        config.before_publish = Some(HooksConfig {
            hooks: Some(vec![HookEntry::Structured(StructuredHook {
                cmd: "echo hello-from-before-publish".to_string(),
                output: Some(true),
                ..Default::default()
            })]),
            post: None,
        });
        let mut ctx = anodizer_core::context::Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");
        add_sentinel_archive(&mut ctx);

        let log = ctx.logger("pipeline-test");
        // The subprocess returns 0 and prints to stdout — the run must succeed.
        // `output: true` plumbing is identical to the shared `run_hooks` path
        // already exercised by `crates/core/src/hooks.rs::tests`; this test
        // pins the call site, not the output capture mechanism itself.
        p.run(&mut ctx, &log)
            .expect("echo hook must succeed under before-publish");
    }

    /// Per-hook `env:` propagates to the subprocess. Verified by running a
    /// hook whose cmd asserts `$FOO == bar` — exits non-zero if the env var
    /// is not visible.
    #[test]
    fn before_publish_hook_env_propagates() {
        use anodizer_core::config::{HookEntry, HooksConfig, StructuredHook};
        use anodizer_core::context::ContextOptions;
        use anodizer_core::hooks::BeforePublishStage;

        let mut p = Pipeline::new();
        p.add(Box::new(BeforePublishStage));

        let mut config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        config.before_publish = Some(HooksConfig {
            hooks: Some(vec![HookEntry::Structured(StructuredHook {
                cmd: r#"sh -c 'test "$FOO" = "bar"'"#.to_string(),
                env: Some(vec!["FOO=bar".to_string()]),
                ..Default::default()
            })]),
            post: None,
        });
        let mut ctx = anodizer_core::context::Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");
        add_sentinel_archive(&mut ctx);

        let log = ctx.logger("pipeline-test");
        p.run(&mut ctx, &log)
            .expect("per-hook env must reach the subprocess");
    }

    /// Shorthand form `before_publish: { hooks: ["echo foo"] }` parses as a
    /// `HookEntry::Simple` (same shape as top-level `before:` / `after:`).
    #[test]
    fn before_publish_string_form_parses() {
        use anodizer_core::config::{Config, HookEntry};

        let yaml = r#"
project_name: myapp
crates:
  - name: myapp
    path: ""
before_publish:
  hooks:
    - "echo foo"
"#;
        let cfg: Config = serde_yaml_ng::from_str(yaml).expect("parse yaml");
        let hooks = cfg
            .before_publish
            .as_ref()
            .expect("before_publish set")
            .hooks
            .as_ref()
            .expect("hooks set");
        assert_eq!(hooks.len(), 1);
        match &hooks[0] {
            HookEntry::Simple(s) => assert_eq!(s, "echo foo"),
            HookEntry::Structured(h) => panic!("expected Simple, got Structured({:?})", h),
        }
    }

    // -----------------------------------------------------------------------
    // before_publish per-artifact iteration
    // -----------------------------------------------------------------------

    /// Register N archives, one hook with `artifacts: archive`, and verify
    /// the rendered cmd carried each artifact's `ArtifactPath` exactly once.
    /// The hook writes one line per invocation into a tempfile so the test
    /// can count by reading the file back.
    #[test]
    fn before_publish_runs_per_matching_artifact() {
        use anodizer_core::artifact::{Artifact, ArtifactKind};
        use anodizer_core::config::{
            BeforePublishArtifactFilter, HookEntry, HooksConfig, StructuredHook,
        };
        use anodizer_core::context::ContextOptions;
        use anodizer_core::hooks::BeforePublishStage;
        use std::collections::HashMap;
        use std::path::PathBuf;

        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("hook-invocations.log");

        let mut p = Pipeline::new();
        p.add(Box::new(BeforePublishStage));

        let mut config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        config.before_publish = Some(HooksConfig {
            hooks: Some(vec![HookEntry::Structured(StructuredHook {
                cmd: format!("echo {{{{ ArtifactPath }}}} >> {}", sh_path(&log_path)),
                artifacts: Some(BeforePublishArtifactFilter::Archive),
                ..Default::default()
            })]),
            post: None,
        });
        let mut ctx = anodizer_core::context::Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");

        for i in 0..3 {
            ctx.artifacts.add(Artifact {
                kind: ArtifactKind::Archive,
                path: PathBuf::from(format!("dist/myapp_{i}.tar.gz")),
                name: format!("myapp_{i}.tar.gz"),
                target: Some("x86_64-unknown-linux-gnu".to_string()),
                crate_name: "myapp".to_string(),
                metadata: HashMap::new(),
                size: None,
            });
        }

        let log = ctx.logger("pipeline-test");
        p.run(&mut ctx, &log)
            .expect("per-artifact iteration must succeed");

        let contents = fs::read_to_string(&log_path).expect("log file exists");
        let lines: Vec<&str> = contents.lines().filter(|l| !l.is_empty()).collect();
        assert_eq!(lines.len(), 3, "hook should run 3 times, got: {lines:?}");
        for i in 0..3 {
            let expected = format!("dist/myapp_{i}.tar.gz");
            assert!(
                lines.iter().any(|l| l == &expected),
                "missing iteration for {expected}; got {lines:?}"
            );
        }
    }

    /// `ids: [a]` restricts iteration to artifacts whose `metadata["id"] == "a"`.
    /// Register two archives with ids `a` and `b`; only `a` should fire.
    #[test]
    fn before_publish_ids_filter_narrows_to_subset() {
        use anodizer_core::artifact::{Artifact, ArtifactKind};
        use anodizer_core::config::{HookEntry, HooksConfig, StructuredHook};
        use anodizer_core::context::ContextOptions;
        use anodizer_core::hooks::BeforePublishStage;
        use std::collections::HashMap;
        use std::path::PathBuf;

        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("ids-filter.log");

        let mut p = Pipeline::new();
        p.add(Box::new(BeforePublishStage));

        let mut config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        config.before_publish = Some(HooksConfig {
            hooks: Some(vec![HookEntry::Structured(StructuredHook {
                cmd: format!("echo {{{{ ArtifactID }}}} >> {}", sh_path(&log_path)),
                ids: Some(vec!["a".to_string()]),
                ..Default::default()
            })]),
            post: None,
        });
        let mut ctx = anodizer_core::context::Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");

        for id in &["a", "b"] {
            let mut meta = HashMap::new();
            meta.insert("id".to_string(), (*id).to_string());
            ctx.artifacts.add(Artifact {
                kind: ArtifactKind::Archive,
                path: PathBuf::from(format!("dist/myapp-{id}.tar.gz")),
                name: format!("myapp-{id}.tar.gz"),
                target: Some("x86_64-unknown-linux-gnu".to_string()),
                crate_name: "myapp".to_string(),
                metadata: meta,
                size: None,
            });
        }

        let log = ctx.logger("pipeline-test");
        p.run(&mut ctx, &log).expect("ids filter must not error");

        let contents = fs::read_to_string(&log_path).expect("log file exists");
        let lines: Vec<&str> = contents.lines().filter(|l| !l.is_empty()).collect();
        assert_eq!(lines, vec!["a"], "only id=a should match; got {lines:?}");
    }

    /// `artifacts: archive` excludes a binary artifact: register one binary
    /// and one archive, then verify only the archive triggered the hook.
    #[test]
    fn before_publish_artifacts_filter_excludes_non_matching_kinds() {
        use anodizer_core::artifact::{Artifact, ArtifactKind};
        use anodizer_core::config::{
            BeforePublishArtifactFilter, HookEntry, HooksConfig, StructuredHook,
        };
        use anodizer_core::context::ContextOptions;
        use anodizer_core::hooks::BeforePublishStage;
        use std::collections::HashMap;
        use std::path::PathBuf;

        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("kind-filter.log");

        let mut p = Pipeline::new();
        p.add(Box::new(BeforePublishStage));

        let mut config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        config.before_publish = Some(HooksConfig {
            hooks: Some(vec![HookEntry::Structured(StructuredHook {
                cmd: format!(
                    "echo {{{{ ArtifactKind }}}}={{{{ ArtifactName }}}} >> {}",
                    sh_path(&log_path)
                ),
                artifacts: Some(BeforePublishArtifactFilter::Archive),
                ..Default::default()
            })]),
            post: None,
        });
        let mut ctx = anodizer_core::context::Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");

        ctx.artifacts.add(Artifact {
            kind: ArtifactKind::Binary,
            path: PathBuf::from("dist/myapp"),
            name: "myapp".to_string(),
            target: Some("x86_64-unknown-linux-gnu".to_string()),
            crate_name: "myapp".to_string(),
            metadata: HashMap::new(),
            size: None,
        });
        ctx.artifacts.add(Artifact {
            kind: ArtifactKind::Archive,
            path: PathBuf::from("dist/myapp.tar.gz"),
            name: "myapp.tar.gz".to_string(),
            target: Some("x86_64-unknown-linux-gnu".to_string()),
            crate_name: "myapp".to_string(),
            metadata: HashMap::new(),
            size: None,
        });

        let log = ctx.logger("pipeline-test");
        p.run(&mut ctx, &log)
            .expect("archive filter must not error");

        let contents = fs::read_to_string(&log_path).expect("log file exists");
        let lines: Vec<&str> = contents.lines().filter(|l| !l.is_empty()).collect();
        assert_eq!(
            lines,
            vec!["archive=myapp.tar.gz"],
            "archive filter must skip binary; got {lines:?}"
        );
    }

    /// Per-artifact template variables (`ArtifactPath`, `ArtifactName`,
    /// `ArtifactExt`, `Os`, `Arch`) all render correctly for each
    /// iteration.
    #[test]
    fn before_publish_template_artifact_vars_bound() {
        use anodizer_core::artifact::{Artifact, ArtifactKind};
        use anodizer_core::config::{HookEntry, HooksConfig, StructuredHook};
        use anodizer_core::context::ContextOptions;
        use anodizer_core::hooks::BeforePublishStage;
        use std::collections::HashMap;
        use std::path::PathBuf;

        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("vars.log");

        let mut p = Pipeline::new();
        p.add(Box::new(BeforePublishStage));

        let mut config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        // Each `{{ Var }}` renders to a token; the cmd writes them
        // space-separated onto one line. The pipe character is
        // deliberately avoided (it has shell meaning under `sh -c`).
        config.before_publish = Some(HooksConfig {
            hooks: Some(vec![HookEntry::Structured(StructuredHook {
                cmd: format!(
                    "printf '%s %s %s %s %s\\n' {{{{ ArtifactPath }}}} {{{{ ArtifactName }}}} {{{{ ArtifactExt }}}} {{{{ Os }}}} {{{{ Arch }}}} >> {}",
                    sh_path(&log_path)
                ),
                ..Default::default()
            })]),
            post: None,
        });
        let mut ctx = anodizer_core::context::Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");

        ctx.artifacts.add(Artifact {
            kind: ArtifactKind::Archive,
            path: PathBuf::from("dist/myapp_linux_amd64.tar.gz"),
            name: "myapp_linux_amd64.tar.gz".to_string(),
            target: Some("x86_64-unknown-linux-gnu".to_string()),
            crate_name: "myapp".to_string(),
            metadata: HashMap::new(),
            size: None,
        });

        let log = ctx.logger("pipeline-test");
        p.run(&mut ctx, &log)
            .expect("template-vars hook must succeed");

        let contents = fs::read_to_string(&log_path).expect("log file exists");
        let line = contents.lines().next().expect("at least one line").trim();
        assert_eq!(
            line, "dist/myapp_linux_amd64.tar.gz myapp_linux_amd64.tar.gz .tar.gz linux amd64",
            "all per-artifact template vars must bind; got {line:?}"
        );
    }

    /// A hook command that exits non-zero on the second artifact aborts the
    /// pipeline so the publish stage never dispatches. The cmd writes its
    /// own iteration count to disk and exits 1 once it sees two
    /// invocations.
    #[test]
    fn before_publish_failure_on_any_artifact_aborts_release() {
        use anodizer_core::artifact::{Artifact, ArtifactKind};
        use anodizer_core::config::{HookEntry, HooksConfig, StructuredHook};
        use anodizer_core::context::ContextOptions;
        use anodizer_core::hooks::BeforePublishStage;
        use std::collections::HashMap;
        use std::path::PathBuf;
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering};

        struct RecordingStage(Arc<AtomicBool>);
        impl anodizer_core::stage::Stage for RecordingStage {
            fn name(&self) -> &str {
                "publish"
            }
            fn run(&self, _ctx: &mut anodizer_core::context::Context) -> anyhow::Result<()> {
                self.0.store(true, Ordering::SeqCst);
                Ok(())
            }
        }

        let publish_ran = Arc::new(AtomicBool::new(false));
        let tmp = TempDir::new().unwrap();
        let counter_path = tmp.path().join("counter");

        let mut p = Pipeline::new();
        p.add(Box::new(BeforePublishStage));
        p.add(Box::new(RecordingStage(publish_ran.clone())));

        let mut config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        // The cmd appends a byte per invocation; when the file size reaches
        // 2, it exits 1 — so the second artifact's iteration fails.
        let cmd = format!(
            r#"sh -c 'printf x >> {p}; if [ "$(wc -c < {p})" -ge 2 ]; then exit 1; fi'"#,
            p = sh_path(&counter_path),
        );
        config.before_publish = Some(HooksConfig {
            hooks: Some(vec![HookEntry::Structured(StructuredHook {
                cmd,
                ..Default::default()
            })]),
            post: None,
        });
        let mut ctx = anodizer_core::context::Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");

        for i in 0..3 {
            ctx.artifacts.add(Artifact {
                kind: ArtifactKind::Archive,
                path: PathBuf::from(format!("dist/myapp_{i}.tar.gz")),
                name: format!("myapp_{i}.tar.gz"),
                target: Some("x86_64-unknown-linux-gnu".to_string()),
                crate_name: "myapp".to_string(),
                metadata: HashMap::new(),
                size: None,
            });
        }

        let log = ctx.logger("pipeline-test");
        let result = p.run(&mut ctx, &log);
        assert!(
            result.is_err(),
            "hook failure on any artifact must abort the pipeline",
        );
        assert!(
            !publish_ran.load(Ordering::SeqCst),
            "publish stage must NOT run after a mid-iteration hook failure",
        );
        let count = fs::read_to_string(&counter_path)
            .map(|s| s.len())
            .unwrap_or(0);
        assert_eq!(
            count, 2,
            "hook should have run exactly twice before aborting; got {count}",
        );
    }

    /// Omitting `artifacts:` is equivalent to `all`: the hook fires against
    /// every registered artifact regardless of kind.
    #[test]
    fn before_publish_artifacts_all_default_matches_everything() {
        use anodizer_core::artifact::{Artifact, ArtifactKind};
        use anodizer_core::config::{HookEntry, HooksConfig, StructuredHook};
        use anodizer_core::context::ContextOptions;
        use anodizer_core::hooks::BeforePublishStage;
        use std::collections::HashMap;
        use std::path::PathBuf;

        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("default-all.log");

        let mut p = Pipeline::new();
        p.add(Box::new(BeforePublishStage));

        let mut config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        config.before_publish = Some(HooksConfig {
            hooks: Some(vec![HookEntry::Structured(StructuredHook {
                cmd: format!("echo {{{{ ArtifactKind }}}} >> {}", sh_path(&log_path)),
                ..Default::default()
            })]),
            post: None,
        });
        let mut ctx = anodizer_core::context::Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");

        let kinds = [
            ArtifactKind::Binary,
            ArtifactKind::Archive,
            ArtifactKind::Checksum,
            ArtifactKind::Sbom,
        ];
        for (i, kind) in kinds.iter().enumerate() {
            ctx.artifacts.add(Artifact {
                kind: *kind,
                path: PathBuf::from(format!("dist/a{i}")),
                name: format!("a{i}"),
                target: None,
                crate_name: "myapp".to_string(),
                metadata: HashMap::new(),
                size: None,
            });
        }

        let log = ctx.logger("pipeline-test");
        p.run(&mut ctx, &log)
            .expect("default-all filter must fire for every artifact");

        let contents = fs::read_to_string(&log_path).expect("log file exists");
        let mut lines: Vec<&str> = contents.lines().filter(|l| !l.is_empty()).collect();
        lines.sort();
        assert_eq!(
            lines,
            vec!["archive", "binary", "checksum", "sbom"],
            "default (artifacts: all) must match every kind; got {lines:?}"
        );
    }

    // -----------------------------------------------------------------------
    // Pipeline-level emit_summary contract.
    //
    // Pipeline::run must ALWAYS invoke `emit_summary` (regardless of
    // whether `AnnounceStage::run` was reached). The unit tests in
    // `stage-announce` pin the stage-side contract; this test pins the
    // pipeline-side contract — specifically that `--skip=announce`
    // doesn't drop `--summary-json`.
    // -----------------------------------------------------------------------

    /// A `Stage` that always returns `Err`. Pins the "emit_summary
    /// fires even on inner-fn Err" half of `Pipeline::run`'s contract.
    /// Kept private to the test module.
    struct AlwaysFailStage;
    impl anodizer_core::stage::Stage for AlwaysFailStage {
        fn name(&self) -> &str {
            "always-fail"
        }
        fn run(&self, _ctx: &mut anodizer_core::context::Context) -> anyhow::Result<()> {
            anyhow::bail!("synthetic stage failure for the I-3 test")
        }
    }

    #[test]
    fn pipeline_emits_summary_even_when_inner_stage_returns_err() {
        // The inner-fn scope-guard shape in `Pipeline::run` must
        // invoke `emit_summary` on Err too, not just on Ok. Without
        // this test, only the doc line pinned the contract; this
        // puts a bisectable green/red signal on the Err path.
        use anodizer_core::context::ContextOptions;

        let tmp = TempDir::new().expect("tempdir");
        let summary_path = tmp.path().join("summary.json");

        let mut p = Pipeline::new();
        p.add(Box::new(AlwaysFailStage));

        let opts = ContextOptions {
            summary_json_path: Some(summary_path.clone()),
            ..ContextOptions::default()
        };
        let config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        let mut ctx = anodizer_core::context::Context::new(config, opts);
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");
        ctx.publish_report = Some(anodizer_core::publish_report::PublishReport::default());

        let log = ctx.logger("pipeline-test");
        let result = p.run(&mut ctx, &log);

        assert!(
            result.is_err(),
            "pipeline must propagate the stage's Err verbatim",
        );
        assert!(
            summary_path.exists(),
            "summary.json must be written even when the inner pipeline body returns Err",
        );
    }

    #[test]
    fn pipeline_emits_summary_when_announce_is_skipped_via_skip_flag() {
        use anodizer_core::context::ContextOptions;
        use anodizer_stage_announce::AnnounceStage;

        let tmp = TempDir::new().expect("tempdir");
        let summary_path = tmp.path().join("summary.json");

        // Build a pipeline whose only stage is AnnounceStage and skip
        // it via `--skip=announce`. The summary still lands on disk
        // because Pipeline::run owns emit_summary and invokes it after
        // the stage loop, regardless of whether the stage ran.
        let mut p = Pipeline::new();
        p.add(Box::new(AnnounceStage));

        let opts = ContextOptions {
            summary_json_path: Some(summary_path.clone()),
            skip_stages: vec!["announce".to_string()],
            ..ContextOptions::default()
        };
        let config = anodizer_core::config::Config {
            project_name: "myapp".to_string(),
            ..Default::default()
        };
        let mut ctx = anodizer_core::context::Context::new(config, opts);
        ctx.template_vars_mut().set("Tag", "v9.9.9-test");
        ctx.publish_report = Some(anodizer_core::publish_report::PublishReport::default());

        let log = ctx.logger("pipeline-test");
        p.run(&mut ctx, &log).expect("pipeline run");

        // The stage was skipped — but the summary must STILL be written.
        // Regression: an earlier shape put emit_summary inside
        // AnnounceStage::run, where a skipped stage never reached it.
        // Pipeline must own emit_summary so operator-skip can't suppress
        // the summary side-effect.
        assert!(
            summary_path.exists(),
            "summary.json must be written even when announce is operator-skipped",
        );
    }
}