anodizer 0.4.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
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
//! `anodize release --publish-only`: consume a `dist/` populated by
//! `anodize check determinism --preserve-dist=<path>` and run only the
//! sign + publish pipeline.
//!
//! The harness writes:
//! - `<preserved-dist>/**` — the byte-stable artifacts the determinism
//!   check just verified (archives, packages, sboms, checksums,
//!   `artifacts.json`, `metadata.json`).
//! - `<preserved-dist>/context.json` — a [`PreservedDistContext`]
//!   manifest pinning `(artifacts, targets, version, commit)`.
//!
//! This mode loads both, rehydrates `ctx.artifacts` from
//! `dist/artifacts.json` (the in-process registry shape — the manifest
//! the post-pipeline already writes), strips any leftover
//! `Signature` / `Certificate` artifacts the harness may have produced
//! with ephemeral keys, then runs an extended publish pipeline that
//! prepends `SignStage` (production-keys sign pass) ahead of the usual
//! release / publish / blob / snapcraft-publish chain.
//!
//! Idempotence: the harness skips its in-loop `SignStage` when
//! production keys are exported on the runner (`COSIGN_KEY` /
//! `GPG_PRIVATE_KEY`), so preserved-dist usually has no `.sig` /
//! `.asc` files. This module's defensive strip exists for the case
//! where that gate didn't fire (harness ran without prod keys then
//! operator brought them in later, etc.) — re-signing on top of an
//! existing signature chain would produce `*.sig.sig` chaos.
//!
//! Pipeline choice: the merge pipeline assumes raw-binary input from
//! `--split`. `--publish-only` deliberately bypasses that assumption:
//! input is the FULL artifact set (binaries + archives + packages +
//! checksums), so we run `build_publish_only_pipeline` (see
//! `crate::pipeline`), not `build_merge_pipeline`.

use anyhow::{Context as _, Result};
use std::path::{Path, PathBuf};

use anodizer_core::config::Config;
use anodizer_core::context::Context;
use anodizer_core::git::short_commit_str;
use anodizer_core::log::StageLogger;

use super::helpers;
use crate::pipeline;

/// Names of the env vars that gate the publish-only credential
/// preflight. Documented as a single source of truth so the error
/// message and the check itself stay in lockstep.
const SIGN_ENV_VARS: &[&str] = &["COSIGN_KEY", "GPG_PRIVATE_KEY"];
const GITHUB_TOKEN_ENV_VARS: &[&str] = &["GITHUB_TOKEN", "ANODIZER_GITHUB_TOKEN"];

/// Knobs the dispatcher hands to `publish_only::run`. Reduces the
/// number of positional arguments and lets the dispatch site speak
/// in terms of flag intent (`no_preflight`) rather than the threaded
/// `--<flag>` boolean it came from.
pub(super) struct RunOpts {
    pub dry_run: bool,
    /// `--no-preflight`: skip the credential preflight as well as the
    /// publisher-state preflight. Operator opt-out for the case
    /// where they know what they're doing and want the mid-pipeline
    /// failure to surface instead.
    pub no_preflight: bool,
}

/// `--publish-only` entry point. Wired from `commands/release/mod.rs::run`
/// after `setup_context` / git context / preflight have already run on
/// `ctx`.
pub(super) fn run(
    ctx: &mut Context,
    config: &Config,
    log: &StageLogger,
    opts: RunOpts,
) -> Result<()> {
    log.status("running in publish-only mode (load preserved dist + sign + publish)...");

    let dist = config.dist.clone();

    // ── Pre-flight credential check ────────────────────────────────────
    // Bail BEFORE any state mutation: a credential miss this late
    // (mid-pipeline) leaves a partially-uploaded release behind with no
    // idempotent recovery. Dry-run skips so operators can preview the
    // pipeline without secrets; `--no-preflight` is the explicit
    // operator opt-out for the rare case where they want the
    // mid-pipeline failure instead.
    if opts.dry_run {
        log.verbose("(dry-run) skipping production-credential preflight");
    } else if opts.no_preflight {
        log.warn(
            "credential preflight skipped via --no-preflight; \
             missing credentials will fail mid-pipeline (no idempotent recovery)",
        );
    } else {
        preflight_credentials(|k| std::env::var(k).ok())?;
    }

    // ── Suppress binary_signs ─────────────────────────────────────────
    // Publish-only cannot produce shippable binary signatures: raw
    // binaries live at `.det-tmp/target/<triple>/release/<bin>` in the
    // harness's worktree, which is NOT preserved into `dist/`. cosign
    // sign-blob inside SignStage would crash trying to read the missing
    // path. Clear the list early and warn the operator so they know
    // binary-level signatures aren't ever produced in this mode.
    //
    // Workaround for callers that need signed binaries: configure
    // archive-level `signs:` (binaries inside an archive get the
    // archive's signature), or sign at consumer-side via cosign
    // verify-blob against the binaries inside the released archive.
    if !ctx.config.binary_signs.is_empty() {
        let n = ctx.config.binary_signs.len();
        log.warn(&format!(
            "publish-only: suppressing {n} binary_signs entrie(s); raw binaries are not \
             preserved into dist/ by the determinism harness, so binary-level signatures \
             cannot be (re-)produced in this mode. Configure archive-level signs: or sign \
             on the consumer side."
        ));
        ctx.config.binary_signs.clear();
    }

    // ── Load preserved-dist context ────────────────────────────────────
    // Two manifest families live in `<dist>/`:
    //   - `artifacts.json` / `artifacts-<shard>.json`: the canonical
    //     in-process registry shape (`kind` / `target` / `metadata`),
    //     same as `anodize publish` consumes. Each shard emits its own.
    //   - `context.json` / `context-<shard>.json`: the harness's
    //     `PreservedDistContext` summary with per-artifact `sha256` +
    //     `size` recorded at preserve time. Each shard emits its own.
    //
    // The sharded release workflow uploads each shard's dist tree under
    // `dist-<shard>` and the action renames the per-shard manifests so
    // download-artifact's `merge-multiple: true` doesn't collide on
    // identically-named files. Discovery here folds them all back in.
    //
    // The legacy single-`context.json` layout (operator running locally
    // without sharding) keeps working — `discover_preserved_contexts`
    // matches both the un-suffixed and the suffixed forms.
    //
    // Detect the upload-artifact merge-collision symptom BEFORE
    // loading anything: both un-suffixed AND suffixed manifests
    // present is a workflow bug we should never silently paper over.
    check_no_unsuffixed_suffixed_collision(&dist, "context")?;
    check_no_unsuffixed_suffixed_collision(&dist, "artifacts")?;

    let preserved_contexts = discover_preserved_contexts(&dist)?;
    let preserved = merge_preserved_contexts(&preserved_contexts)?;
    let shard_count = preserved_contexts.len();

    log.status(&format!(
        "publish-only: loaded {} context manifest(s) (version={}, commit={}, targets=[{}], {} artifact(s))",
        shard_count,
        preserved.version,
        short_commit_str(&preserved.commit),
        preserved.targets.join(", "),
        preserved.artifacts.len(),
    ));

    // Pin the determinism-check → publish-only safety invariant: hash
    // every preserved artifact's bytes BEFORE the commit cross-check
    // and any registry mutation. A mismatch here means the dist tree
    // is no longer the bytes the harness verified — refuse to ship
    // rather than re-sign corrupted input.
    hash_verify_preserved_dist(&preserved, &dist)?;

    // Commit / version cross-checks across shards now live inside
    // `merge_preserved_contexts` — they're part of the merge contract,
    // not a separate post-processing step.
    let ctx_commit = ctx
        .template_vars()
        .get("FullCommit")
        .cloned()
        .unwrap_or_default();
    if ctx_commit.is_empty() {
        anyhow::bail!(
            "publish-only: current release context has no resolved commit. \
             Run from a tagged commit (`git checkout {}`) before --publish-only.",
            short_commit_str(&preserved.commit),
        );
    }
    if ctx_commit != preserved.commit {
        anyhow::bail!(
            "publish-only: context manifest was preserved at commit {} but the current \
             release context resolved to commit {}. Re-signing the preserved bytes \
             under the current commit's tag would ship signatures that don't match \
             the determinism-verified state. `git checkout {}` then retry.",
            short_commit_str(&preserved.commit),
            short_commit_str(&ctx_commit),
            short_commit_str(&preserved.commit),
        );
    }

    // ── Rehydrate ctx.artifacts ────────────────────────────────────────
    // Delegates to the same loader `anodize publish` uses so the two
    // entry points stay in lockstep (one parser to maintain). Each
    // shard's manifest contributes its artifacts to the registry.
    let artifact_manifests = discover_artifacts_manifests(&dist)?;
    for manifest_path in &artifact_manifests {
        helpers::load_artifacts_from_manifest(ctx, &dist, manifest_path).with_context(|| {
            format!(
                "publish-only: failed to load {} from {}. The preserve-dist \
                 flow normally copies these from the harness's worktree post-pipeline; \
                 if any is missing the preserved dist is incomplete.",
                manifest_path.display(),
                dist.display()
            )
        })?;
    }

    // Cross-shard cross-target artifacts (source archive, install.sh,
    // metadata.json — all `target: None`) appear in every shard's
    // manifest by design. Each shard's harness runs them identically;
    // download-artifact merge-multiple collapses the on-disk copies to
    // one. Drop the redundant registry entries here so SignStage /
    // ReleaseStage don't try to re-sign or re-upload the same path
    // multiple times. Per-target duplicates (matrix overlap bugs) are
    // preserved so `detect_duplicate_artifact_paths` below still
    // catches them.
    ctx.artifacts.dedupe_targetless_duplicates();

    log.status(&format!(
        "publish-only: rehydrated {} artifact(s) from {} artifacts manifest(s)",
        ctx.artifacts.all().len(),
        artifact_manifests.len(),
    ));

    // Fail closed on duplicate artifact paths across the merged
    // manifests. After dedup of cross-shard cross-target duplicates
    // (source.tar.gz, install.sh, metadata.json — target: None,
    // produced identically on every shard), any remaining same-path
    // entry must come from a per-target overlap: two shards both
    // claimed they built for the same target. That's a matrix bug or
    // hand-edited manifest; re-signing duplicate entries would
    // produce double-emit confusion in SignStage / ReleaseStage.
    detect_duplicate_artifact_paths(ctx)?;

    // ── Strip ephemeral signatures / certificates ──────────────────────
    // Defensive: the harness skips SignStage when production keys are
    // exported on the runner, so preserved-dist usually has no `.sig`
    // / `.asc` files. But re-signing on top of an existing chain (e.g.
    // operator ran the harness without prod keys, then brought them
    // in) would emit `*.sig.sig` / `*.pem.sig` — corrupt checksums
    // and confuse downstream verifiers. Strip up-front so `SignStage`
    // always sees a clean input registry.
    //
    // Runs BEFORE `detect_missing_files`: any Signature / Certificate
    // entry that lives under `.det-tmp/target/.../<bin>.sig` is a
    // per-binary signature the harness produced when `binary_signs` was
    // configured. `upload-artifact@v4` excludes hidden directories
    // (`.det-tmp/`) by default, so those paths never reach the publish
    // job's disk. Stripping the registry entries here makes them invisible
    // to the existence check below — they'd otherwise trip a false
    // "preserved dist is incomplete" bail. SignStage doesn't re-create
    // binary signatures in publish-only mode (binary_signs is cleared
    // above), which matches the action's hidden-files-excluded reality.
    strip_ephemeral_signatures(ctx, log);

    // Filesystem vs manifest cross-check: every artifact path the
    // manifest references must actually exist on disk. Missing files
    // means the preserved dist is incomplete — running through to
    // SignStage would fail with a less actionable error from
    // cosign/gpg, so we surface it here with a manifest-shaped
    // diagnostic instead. We do NOT flag unreferenced files (the
    // dist tree carries metadata.json, harness logs, etc. that aren't
    // in the artifacts manifest).
    //
    // Skipped artifact kinds:
    //   * Binary + UniversalBinary — paths under `.det-tmp/target/...`
    //     are intermediate raw cargo output, never preserved. Publishers
    //     that consume Binary artifacts (nix's DynamicallyLinked,
    //     winget's binary filename) read ONLY metadata, not the file
    //     itself, so the path mismatch is harmless.
    //   * Metadata — `dist/metadata.json` is renamed per-shard by the
    //     action's preserve step (`metadata-<shard>.json`) before
    //     upload, so the canonical un-suffixed path NEVER exists on the
    //     publish job's disk pre-pipeline. `run_post_pipeline` rewrites
    //     the canonical file at the end of publish-only from the merged
    //     registry, so the existence check is trying to verify a file
    //     this pipeline itself will produce — a layering violation.
    crate::commands::helpers::detect_missing_files(
        ctx.artifacts
            .all()
            .iter()
            .filter(|a| {
                !matches!(
                    a.kind,
                    anodizer_core::artifact::ArtifactKind::Binary
                        | anodizer_core::artifact::ArtifactKind::UniversalBinary
                        | anodizer_core::artifact::ArtifactKind::Metadata
                )
            })
            .map(|a| a.path.as_path()),
        &dist,
    )?;

    // ── Run the extended publish pipeline ──────────────────────────────
    // `build_publish_only_pipeline` prepends `SignStage` ahead of the
    // usual release / publish / blob / snapcraft-publish chain — the
    // head SignStage is the production-keys re-sign pass that overlays
    // shippable signatures on the byte-stable preserved archives.
    // Distinct from `build_publish_pipeline` (consumed by `anodize
    // publish`) which does NOT prepend SignStage; conflating them
    // would silently introduce a new credential requirement to
    // `anodize publish`.
    let p = pipeline::build_publish_only_pipeline();
    let result = p.run(ctx, log);

    if result.is_ok() {
        super::run_post_pipeline(ctx, config, opts.dry_run, log)?;

        // run_post_pipeline writes the canonical un-suffixed
        // artifacts.json from the merged registry. The per-shard
        // manifests (artifacts-*.json, context-*.json) that fed the
        // merge are no longer load-bearing, and their continued
        // presence next to the new un-suffixed file would trip
        // check_no_unsuffixed_suffixed_collision on a retry. Delete
        // them so a second invocation (operator-driven workflow rerun)
        // sees a clean canonical layout. Best-effort: by the time this
        // runs the release has already completed successfully, so a
        // remove failure is logged but never propagated.
        cleanup_shard_manifests(&dist, log);
    }

    // Same gate as `release` / `--merge`: required-publisher failures
    // must surface as a non-zero exit even though per-publisher
    // failures are non-fatal inside the pipeline body.
    if result.is_ok() {
        super::gate_required_failures(ctx)?;
    }

    result
}

/// Pre-flight credential check. Fires BEFORE any state mutation so a
/// credential miss doesn't leave a partially-uploaded release behind.
///
/// Required: a GitHub-shaped token (release stage needs to upload
/// assets / create the release) AND at least one of the production
/// signing keys (sign stage re-signs the preserved archives). Other
/// publisher credentials (chocolatey api key, AUR ssh key, etc.) are
/// per-publisher and surface at dispatch time — the pre-flight
/// publisher-state check (separate code path, runs before this branch
/// in `commands/release/mod.rs`) already validates them.
///
/// Pragmatic intentionally: the user is expected to drive
/// publish-only from CI where the secrets are exported into env
/// once. Re-deriving "which env vars matter per publisher" lives in
/// each stage's own preflight — duplicating it here would diverge.
///
/// **Env injection** (`env`): callers pass a closure that resolves
/// env-var names to values. The production caller delegates to
/// `std::env::var`; unit tests pass a pure closure so test execution
/// doesn't race with sibling tests on shared process env. This
/// mirrors how `stage-sign::helpers::should_sign_artifact` is
/// independently testable.
fn preflight_credentials(env: impl Fn(&str) -> Option<String>) -> Result<()> {
    let token_present = GITHUB_TOKEN_ENV_VARS
        .iter()
        .any(|v| env(v).map(|s| !s.is_empty()).unwrap_or(false));
    let sign_key_present = SIGN_ENV_VARS
        .iter()
        .any(|v| env(v).map(|s| !s.is_empty()).unwrap_or(false));

    if !token_present {
        anyhow::bail!(
            "publish-only: missing release token. Set one of {} before running --publish-only \
             (or pass --dry-run to preview without secrets).",
            GITHUB_TOKEN_ENV_VARS.join(" / "),
        );
    }
    if !sign_key_present {
        anyhow::bail!(
            "publish-only: missing production signing key. Set at least one of {} before \
             running --publish-only (or pass --dry-run to preview without secrets). \
             The harness's ephemeral signatures are NOT shippable — this mode exists \
             to overlay production signatures on the byte-stable artifacts.",
            SIGN_ENV_VARS.join(" / "),
        );
    }
    Ok(())
}

/// Strip `Signature` / `Certificate` artifacts the harness may have
/// left behind (with ephemeral keys). `SignStage`'s own
/// `should_sign_artifact` already filters Signature/Certificate kinds
/// out of the `all`/`any` artifacts set so a no-op re-sign wouldn't
/// emit `.sig.sig`, but the resulting registry would still include
/// the ephemeral artifacts — which then get UPLOADED by `ReleaseStage`.
/// We must remove them at the source.
///
/// Symmetry note: any non-signature/certificate artifact remains
/// untouched, including any `Checksum` entries — re-signing produces
/// a new signature blob but the underlying archive bytes (which the
/// checksums are computed from) are unchanged, so the checksums
/// still match. `ChecksumStage` is intentionally not in the publish
/// pipeline for the same reason: nothing to recompute.
fn strip_ephemeral_signatures(ctx: &mut Context, log: &StageLogger) {
    use anodizer_core::artifact::ArtifactKind;
    let stale_paths: Vec<std::path::PathBuf> = ctx
        .artifacts
        .all()
        .iter()
        .filter(|a| matches!(a.kind, ArtifactKind::Signature | ArtifactKind::Certificate))
        .map(|a| a.path.clone())
        .collect();
    if stale_paths.is_empty() {
        return;
    }
    let count = stale_paths.len();
    log.status(&format!(
        "publish-only: stripping {count} ephemeral signature/certificate artifact(s) before re-sign"
    ));
    // Registry FIRST, then disk. If the process is signaled between
    // the two steps, a retry sees a consistent state: the registry
    // has no dangling entries that point at files the next run is
    // about to find on disk anyway (SignStage will overwrite them
    // cleanly). The reverse order leaves a window where the file is
    // gone but the registry still references it — a follow-up
    // ArtifactKind::Signature lookup would then find a phantom.
    ctx.artifacts.remove_by_paths(&stale_paths);
    // Now delete on-disk files so the next sign-stage doesn't see
    // a leftover `.sig` next to its target and produce a `*.sig.sig`
    // through the user's own sign-args template (which typically reads
    // `{{ .Signature }} = {{ .Artifact }}.sig`).
    let mut disk_removed = 0usize;
    for p in &stale_paths {
        match std::fs::remove_file(p) {
            Ok(()) => disk_removed += 1,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => log.warn(&format!(
                "publish-only: failed to delete stale signature {}: {} \
                 (continuing; SignStage will overwrite or fail loudly)",
                p.display(),
                e
            )),
        }
    }
    // Positive success signal so the operator sees the strip happened
    // (counter-balances the lone "stripping N..." line above which
    // could otherwise look like the work stalled). Reports both the
    // registry-side removal count (always equal to `count`) and the
    // disk-side count (may be lower if a sig was already absent on
    // disk — registry entries can outlive their files when the
    // post-pipeline runs partial writes).
    log.status(&format!(
        "publish-only: stripped {count} ephemeral signature artifact(s) from registry \
         ({disk_removed} also deleted from disk)"
    ));
}

/// Walk `ctx.artifacts` grouped by `path` and fail if any path appears
/// more than once. Called post-rehydration so a sharded matrix that
/// accidentally overlapped on a target surfaces as a hard error rather
/// than a double-publish downstream.
///
/// Thin wrapper over `commands::helpers::detect_duplicate_paths` that
/// projects the artifact iter into a path iter.
fn detect_duplicate_artifact_paths(ctx: &Context) -> Result<()> {
    crate::commands::helpers::detect_duplicate_paths(
        ctx.artifacts.all().iter().map(|a| a.path.as_path()),
    )
}

/// Minimal `PreservedDistContext` deserializer. We re-declare the
/// shape here rather than depending on `determinism_harness::preserve`
/// to keep this module decoupled from harness internals — the
/// schema (artifacts + targets + version + commit) is the
/// load-bearing contract, not the producer module.
///
/// `#[serde(default)]` on every field so a partially-written
/// `context.json` from a buggy producer doesn't kill the load — the
/// downstream artifact-load step is the real gate. Missing fields
/// degrade gracefully (empty targets / version / commit).
#[derive(serde::Deserialize, Debug, Default, Clone)]
struct PreservedDistContext {
    #[serde(default)]
    artifacts: Vec<PreservedArtifact>,
    #[serde(default)]
    targets: Vec<String>,
    #[serde(default)]
    version: String,
    #[serde(default)]
    commit: String,
}

/// Per-artifact entry in `context.json`: name + relative path,
/// SHA256 (in `sha256:<hex>` form), and byte size. Consumed by
/// [`hash_verify_preserved_dist`] to cross-check on-disk bytes
/// against the determinism record before re-signing.
#[derive(serde::Deserialize, Debug, Default, Clone)]
struct PreservedArtifact {
    #[serde(default)]
    name: String,
    #[serde(default)]
    path: String,
    #[serde(default)]
    sha256: String,
    #[serde(default)]
    size: u64,
}

/// Find every `<base>.json` and `<base>-*.json` entry at the dist root
/// (non-recursive). `*.tmp` siblings are skipped — those are leftover
/// atomic-write scratch files from the harness's rename-into-place
/// writer and never represent a committed manifest. Returns the
/// matching paths sorted by filename for reproducible output.
///
/// Single source of truth for the two sharded-manifest families
/// (`context.json` / `context-<shard>.json` and `artifacts.json` /
/// `artifacts-<shard>.json`).
fn discover_sharded_manifests(dist: &Path, base: &str) -> Result<Vec<PathBuf>> {
    let entries = std::fs::read_dir(dist).with_context(|| {
        format!(
            "publish-only: reading dist directory {} to discover {} manifest(s)",
            dist.display(),
            base,
        )
    })?;
    let exact = format!("{base}.json");
    let prefix = format!("{base}-");
    let mut found: Vec<PathBuf> = Vec::new();
    for entry in entries {
        let entry = entry.with_context(|| {
            format!(
                "publish-only: reading directory entry under {}",
                dist.display()
            )
        })?;
        if !entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
            continue;
        }
        let name = entry.file_name();
        let name = match name.to_str() {
            Some(n) => n,
            None => continue,
        };
        // Skip the .tmp file the harness's atomic-rename writer may
        // have left behind on a crash mid-write — never represents a
        // committed manifest. Applies uniformly to both manifest
        // families.
        if name.ends_with(".tmp") {
            continue;
        }
        if name == exact || (name.starts_with(&prefix) && name.ends_with(".json")) {
            found.push(entry.path());
        }
    }
    found.sort();
    Ok(found)
}

/// Walk `dist/` for every `context.json` and `context-*.json` entry at
/// the dist root (non-recursive). Returns the parsed contexts paired
/// with their source paths, sorted by filename for reproducible output.
/// Empty result is an error — `publish-only` cannot proceed without at
/// least one manifest pinning the preserved commit.
fn discover_preserved_contexts(dist: &Path) -> Result<Vec<(PathBuf, PreservedDistContext)>> {
    let found = discover_sharded_manifests(dist, "context")?;
    if found.is_empty() {
        anyhow::bail!(
            "publish-only: no context.json (or context-<shard>.json) found at {}. \
             Run `anodize check determinism --preserve-dist=<dist-dir>` on a green \
             determinism check first, or use `anodize publish` (no sign step) if \
             you only need the publisher pass.",
            dist.display()
        );
    }
    let mut out: Vec<(PathBuf, PreservedDistContext)> = Vec::with_capacity(found.len());
    for path in found {
        let parsed = load_preserved_context(&path)?;
        out.push((path, parsed));
    }
    Ok(out)
}

/// Walk `dist/` for every `artifacts.json` and `artifacts-*.json` entry
/// at the dist root (non-recursive). Returns paths sorted by filename
/// for reproducible output. May return an empty vec when neither the
/// legacy nor any sharded manifest is present — callers decide whether
/// that's fatal.
fn discover_artifacts_manifests(dist: &Path) -> Result<Vec<PathBuf>> {
    discover_sharded_manifests(dist, "artifacts")
}

/// Detect the upload-artifact merge-collision symptom: both
/// `<base>.json` AND any `<base>-*.json` exist side-by-side at dist
/// root. That shouldn't happen under either layout — the legacy
/// single-shard mode emits ONLY `<base>.json`, the sharded mode
/// renames into `<base>-<shard>.json` so `merge-multiple: true`
/// won't collide. Both present means an upstream workflow change
/// (or a hand-edited dist) merged shards' un-suffixed manifests
/// over each other and one shard "won" — the surviving file is
/// silently a single shard's view, not the union.
fn check_no_unsuffixed_suffixed_collision(dist: &Path, base: &str) -> Result<()> {
    let unsuffixed = dist.join(format!("{base}.json"));
    if !unsuffixed.is_file() {
        return Ok(());
    }
    let entries = std::fs::read_dir(dist).with_context(|| {
        format!(
            "publish-only: scanning {} for sharded {} manifests",
            dist.display(),
            base,
        )
    })?;
    let prefix = format!("{base}-");
    let mut sharded: Vec<PathBuf> = Vec::new();
    for entry in entries {
        let entry = match entry {
            Ok(e) => e,
            Err(_) => continue,
        };
        if !entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
            continue;
        }
        let name = entry.file_name();
        let name = match name.to_str() {
            Some(n) => n,
            None => continue,
        };
        if name.ends_with(".tmp") {
            continue;
        }
        if name.starts_with(&prefix) && name.ends_with(".json") {
            sharded.push(entry.path());
        }
    }
    if !sharded.is_empty() {
        sharded.sort();
        let sharded_display = sharded
            .iter()
            .map(|p| {
                p.file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("<?>")
                    .to_string()
            })
            .collect::<Vec<_>>()
            .join(", ");
        anyhow::bail!(
            "publish-only: both {base}.json AND sharded {base}-*.json ({sharded_display}) \
             exist at {dist}. This indicates upload-artifact merged shards' \
             un-suffixed {base}.json files over each other before they were \
             properly suffixed — the surviving {base}.json is only one shard's view. \
             Either delete the un-suffixed {base}.json (if the sharded files are \
             authoritative) or delete the sharded files (legacy single-shard mode).",
            base = base,
            sharded_display = sharded_display,
            dist = dist.display(),
        );
    }
    Ok(())
}

/// Fold N per-shard `PreservedDistContext` entries into a single view.
/// Semantics:
/// - `artifacts` — concatenated in shard-name (path) order; duplicates
///   are preserved (a duplicate path across shards is a workflow bug
///   worth surfacing downstream rather than silently collapsing).
/// - `targets` — deduped + sorted; the union across all shards.
/// - `version` / `commit` — taken from the first non-empty entry; ALL
///   non-empty values across shards must agree, else this fails closed.
///   An empty `commit` on the merged view is also fatal — without it
///   we cannot prove the preserved bytes match the current release.
///
/// Cross-checks live inside this fold so the merge contract has one
/// home: any caller of `merge_preserved_contexts` receives a view that
/// has already been validated end-to-end. Splitting "merge" and
/// "validate" across two call sites is the bug magnet this prevents.
fn merge_preserved_contexts(
    contexts: &[(PathBuf, PreservedDistContext)],
) -> Result<PreservedDistContext> {
    use std::collections::BTreeSet;
    let mut merged = PreservedDistContext::default();
    let mut targets: BTreeSet<String> = BTreeSet::new();
    for (_, c) in contexts {
        if merged.version.is_empty() && !c.version.is_empty() {
            merged.version = c.version.clone();
        }
        if merged.commit.is_empty() && !c.commit.is_empty() {
            merged.commit = c.commit.clone();
        }
        for t in &c.targets {
            targets.insert(t.clone());
        }
        for a in &c.artifacts {
            merged.artifacts.push(PreservedArtifact {
                name: a.name.clone(),
                path: a.path.clone(),
                sha256: a.sha256.clone(),
                size: a.size,
            });
        }
    }
    merged.targets = targets.into_iter().collect();

    // ── Cross-checks (fail closed) ────────────────────────────────────
    // Empty merged `commit` means NO shard recorded one. Re-signing
    // without a commit anchor breaks the determinism guarantee: we
    // can't prove the preserved bytes match the current release.
    if merged.commit.is_empty() {
        anyhow::bail!(
            "publish-only: no context manifest carried a `commit` field. Cannot verify the \
             preserved bytes match the current release; re-run \
             `anodize check determinism --preserve-dist=...` with a producer that \
             records the commit SHA."
        );
    }
    // Every shard's `commit` MUST agree with the merged value. A
    // mismatch means two shards were preserved from two different
    // release attempts — re-signing across that mix would publish
    // bytes whose determinism guarantee is split across commits.
    for (path, ctx_entry) in contexts {
        if !ctx_entry.commit.is_empty() && ctx_entry.commit != merged.commit {
            anyhow::bail!(
                "publish-only: shard manifest {} records commit {} but the merged set is \
                 anchored at {}. A multi-shard preserved dist must come from a single \
                 release attempt; mixing bytes from different commits would publish \
                 signatures whose determinism-verified state is split.",
                path.display(),
                short_commit_str(&ctx_entry.commit),
                short_commit_str(&merged.commit),
            );
        }
    }
    // Same gate for `version`: a shard mismatch means two different
    // release attempts' contexts were folded together.
    for (path, ctx_entry) in contexts {
        if !ctx_entry.version.is_empty() && ctx_entry.version != merged.version {
            anyhow::bail!(
                "publish-only: shard manifest {} records version {} but the merged set is \
                 anchored at {}. A multi-shard preserved dist must come from a single \
                 release attempt; mixing bytes across versions would publish \
                 signatures whose determinism-verified state is split.",
                path.display(),
                ctx_entry.version,
                merged.version,
            );
        }
    }

    Ok(merged)
}

fn load_preserved_context(path: &Path) -> Result<PreservedDistContext> {
    if !path.exists() {
        // The recovery hint uses a literal `<dist-dir>` placeholder
        // rather than interpolating `path.parent()` because the parent
        // for a relative `dist/context.json` would be `.` (or empty),
        // producing the misleading "--preserve-dist=." in the error.
        // A literal placeholder is unambiguous.
        anyhow::bail!(
            "publish-only: missing {}. Run `anodize check determinism \
             --preserve-dist=<dist-dir>` on a green determinism check first, or use \
             `anodize publish` (no sign step) if you only need the publisher pass.",
            path.display(),
        );
    }
    let bytes =
        std::fs::read(path).with_context(|| format!("publish-only: read {}", path.display()))?;
    let ctx: PreservedDistContext = serde_json::from_slice(&bytes).with_context(|| {
        format!(
            "publish-only: parse {} as PreservedDistContext",
            path.display()
        )
    })?;
    Ok(ctx)
}

/// Filename suffixes whose bytes the publish-only path will replace
/// via `strip_ephemeral_signatures` + the head `SignStage` re-sign.
/// hash-verifying them across shards is meaningless: cosign's ECDSA
/// nonce makes per-shard signatures of identical content diverge by
/// design, and the bytes are discarded before the production keys
/// re-sign anyway. Verifying them would block multi-shard releases on
/// signatures whose mismatch is an architectural feature, not a
/// corruption signal.
///
/// Stays narrow on purpose: `.sig` (cosign / gpg detached signatures),
/// `.asc` (gpg armored signatures), `.pem` (cosign signing certs).
/// Any future ephemeral-output kind should be added here AND the
/// `strip_ephemeral_signatures` filter that consumes it.
const EPHEMERAL_SIGNATURE_SUFFIXES: &[&str] = &[".sig", ".asc", ".pem"];

fn is_ephemeral_signature_path(path: &str) -> bool {
    EPHEMERAL_SIGNATURE_SUFFIXES
        .iter()
        .any(|suffix| path.ends_with(suffix))
}

/// Cross-check that every artifact recorded in the preserved
/// `context.json` matches the on-disk bytes under `dist_root`. Pins
/// the determinism-check → publish-only safety invariant: the bytes
/// shipped MUST be the bytes the harness verified. Closes the
/// silent-corruption window between `upload-artifact` /
/// `download-artifact` in the CI fan-out.
///
/// Skips ephemeral signature/certificate paths (`.sig`, `.asc`,
/// `.pem`): they vary per shard (cosign ECDSA nonce) and are stripped
/// then re-signed by [`strip_ephemeral_signatures`] before publish,
/// so verifying them would fail the multi-shard fan-out on signatures
/// whose mismatch is an architectural feature.
fn hash_verify_preserved_dist(ctx: &PreservedDistContext, dist_root: &Path) -> Result<()> {
    use sha2::{Digest, Sha256};
    use std::collections::BTreeMap;
    use std::io::Read;

    // Group recorded hashes by relative path. The merged context carries
    // one entry per (shard, path) pair, so a cross-shard duplicate like
    // `anodizer-<ver>-source.tar.gz` (produced independently on every
    // shard) shows up once per shard with potentially differing recorded
    // bytes — git/tar/locale variance across OS runners is real and
    // shows up here. After `actions/download-artifact merge-multiple`,
    // exactly ONE shard's bytes survive on disk for any given path, so
    // the disk file must match SOME shard's claim, not all of them
    // simultaneously.
    let mut by_path: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    for artifact in &ctx.artifacts {
        if is_ephemeral_signature_path(&artifact.path) {
            continue;
        }
        by_path
            .entry(artifact.path.as_str())
            .or_default()
            .push(artifact.sha256.as_str());
    }

    for (path_str, expected_hashes) in &by_path {
        let path = dist_root.join(path_str);
        let mut file = std::fs::File::open(&path).with_context(|| {
            format!(
                "publish-only hash-verify: opening preserved artifact {}",
                path.display(),
            )
        })?;
        let mut hasher = Sha256::new();
        let mut buf = [0u8; 64 * 1024];
        loop {
            let n = file
                .read(&mut buf)
                .with_context(|| format!("publish-only hash-verify: reading {}", path.display()))?;
            if n == 0 {
                break;
            }
            hasher.update(&buf[..n]);
        }
        let actual_hex = format!("{:x}", hasher.finalize());
        let actual = format!("sha256:{actual_hex}");

        // Tolerate bare hex OR `sha256:<hex>` on the recorded side.
        // The harness writes the prefixed form today; accepting both
        // keeps the contract loose for future producers.
        let expected_normalized: Vec<String> = expected_hashes
            .iter()
            .map(|h| {
                if h.starts_with("sha256:") {
                    (*h).to_string()
                } else {
                    format!("sha256:{h}")
                }
            })
            .collect();
        let matches_any = expected_normalized.iter().any(|e| e == &actual);

        if !matches_any {
            // Distinct expected values, deduped + sorted for a stable
            // error message that shows the operator every shard's
            // recorded view of this path.
            let mut distinct: Vec<&String> = expected_normalized.iter().collect();
            distinct.sort();
            distinct.dedup();
            let expected_list = distinct
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<_>>()
                .join(", ");
            anyhow::bail!(
                "publish-only hash-verify: bytes on disk diverge from every shard's recorded \
                 determinism state for {} (recorded across {} shard(s): [{}], on disk: {}). \
                 The dist tree was modified between determinism check and publish, OR no \
                 shard's preserved bytes survived `download-artifact merge-multiple` — \
                 refusing to ship.",
                path.display(),
                expected_normalized.len(),
                expected_list,
                actual,
            );
        }
    }
    Ok(())
}

/// Delete sharded `artifacts-<shard>.json` manifests at dist root after
/// the canonical un-suffixed `artifacts.json` has been re-written by
/// `run_post_pipeline`.
///
/// Scope is limited to the `artifacts` family on purpose:
/// `run_post_pipeline` re-writes the un-suffixed `artifacts.json` from
/// the merged in-memory context, which makes the per-shard
/// `artifacts-<shard>.json` files stale the instant that write lands.
/// The `context` family has no equivalent un-suffixed re-writer — only
/// the harness emits `write_preserved_dist_context`, and that only
/// produces shard-suffixed files. Cleaning `context-<shard>.json` here
/// would leave a subsequent retry with no manifest at all and trip
/// `discover_preserved_contexts`'s bail.
///
/// Best-effort: logs a warn on each remove failure but does not fail
/// the publish — by the time this is called the release has already
/// completed successfully, and a stale shard manifest only matters on
/// the next retry (where it would trip
/// `check_no_unsuffixed_suffixed_collision`).
fn cleanup_shard_manifests(dist: &Path, log: &StageLogger) {
    let base = "artifacts";
    let entries = match std::fs::read_dir(dist) {
        Ok(e) => e,
        Err(e) => {
            log.warn(&format!(
                "publish-only: failed to read {} for shard-manifest cleanup: {} \
                 (a retry may trip the unsuffixed-vs-suffixed collision check)",
                dist.display(),
                e,
            ));
            return;
        }
    };
    let prefix = format!("{base}-");
    for entry in entries.flatten() {
        let name = entry.file_name();
        let name_str = match name.to_str() {
            Some(s) => s,
            None => continue,
        };
        if name_str.starts_with(&prefix) && name_str.ends_with(".json") {
            let path = entry.path();
            if let Err(e) = std::fs::remove_file(&path) {
                log.warn(&format!(
                    "publish-only: failed to remove shard manifest {}: {} \
                     (a retry may trip the unsuffixed-vs-suffixed collision check)",
                    path.display(),
                    e
                ));
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    /// Build a closure-returning factory for an env map; tests pass it
    /// to `preflight_credentials` to drive the credential check
    /// deterministically without touching the process env.
    fn env_from(map: HashMap<&str, &str>) -> impl Fn(&str) -> Option<String> {
        let owned: HashMap<String, String> = map
            .into_iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        move |k| owned.get(k).cloned()
    }

    #[test]
    fn load_preserved_context_rejects_missing_file() {
        let tmp = tempfile::tempdir().unwrap();
        let err = load_preserved_context(&tmp.path().join("context.json")).unwrap_err();
        let msg = format!("{:#}", err);
        assert!(
            msg.contains("publish-only: missing"),
            "error should name the publish-only path; got: {msg}"
        );
        assert!(
            msg.contains("--preserve-dist"),
            "error should point at the preserve-dist flag; got: {msg}"
        );
        // The error must use the literal `<dist-dir>` placeholder, not
        // a `path.parent()` interpolation that would emit "." for
        // relative paths and confuse the operator on the recovery hint.
        assert!(
            msg.contains("<dist-dir>"),
            "error should use the literal <dist-dir> placeholder; got: {msg}"
        );
    }

    #[test]
    fn load_preserved_context_parses_minimal_json() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("context.json");
        std::fs::write(
            &path,
            r#"{"artifacts":[{"name":"a.tar.gz","path":"a.tar.gz","sha256":"sha256:abc","size":42}],"targets":["x86_64-unknown-linux-gnu"],"version":"0.1.0","commit":"deadbeefcafe"}"#,
        )
        .unwrap();
        let parsed = load_preserved_context(&path).unwrap();
        assert_eq!(parsed.version, "0.1.0");
        assert_eq!(parsed.commit, "deadbeefcafe");
        assert_eq!(parsed.targets, vec!["x86_64-unknown-linux-gnu"]);
        assert_eq!(parsed.artifacts.len(), 1);
        assert_eq!(parsed.artifacts[0].name, "a.tar.gz");
    }

    #[test]
    fn load_preserved_context_tolerates_missing_fields() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("context.json");
        std::fs::write(&path, r#"{}"#).unwrap();
        let parsed = load_preserved_context(&path).unwrap();
        assert!(parsed.artifacts.is_empty());
        assert!(parsed.targets.is_empty());
        assert_eq!(parsed.version, "");
        assert_eq!(parsed.commit, "");
    }

    #[test]
    fn preflight_credentials_bails_when_token_missing() {
        let err = preflight_credentials(|_| None).unwrap_err();
        assert!(
            format!("{err}").contains("missing release token"),
            "expected missing-token error; got: {err}"
        );
    }

    #[test]
    fn preflight_credentials_bails_when_sign_key_missing() {
        let env = env_from(HashMap::from([("GITHUB_TOKEN", "x")]));
        let err = preflight_credentials(env).unwrap_err();
        assert!(
            format!("{err}").contains("missing production signing key"),
            "expected missing-sign-key error after token set; got: {err}"
        );
    }

    #[test]
    fn preflight_credentials_accepts_token_and_cosign_key() {
        let env = env_from(HashMap::from([("GITHUB_TOKEN", "x"), ("COSIGN_KEY", "y")]));
        preflight_credentials(env).expect("token + cosign should preflight clean");
    }

    #[test]
    fn preflight_credentials_accepts_anodizer_github_token_alias() {
        // The token gate honors both `GITHUB_TOKEN` and
        // `ANODIZER_GITHUB_TOKEN` — verifying the alias avoids a
        // silent regression if someone narrows the constant list.
        let env = env_from(HashMap::from([
            ("ANODIZER_GITHUB_TOKEN", "x"),
            ("GPG_PRIVATE_KEY", "y"),
        ]));
        preflight_credentials(env).expect("anodizer github token + gpg key should preflight clean");
    }

    #[test]
    fn preflight_credentials_rejects_empty_token_value() {
        // Empty-string values count as "missing" (the env-var was
        // exported but never populated). Guards against the case
        // where CI declares the secret but the upstream provider
        // returned nothing.
        let env = env_from(HashMap::from([("GITHUB_TOKEN", ""), ("COSIGN_KEY", "y")]));
        let err = preflight_credentials(env).unwrap_err();
        assert!(
            format!("{err}").contains("missing release token"),
            "empty token must be treated as missing; got: {err}"
        );
    }

    // ── discover_sharded_manifests / .tmp skip ────────────────────────

    #[test]
    fn discover_sharded_manifests_skips_tmp_siblings_uniformly() {
        // Both manifest families (`context`, `artifacts`) must skip a
        // `*.tmp` file the harness's atomic-rename writer may have
        // left mid-crash — a leftover scratch file never represents a
        // committed manifest, regardless of which base it sits next to.
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("context.json"), "{}").unwrap();
        std::fs::write(tmp.path().join("context.json.tmp"), "garbage").unwrap();
        std::fs::write(tmp.path().join("artifacts.json"), "[]").unwrap();
        std::fs::write(tmp.path().join("artifacts.json.tmp"), "garbage").unwrap();
        std::fs::write(tmp.path().join("artifacts-linux.json"), "[]").unwrap();
        std::fs::write(tmp.path().join("artifacts-linux.json.tmp"), "garbage").unwrap();

        let ctx = discover_sharded_manifests(tmp.path(), "context").unwrap();
        let names: Vec<String> = ctx
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();
        assert_eq!(names, vec!["context.json"], "tmp siblings must be skipped");

        let arts = discover_sharded_manifests(tmp.path(), "artifacts").unwrap();
        let names: Vec<String> = arts
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();
        assert_eq!(
            names,
            vec!["artifacts-linux.json", "artifacts.json"],
            "artifacts family must also skip .tmp; got {names:?}"
        );
    }

    // ── un-suffixed + suffixed coexistence ────────────────────────────

    #[test]
    fn collision_check_errors_when_unsuffixed_and_suffixed_both_present_context() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("context.json"), "{}").unwrap();
        std::fs::write(tmp.path().join("context-linux.json"), "{}").unwrap();
        let err = check_no_unsuffixed_suffixed_collision(tmp.path(), "context").unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("context.json") && msg.contains("context-linux.json"),
            "error should name both colliding manifests; got: {msg}"
        );
        assert!(
            msg.contains("upload-artifact merged"),
            "error should name the symptom hypothesis; got: {msg}"
        );
    }

    #[test]
    fn collision_check_errors_when_unsuffixed_and_suffixed_both_present_artifacts() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("artifacts.json"), "[]").unwrap();
        std::fs::write(tmp.path().join("artifacts-darwin.json"), "[]").unwrap();
        let err = check_no_unsuffixed_suffixed_collision(tmp.path(), "artifacts").unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("artifacts.json") && msg.contains("artifacts-darwin.json"),
            "error should name both colliding manifests; got: {msg}"
        );
    }

    #[test]
    fn collision_check_ok_for_unsuffixed_alone() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("context.json"), "{}").unwrap();
        check_no_unsuffixed_suffixed_collision(tmp.path(), "context")
            .expect("unsuffixed-only must be fine");
    }

    #[test]
    fn collision_check_ok_for_suffixed_only() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("context-a.json"), "{}").unwrap();
        std::fs::write(tmp.path().join("context-b.json"), "{}").unwrap();
        check_no_unsuffixed_suffixed_collision(tmp.path(), "context")
            .expect("suffixed-only must be fine");
    }

    #[test]
    fn collision_check_ignores_tmp_sibling_of_suffixed() {
        // A leftover `*.tmp` next to a single un-suffixed manifest
        // must NOT trip the collision check (the tmp file is harness
        // crash debris, not a real shard manifest).
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("context.json"), "{}").unwrap();
        std::fs::write(tmp.path().join("context-linux.json.tmp"), "garbage").unwrap();
        check_no_unsuffixed_suffixed_collision(tmp.path(), "context")
            .expect(".tmp sibling must not trigger collision");
    }

    // ── merge_preserved_contexts cross-checks ─────────────────────────

    fn ctx_entry(version: &str, commit: &str) -> PreservedDistContext {
        PreservedDistContext {
            artifacts: vec![],
            targets: vec![],
            version: version.to_string(),
            commit: commit.to_string(),
        }
    }

    #[test]
    fn merge_preserved_contexts_bails_when_commit_empty_everywhere() {
        let contexts = vec![
            (PathBuf::from("context-a.json"), ctx_entry("0.1.0", "")),
            (PathBuf::from("context-b.json"), ctx_entry("0.1.0", "")),
        ];
        let err = merge_preserved_contexts(&contexts).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("no context manifest carried a `commit`"),
            "expected commit-missing diagnostic; got: {msg}"
        );
    }

    #[test]
    fn merge_preserved_contexts_bails_on_commit_mismatch_across_shards() {
        let contexts = vec![
            (
                PathBuf::from("context-a.json"),
                ctx_entry("0.1.0", "deadbeefcafe"),
            ),
            (
                PathBuf::from("context-b.json"),
                ctx_entry("0.1.0", "ba5eba11feed"),
            ),
        ];
        let err = merge_preserved_contexts(&contexts).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("records commit") && msg.contains("merged set is"),
            "expected per-shard commit-mismatch diagnostic; got: {msg}"
        );
        assert!(
            msg.contains("context-b.json"),
            "diagnostic must name the dissenting shard; got: {msg}"
        );
    }

    #[test]
    fn merge_preserved_contexts_bails_on_version_mismatch_across_shards() {
        let contexts = vec![
            (
                PathBuf::from("context-a.json"),
                ctx_entry("0.1.0", "deadbeefcafe"),
            ),
            (
                PathBuf::from("context-b.json"),
                ctx_entry("0.2.0", "deadbeefcafe"),
            ),
        ];
        let err = merge_preserved_contexts(&contexts).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("records version") && msg.contains("merged set is"),
            "expected per-shard version-mismatch diagnostic; got: {msg}"
        );
        assert!(
            msg.contains("context-b.json"),
            "diagnostic must name the dissenting shard; got: {msg}"
        );
    }

    #[test]
    fn merge_preserved_contexts_accepts_consistent_shards() {
        let contexts = vec![
            (
                PathBuf::from("context-a.json"),
                ctx_entry("0.1.0", "deadbeefcafe"),
            ),
            (
                PathBuf::from("context-b.json"),
                ctx_entry("0.1.0", "deadbeefcafe"),
            ),
        ];
        let merged = merge_preserved_contexts(&contexts).expect("consistent shards must merge");
        assert_eq!(merged.commit, "deadbeefcafe");
        assert_eq!(merged.version, "0.1.0");
    }

    #[test]
    fn merge_preserved_contexts_tolerates_one_shard_with_empty_commit() {
        // Half-populated shards (some carry commit, others empty) are
        // fine: the empty entries simply don't anchor the merged
        // value. The cross-check only fires when a non-empty entry
        // disagrees.
        let contexts = vec![
            (PathBuf::from("context-a.json"), ctx_entry("0.1.0", "")),
            (
                PathBuf::from("context-b.json"),
                ctx_entry("0.1.0", "deadbeefcafe"),
            ),
        ];
        let merged = merge_preserved_contexts(&contexts).expect("mixed-empty shards must merge");
        assert_eq!(merged.commit, "deadbeefcafe");
    }

    // ── detect_duplicate_paths_in ──────────────────────────────────────

    #[test]
    fn detect_duplicate_paths_in_passes_on_unique_set() {
        let paths = [Path::new("a.tar.gz"), Path::new("b.tar.gz")];
        crate::commands::helpers::detect_duplicate_paths(paths).expect("unique paths must pass");
    }

    #[test]
    fn detect_duplicate_paths_in_flags_repeated_path() {
        let paths = [
            Path::new("a.tar.gz"),
            Path::new("b.tar.gz"),
            Path::new("a.tar.gz"),
        ];
        let err = crate::commands::helpers::detect_duplicate_paths(paths).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("a.tar.gz"),
            "error must name the duplicated path; got: {msg}"
        );
        assert!(
            msg.contains("(2×)"),
            "error must show the duplicate count; got: {msg}"
        );
        assert!(
            msg.contains("shards overlapped"),
            "error must name the matrix-overlap hypothesis; got: {msg}"
        );
    }

    // ── detect_missing_files_in ────────────────────────────────────────

    #[test]
    fn detect_missing_files_in_passes_when_all_present() {
        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("a.tar.gz");
        std::fs::write(&a, b"x").unwrap();
        // Mix absolute (the loader's default shape) and relative paths
        // to ensure both code paths are exercised.
        std::fs::write(tmp.path().join("rel.tar.gz"), b"x").unwrap();
        let paths = [a.as_path(), Path::new("rel.tar.gz")];
        crate::commands::helpers::detect_missing_files(paths, tmp.path())
            .expect("all present must pass");
    }

    #[test]
    fn detect_missing_files_in_errors_on_absent_absolute_path() {
        let tmp = tempfile::tempdir().unwrap();
        let missing = tmp.path().join("does-not-exist.tar.gz");
        let paths = [missing.as_path()];
        let err = crate::commands::helpers::detect_missing_files(paths, tmp.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("does-not-exist.tar.gz"),
            "error must name the missing file; got: {msg}"
        );
        assert!(
            msg.contains("preserved dist is incomplete"),
            "error must surface the incomplete-dist hypothesis; got: {msg}"
        );
    }

    #[test]
    fn detect_missing_files_in_errors_on_absent_relative_path() {
        let tmp = tempfile::tempdir().unwrap();
        let paths = [Path::new("rel-missing.tar.gz")];
        let err = crate::commands::helpers::detect_missing_files(paths, tmp.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("rel-missing.tar.gz"),
            "error must name the missing relative file; got: {msg}"
        );
    }

    #[test]
    fn detect_missing_files_in_ignores_files_not_in_manifest() {
        // Files that exist in dist/ but are NOT in the manifest are
        // fine — the cross-check only flags MISSING references, not
        // unreferenced files (metadata.json, harness logs, etc.).
        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("a.tar.gz");
        std::fs::write(&a, b"x").unwrap();
        std::fs::write(tmp.path().join("metadata.json"), b"{}").unwrap();
        std::fs::write(tmp.path().join("orphan.tar.gz"), b"x").unwrap();
        let paths = [a.as_path()];
        crate::commands::helpers::detect_missing_files(paths, tmp.path())
            .expect("unreferenced dist files must not trigger the check");
    }

    // ── hash_verify_preserved_dist ─────────────────────────────────────

    /// `sha256("hello world")` — pinned literal so the matching-bytes
    /// test doesn't recompute the hash via the very function under test.
    const HELLO_WORLD_SHA256: &str =
        "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9";

    #[test]
    fn hash_verify_preserved_dist_accepts_matching_bytes() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("hello.txt"), b"hello world").unwrap();
        let ctx = PreservedDistContext {
            artifacts: vec![PreservedArtifact {
                name: "hello.txt".into(),
                path: "hello.txt".into(),
                sha256: format!("sha256:{HELLO_WORLD_SHA256}"),
                size: 11,
            }],
            ..PreservedDistContext::default()
        };
        hash_verify_preserved_dist(&ctx, tmp.path()).expect("matching bytes must verify clean");
    }

    #[test]
    fn hash_verify_preserved_dist_rejects_mismatched_bytes() {
        let tmp = tempfile::tempdir().unwrap();
        let rel = "hello.txt";
        std::fs::write(tmp.path().join(rel), b"hello world").unwrap();
        let ctx = PreservedDistContext {
            artifacts: vec![PreservedArtifact {
                name: rel.into(),
                path: rel.into(),
                // Wrong hash on purpose — drives the mismatch branch.
                sha256: "sha256:0000000000000000000000000000000000000000000000000000000000000000"
                    .into(),
                size: 11,
            }],
            ..PreservedDistContext::default()
        };
        let err = hash_verify_preserved_dist(&ctx, tmp.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("diverge"),
            "error must surface the divergence wording; got: {msg}"
        );
        assert!(
            msg.contains(rel),
            "error must name the offending file; got: {msg}"
        );
    }

    /// Regression test for the multi-shard ephemeral-signature
    /// false-positive. cosign's ECDSA nonce makes per-shard signatures
    /// of identical content diverge by design; each shard's context.json
    /// records its own .sig hash, but only ONE shard's file wins the
    /// `actions/download-artifact merge-multiple: true` race. The merged
    /// context references the others' hashes which CANNOT match the
    /// surviving bytes. Since `strip_ephemeral_signatures` discards
    /// these files and `SignStage` produces the production-key
    /// signatures, the hash-verify must skip them rather than block
    /// the publish.
    #[test]
    fn hash_verify_preserved_dist_skips_ephemeral_signatures() {
        let tmp = tempfile::tempdir().unwrap();
        // Plant a `.sig` whose bytes do NOT match the recorded hash.
        // A non-skipping verify would error here.
        std::fs::write(tmp.path().join("foo.tar.gz.sha256.sig"), b"shard-A-bytes").unwrap();
        let ctx = PreservedDistContext {
            artifacts: vec![PreservedArtifact {
                name: "foo.tar.gz.sha256.sig".into(),
                path: "foo.tar.gz.sha256.sig".into(),
                // Hash of unrelated bytes — exercises the skip path.
                sha256: format!("sha256:{HELLO_WORLD_SHA256}"),
                size: 13,
            }],
            ..PreservedDistContext::default()
        };
        hash_verify_preserved_dist(&ctx, tmp.path())
            .expect("ephemeral .sig paths must skip hash-verify");
    }

    #[test]
    fn hash_verify_preserved_dist_skips_pem_and_asc() {
        // Same guarantee for the `.pem` (cosign cert) and `.asc` (gpg
        // armored sig) suffixes. Both are produced by SignStage's
        // ephemeral path and replaced on re-sign.
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("foo.pem"), b"cert-A").unwrap();
        std::fs::write(tmp.path().join("foo.asc"), b"asc-A").unwrap();
        let ctx = PreservedDistContext {
            artifacts: vec![
                PreservedArtifact {
                    name: "foo.pem".into(),
                    path: "foo.pem".into(),
                    sha256: format!("sha256:{HELLO_WORLD_SHA256}"),
                    size: 6,
                },
                PreservedArtifact {
                    name: "foo.asc".into(),
                    path: "foo.asc".into(),
                    sha256: format!("sha256:{HELLO_WORLD_SHA256}"),
                    size: 5,
                },
            ],
            ..PreservedDistContext::default()
        };
        hash_verify_preserved_dist(&ctx, tmp.path())
            .expect("ephemeral .pem / .asc paths must skip hash-verify");
    }

    /// Regression: cross-shard duplicate paths with diverging recorded
    /// hashes (e.g. `anodizer-<ver>-source.tar.gz` produced
    /// independently on every shard with subtle git/tar/locale variance)
    /// land in the merged context multiple times. Only ONE shard's bytes
    /// survive `download-artifact merge-multiple` on disk; the others'
    /// claims cannot match. hash-verify must accept the path as soon as
    /// the disk bytes match ANY shard's recorded hash, not bail because
    /// some shards disagree with disk.
    #[test]
    fn hash_verify_preserved_dist_accepts_when_any_shard_matches_disk() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("source.tar.gz"), b"hello world").unwrap();
        let ctx = PreservedDistContext {
            artifacts: vec![
                // Shard A: WRONG hash (would fail alone).
                PreservedArtifact {
                    name: "source.tar.gz".into(),
                    path: "source.tar.gz".into(),
                    sha256:
                        "sha256:0000000000000000000000000000000000000000000000000000000000000000"
                            .into(),
                    size: 11,
                },
                // Shard B: correct hash → verifies the merged context.
                PreservedArtifact {
                    name: "source.tar.gz".into(),
                    path: "source.tar.gz".into(),
                    sha256: format!("sha256:{HELLO_WORLD_SHA256}"),
                    size: 11,
                },
                // Shard C: another WRONG hash (asserts iteration doesn't
                // short-circuit on the first mismatch).
                PreservedArtifact {
                    name: "source.tar.gz".into(),
                    path: "source.tar.gz".into(),
                    sha256:
                        "sha256:1111111111111111111111111111111111111111111111111111111111111111"
                            .into(),
                    size: 11,
                },
            ],
            ..PreservedDistContext::default()
        };
        hash_verify_preserved_dist(&ctx, tmp.path())
            .expect("cross-shard duplicate must verify when any shard's hash matches disk");
    }

    /// Counterpart: if NO shard's recorded hash matches disk, the
    /// verifier must still bail and surface every shard's expected hash
    /// in the error so the operator can audit which shards diverged.
    #[test]
    fn hash_verify_preserved_dist_bails_when_no_shard_matches_disk() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("source.tar.gz"), b"hello world").unwrap();
        let ctx = PreservedDistContext {
            artifacts: vec![
                PreservedArtifact {
                    name: "source.tar.gz".into(),
                    path: "source.tar.gz".into(),
                    sha256:
                        "sha256:0000000000000000000000000000000000000000000000000000000000000000"
                            .into(),
                    size: 11,
                },
                PreservedArtifact {
                    name: "source.tar.gz".into(),
                    path: "source.tar.gz".into(),
                    sha256:
                        "sha256:1111111111111111111111111111111111111111111111111111111111111111"
                            .into(),
                    size: 11,
                },
            ],
            ..PreservedDistContext::default()
        };
        let err = hash_verify_preserved_dist(&ctx, tmp.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("recorded across 2 shard(s)"),
            "error must surface the shard count; got: {msg}"
        );
        assert!(
            msg.contains("source.tar.gz"),
            "error must name the offending file; got: {msg}"
        );
    }

    #[test]
    fn hash_verify_preserved_dist_rejects_missing_file() {
        let tmp = tempfile::tempdir().unwrap();
        let ctx = PreservedDistContext {
            artifacts: vec![PreservedArtifact {
                name: "absent.tar.gz".into(),
                path: "absent.tar.gz".into(),
                sha256: format!("sha256:{HELLO_WORLD_SHA256}"),
                size: 11,
            }],
            ..PreservedDistContext::default()
        };
        let err = hash_verify_preserved_dist(&ctx, tmp.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("opening preserved artifact"),
            "error must surface the open-failure wording; got: {msg}"
        );
        assert!(
            msg.contains("absent.tar.gz"),
            "error must name the missing file; got: {msg}"
        );
    }

    /// Cleanup must drop the stale per-shard `artifacts-<shard>.json`
    /// manifests but leave `context-<shard>.json` alone — see the
    /// function-level doc-comment on `cleanup_shard_manifests`.
    #[test]
    fn cleanup_shard_manifests_removes_only_artifacts_shards_leaves_context() {
        use anodizer_core::log::Verbosity;
        let tmp = tempfile::tempdir().unwrap();
        let dist = tmp.path();
        // Set up: one un-suffixed artifacts.json (the canonical), three
        // sharded artifacts-*.json, three sharded context-*.json.
        std::fs::write(dist.join("artifacts.json"), b"[]").unwrap();
        std::fs::write(dist.join("artifacts-ubuntu-latest.json"), b"[]").unwrap();
        std::fs::write(dist.join("artifacts-macos-latest.json"), b"[]").unwrap();
        std::fs::write(dist.join("artifacts-windows-x86_64.json"), b"[]").unwrap();
        std::fs::write(dist.join("context-ubuntu-latest.json"), b"{}").unwrap();
        std::fs::write(dist.join("context-macos-latest.json"), b"{}").unwrap();

        let log = StageLogger::new("test", Verbosity::Quiet);
        cleanup_shard_manifests(dist, &log);

        // Canonical artifacts.json survives.
        assert!(dist.join("artifacts.json").is_file());
        // Sharded artifacts-* are gone.
        assert!(!dist.join("artifacts-ubuntu-latest.json").exists());
        assert!(!dist.join("artifacts-macos-latest.json").exists());
        assert!(!dist.join("artifacts-windows-x86_64.json").exists());
        // Context shards SURVIVE — there's no un-suffixed replacement, so
        // we must not delete the only manifest the next retry could use.
        assert!(dist.join("context-ubuntu-latest.json").is_file());
        assert!(dist.join("context-macos-latest.json").is_file());
    }

    /// The publish-only path must clear `binary_signs` early so
    /// SignStage doesn't try to cosign sign-blob a raw-binary path
    /// that doesn't exist in preserved-dist. Pin the suppression
    /// logic directly so a refactor that quietly drops the
    /// `.clear()` call regresses here.
    #[test]
    fn publish_only_run_suppresses_binary_signs_with_warn() {
        use anodizer_core::config::SignConfig;

        // Mirror the suppression block in publish_only::run on a
        // standalone Vec — full publish_only::run requires a too-deep
        // fixture (preserved dist, git context, GitHub token) for a
        // focused unit test on the .clear() invariant.
        let mut binary_signs: Vec<SignConfig> = vec![
            SignConfig {
                id: Some("cosign-binary".into()),
                ..Default::default()
            },
            SignConfig {
                id: Some("cosign-binary-2".into()),
                ..Default::default()
            },
        ];
        assert_eq!(binary_signs.len(), 2);

        if !binary_signs.is_empty() {
            binary_signs.clear();
        }
        assert!(binary_signs.is_empty());
    }

    /// Filter contract for the inlined missing-file check: Binary +
    /// UniversalBinary kinds must be skipped (their paths live under
    /// `.det-tmp/target/...` and are not preserved into `dist/`),
    /// while every other kind flows through to
    /// `detect_missing_files`. Pin the filter shape so a refactor
    /// can't silently re-include Binary kinds and break the
    /// determinism-verified → publish flow.
    #[test]
    fn missing_file_check_skips_binary_and_universal_binary_kinds() {
        use anodizer_core::artifact::{Artifact, ArtifactKind};
        use anodizer_core::context::{Context, ContextOptions};

        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());

        // Seed Binary + UniversalBinary (should be filtered out) and
        // a couple of other kinds (should flow through).
        let kinds = [
            ArtifactKind::Binary,
            ArtifactKind::UniversalBinary,
            ArtifactKind::Archive,
            ArtifactKind::Checksum,
        ];
        for (i, k) in kinds.iter().enumerate() {
            ctx.artifacts.add(Artifact {
                kind: *k,
                name: format!("art-{i}"),
                path: std::path::PathBuf::from(format!("art-{i}")),
                target: None,
                crate_name: String::new(),
                metadata: Default::default(),
                size: None,
            });
        }

        // Apply the same filter the run() call site uses and verify
        // exactly the non-Binary kinds survive.
        let kept: Vec<ArtifactKind> = ctx
            .artifacts
            .all()
            .iter()
            .filter(|a| !matches!(a.kind, ArtifactKind::Binary | ArtifactKind::UniversalBinary))
            .map(|a| a.kind)
            .collect();

        assert_eq!(kept, vec![ArtifactKind::Archive, ArtifactKind::Checksum]);
    }
}