anodizer 0.21.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
//! In-process failure policy for `anodizer release`.
//!
//! On a release-pipeline failure the binary itself evaluates
//! `release.on_failure` and executes the result — no summary.json →
//! workflow-output → `if:` chain is needed on the CI side:
//!
//! - `rollback` (default): delete the run's release tag(s) and revert
//!   the version-bump commit via the same code path as `anodizer tag
//!   rollback`, so the version can be re-cut cleanly.
//! - `hold`: leave everything in place for forensics; the operator
//!   recovers with `release --rollback-only --from-run=<id>` or fixes
//!   forward.
//! - `--publish-only`: the tag and bump commit are permanent (a prior
//!   release created them), so this mode collapses to `hold` regardless
//!   of `on_failure` — see `decide`'s `publish_only` parameter.
//!
//! `rollback` auto-degrades to `hold` the moment any one-way-door
//! (Submitter-group) publisher has landed: crates.io, chocolatey,
//! winget, snapcraft and friends never accept the same version twice,
//! so the version is burned and destructive rollback could only orphan
//! the live published state. The degrade is decided from the run's own
//! evidence — every `summary.json` under the dist tree (which covers
//! prior crates in per-crate workspace mode) plus the live in-memory
//! publish report.
//!
//! The shared `tag rollback` execution path keeps its own
//! published-state guard as defense in depth: it re-derives burn
//! evidence per tag and additionally probes the GitHub Releases API for
//! tags with no summary, which is what protects re-publish runs (a
//! live published release with no local summary refuses rollback).
//!
//! Whatever path is taken is recorded into the run's summaries
//! (`failure_policy` field) so the audit artifact states how the
//! failure was handled. The original pipeline error always propagates —
//! both policies exit nonzero.

use anodizer_core::config::OnFailureConfig;
use anodizer_core::context::Context;
use anodizer_core::log::StageLogger;
use anodizer_stage_publish::run_summary::{
    FailurePolicyRecord, RunSummary, collect_run_summary_paths, record_failure_policy,
    summary_path, write_summary_json,
};
use anyhow::Result;

use super::ReleaseOpts;
use crate::commands::tag::rollback::{Mode, RollbackOpts, RollbackRefusal, Scope};

/// What the policy resolved to for this failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum FailureAction {
    /// Roll back reversible state (tag delete + bump revert).
    Rollback,
    /// Leave state in place. `degraded` is true when the configured
    /// policy was `rollback` but a one-way-door publisher landed.
    Hold { degraded: bool },
}

/// Pure policy decision: configured policy × whether any irreversible
/// publisher landed × whether this is a publish-only run.
///
/// `publish_only` forces `Hold` unconditionally: in `--publish-only` the
/// tag and version-bump commit were created and pushed by a *prior*
/// release run and are already permanent (the build artifacts and GitHub
/// release shipped with it). The `Rollback` path reverts the source-repo
/// bump commit and deletes the released tag — destroying history that
/// publish-only never owns. So the only case that would roll back
/// (`rollback` configured, no one-way door burned) holds instead; every
/// other outcome is identical to a normal run — a one-way door that burned
/// still degrades the hold so the operator sees the burned publisher, and an
/// explicit `hold` stays a clean hold. Reversible publisher-level reversals
/// (cargo yank, npm unpublish) recover out-of-band via
/// `release --rollback-only --from-run=<id>`, which never touches the source
/// repo.
pub(super) fn decide(
    configured: OnFailureConfig,
    irreversible_landed: bool,
    publish_only: bool,
) -> FailureAction {
    match (configured, irreversible_landed) {
        (OnFailureConfig::Hold, _) => FailureAction::Hold { degraded: false },
        (OnFailureConfig::Rollback, true) => FailureAction::Hold { degraded: true },
        // The only publish-only divergence: a clean rollback would delete the
        // already-released tag, so publish-only holds instead.
        (OnFailureConfig::Rollback, false) if publish_only => {
            FailureAction::Hold { degraded: false }
        }
        (OnFailureConfig::Rollback, false) => FailureAction::Rollback,
    }
}

/// Whether the failure policy governs this invocation.
///
/// Covered: the full release pipeline, `--publish-only` (both dist
/// layouts), and `--merge` — every mode that reaches upstream
/// publishers. Excluded:
///
/// - `--dry-run` / `--snapshot`: no real tag, nothing upstream.
/// - `--preflight`: check-only mode, mutates nothing.
/// - `--prepare`: contractually local-only (publish stages skipped).
/// - `--split`: a partial build leg of an operator-orchestrated flow;
///   the publishing `--merge` leg carries the policy.
/// - `--announce-only`: re-fires notifications after an already
///   successful publish; a Slack 502 must never destroy the release.
/// - `--rollback-only`: already the recovery path.
pub(super) fn applies(opts: &ReleaseOpts) -> bool {
    !opts.dry_run
        && !opts.snapshot
        && !opts.preflight
        && !opts.prepare
        && !opts.split
        && !opts.announce_only
        && !opts.rollback_only
        // The determinism harness's hermetic replica (which may run with
        // snapshot=false so its dist carries the real version) sets this to
        // suppress the source-repo rollback/hold policy: it builds nothing
        // upstream and must surface a stage failure plainly.
        && !opts.no_failure_policy
}

/// One-way-door evidence for the current run.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub(super) struct BurnEvidence {
    /// Submitter publishers whose publish action landed.
    pub names: Vec<String>,
    /// Where each burned name came from (summary file + the release it
    /// records, or the live report), so a degrade caused by evidence from
    /// the wrong release is diagnosable from the operator message.
    pub sources: Vec<String>,
}

impl BurnEvidence {
    pub(super) fn burned(&self) -> bool {
        !self.names.is_empty()
    }
}

/// Gather burn evidence from the run summaries under the dist tree plus
/// the live in-memory publish report.
///
/// The disk pass is what makes per-crate workspace mode safe: each
/// crate's publish run persists its own `dist/<crate>/run-*/summary.json`,
/// so a crate that burned the version before a later crate failed is
/// still seen even though the live report only covers the failing run.
///
/// Disk-summary filtering is FAIL-CLOSED: a summary is kept unless it
/// provably belongs to a DIFFERENT release — its tag is in the same tag
/// family as this run's tag (equal family prefix, e.g. both `v…` or both
/// `crd-v…`) AND stamps a different base version. That is the
/// `--publish-only` preserved-dist case: a prior attempt of the same
/// family sitting beside this run's summary, whose burn belongs to that
/// other release and must not degrade this rollback. Everything else is
/// kept: sibling per-crate summaries (different family prefixes carry
/// different versions in one release train), tags whose family or
/// version cannot be established, and same-base-version tags whose
/// prerelease/build suffix differs from this run's (a representation
/// mismatch must never weaken the guard). Kept-but-unverifiable
/// summaries name their file in `sources` so a wrong-release degrade is
/// diagnosable from the operator message.
pub(super) fn gather_burn_evidence(ctx: &Context, log: &StageLogger) -> BurnEvidence {
    let current_tag = ctx
        .template_vars()
        .get("Tag")
        .cloned()
        .filter(|t| !t.is_empty());
    let current_family = current_tag
        .as_deref()
        .and_then(anodizer_core::git::split_tag_family);
    let mut names: Vec<String> = Vec::new();
    let mut sources: Vec<String> = Vec::new();
    for path in collect_run_summary_paths(&ctx.config.dist) {
        let summary = match std::fs::read_to_string(&path)
            .map_err(anyhow::Error::from)
            .and_then(|text| Ok(serde_json::from_str::<RunSummary>(&text)?))
        {
            Ok(summary) => summary,
            Err(e) => {
                log.warn(&format!(
                    "ignoring unreadable run summary {} for failure-policy evaluation: {e:#}",
                    path.display()
                ));
                continue;
            }
        };
        let burned = summary.burned_submitter_names();
        if burned.is_empty() {
            continue;
        }
        match (
            anodizer_core::git::split_tag_family(&summary.tag),
            &current_family,
        ) {
            // Provably a different release: same tag family as this run's
            // tag, different base version. Prerelease/build suffixes are
            // deliberately NOT compared — a suffix-only mismatch may be a
            // representation difference within this release, and guessing
            // wrong here flips the guard fail-open.
            (Some((recorded_prefix, recorded_sv)), Some((current_prefix, current_sv)))
                if recorded_prefix == *current_prefix
                    && (recorded_sv.major, recorded_sv.minor, recorded_sv.patch)
                        != (current_sv.major, current_sv.minor, current_sv.patch) =>
            {
                log.verbose(&format!(
                    "ignoring run summary {} for failure-policy evaluation — it records \
                     tag {} ({recorded_prefix}-family version {}), a different release \
                     than the current {}",
                    path.display(),
                    summary.tag,
                    recorded_sv.version_string(),
                    current_sv.version_string()
                ));
                continue;
            }
            (Some(_), _) => sources.push(format!("{} (tag {})", path.display(), summary.tag)),
            (None, _) => sources.push(format!(
                "{} (no release version recorded{} — kept conservatively; verify it \
                 belongs to this release)",
                path.display(),
                if summary.tag.is_empty() {
                    String::new()
                } else {
                    format!("; tag field: {:?}", summary.tag)
                }
            )),
        }
        names.extend(burned);
    }
    let live = RunSummary::from_context(ctx).burned_submitter_names();
    if !live.is_empty() {
        sources.push("this run's live publish report".to_string());
        names.extend(live);
    }
    names.sort();
    names.dedup();
    BurnEvidence { names, sources }
}

/// Route a release-mode outcome through the failure policy. `Ok` passes
/// through untouched; on `Err` the policy is evaluated and executed,
/// the taken path is recorded into the run's summaries, and the
/// ORIGINAL error propagates (rollback and hold both exit nonzero —
/// the release failed either way).
pub(super) fn finish(
    ctx: &Context,
    opts: &ReleaseOpts,
    log: &StageLogger,
    result: Result<()>,
) -> Result<()> {
    let Err(err) = result else {
        return result;
    };
    if !applies(opts) {
        // Modes outside the rollback/hold policy (dry-run, snapshot,
        // preflight, ...) still count as pipeline failures for the
        // notification surface.
        fire_release_on_error(ctx, &err, false, log);
        return Err(err);
    }
    let log = log.with_stage("failure-policy");

    // Crate-level `release.on_failure` was already rejected at config
    // load (`validate_on_failure_root_only`), so the root block is the
    // only possible source here.
    let configured = ctx
        .config
        .release
        .as_ref()
        .map(|r| r.resolved_on_failure())
        .unwrap_or_default();
    let evidence = gather_burn_evidence(ctx, &log);
    let publish_only = ctx.is_publish_only();
    let record = match decide(configured, evidence.burned(), publish_only) {
        FailureAction::Rollback => execute_rollback(opts, configured, &log),
        FailureAction::Hold { degraded } => {
            if degraded {
                log.warn(&format!(
                    "on_failure=rollback DEGRADED to hold — one-way-door publisher(s) already \
                     accepted this version: {}. Those registries never accept the same version \
                     twice, so the version is burned and rolling back the tag would only orphan \
                     the live published state. Fix forward: keep the tag, revert reversible \
                     publishers with `anodizer release --rollback-only --from-run=<id>` if \
                     needed, repair the failure, and cut the NEXT version.\n\
                     Burn evidence came from:\n  {}",
                    evidence.names.join(", "),
                    evidence.sources.join("\n  ")
                ));
            } else if publish_only {
                log.status(
                    "publish-only run failed — holding the already-released tag and \
                     version-bump commit in place (they were created by a prior release \
                     run and are permanent; reverting them is never correct here). Recover \
                     reversible publishers with `anodizer release --rollback-only \
                     --from-run=<id>`, then re-run the publish-only backfill once fixed.",
                );
            } else {
                log.status(
                    "holding tags, commits, and published state in place for forensics \
                     (on_failure=hold). Recover with `anodizer release --rollback-only \
                     --from-run=<id>` (reverts reversible publishers) and/or \
                     `anodizer tag rollback` once investigated.",
                );
            }
            FailurePolicyRecord {
                configured: configured.to_string(),
                action: "held".into(),
                degraded,
                burned_publishers: evidence.names.clone(),
                rollback_error: None,
            }
        }
    };
    record_outcome(ctx, &record, &log);
    fire_release_on_error(ctx, &err, record.action == "rolled-back", &log);
    Err(err)
}

/// `ANODIZER_*` env var → template var pairs exported to a release-level
/// `on_error` hook. Same injection-safety rationale as the per-publisher
/// failure hooks: `{{ .Error }}` carries remote-controlled text (HTTP
/// bodies, subprocess stderr), so hooks read `"$ANODIZER_ERROR"` instead
/// of interpolating it into the command string.
const RELEASE_ON_ERROR_ENV_VARS: [(&str, &str); 4] = [
    ("ANODIZER_ERROR", "Error"),
    ("ANODIZER_ROLLED_BACK", "RolledBack"),
    ("ANODIZER_VERSION", "Version"),
    ("ANODIZER_TAG", "Tag"),
];

/// Fire the root `on_error:` hooks after ANY release-pipeline failure —
/// build, sign, package, publish, anything the dispatched mode ran —
/// once the failure policy (if applicable) has executed, so
/// `{{ .RolledBack }}` reflects the taken path. Notification / cleanup
/// hooks: a hook's own failure is logged and never masks the pipeline
/// error. Dry-run previews the hooks instead of executing them (the
/// standard hook-runner behavior).
fn fire_release_on_error(ctx: &Context, err: &anyhow::Error, rolled_back: bool, log: &StageLogger) {
    let Some(hooks) = ctx
        .config
        .on_error
        .as_ref()
        .and_then(|h| h.hooks.as_deref())
    else {
        return;
    };
    if hooks.is_empty() {
        return;
    }
    let mut vars = ctx.template_vars().clone();
    vars.set("Error", &format!("{err:#}"));
    vars.set("RolledBack", if rolled_back { "true" } else { "false" });
    let env: Vec<(String, String)> = RELEASE_ON_ERROR_ENV_VARS
        .iter()
        .map(|(env_key, var_key)| {
            let value = vars.get(var_key).cloned().unwrap_or_default();
            ((*env_key).to_string(), value)
        })
        .collect();
    let hook_ctx = anodizer_core::hooks::HookRunContext::new(ctx.is_dry_run(), log, Some(&vars))
        .with_extra_env(&env);
    if let Err(hook_err) = anodizer_core::hooks::run_hooks(hooks, "on-error", hook_ctx) {
        log.warn(&format!(
            "on-error hook failed (ignored — notification/cleanup hooks never mask the \
             pipeline error): {hook_err:#}"
        ));
    }
}

/// Run the shared `tag rollback` path against HEAD (the tagged commit
/// every release mode runs at). Its internal published-state guard
/// stays armed (`force: false`) so cross-run evidence this process
/// cannot see — a live published GitHub release on a re-publish run —
/// still refuses destruction. Outcomes split three ways: clean rollback
/// (`rolled-back`), guard refusal (`rollback-refused` — protective
/// status output, never a warn), and mechanical failure
/// (`rollback-failed` — warn, state held). None mask the pipeline error.
fn execute_rollback(
    opts: &ReleaseOpts,
    configured: OnFailureConfig,
    log: &StageLogger,
) -> FailurePolicyRecord {
    log.status(
        "rolling back this run's release tag(s) and version bump \
         (on_failure=rollback) — no one-way-door publisher landed",
    );
    let rollback = crate::commands::tag::rollback::run(RollbackOpts {
        sha: None,
        dry_run: false,
        no_push: false,
        force: false,
        scope: Scope::All,
        mode: Mode::Revert,
        branch: None,
        verbose: opts.verbose,
        debug: opts.debug,
        quiet: opts.quiet,
    });
    rollback_record(configured, rollback, log)
}

/// Map the shared rollback path's result onto the recorded
/// failure-policy outcome (see [`execute_rollback`]). Split out so the
/// refusal-vs-mechanical classification is unit-testable without a git
/// fixture.
fn rollback_record(
    configured: OnFailureConfig,
    rollback: Result<()>,
    log: &StageLogger,
) -> FailurePolicyRecord {
    match rollback {
        Ok(()) => {
            log.status("rollback complete — the version can be re-cut once the failure is fixed");
            FailurePolicyRecord {
                configured: configured.to_string(),
                action: "rolled-back".into(),
                degraded: false,
                burned_publishers: Vec::new(),
                rollback_error: None,
            }
        }
        // A refusal is the guard WORKING, not the rollback breaking:
        // render it as protective status lines (never a warn) and record
        // a distinct action so summary consumers can tell "refused by
        // design" from "mechanically failed".
        Err(e) if e.downcast_ref::<RollbackRefusal>().is_some() => {
            let refusal = e
                .downcast_ref::<RollbackRefusal>()
                .expect("downcast_ref succeeded in the guard above");
            log.status(&format!(
                "rollback REFUSED (by design): {}", // status-ok: refusal banner, a high-level protective outcome
                refusal.reason
            ));
            log.status(&format!("next step: {}", refusal.next_step)); // status-ok: operator guidance paired with the refusal banner
            FailurePolicyRecord {
                configured: configured.to_string(),
                action: "rollback-refused".into(),
                degraded: false,
                burned_publishers: Vec::new(),
                rollback_error: Some(refusal.to_string()),
            }
        }
        Err(e) => {
            log.warn(&format!(
                "rollback did not complete: {e:#}. State is held; recover manually with \
                 `anodizer tag rollback` and/or `anodizer release --rollback-only \
                 --from-run=<id>` once investigated."
            ));
            FailurePolicyRecord {
                configured: configured.to_string(),
                action: "rollback-failed".into(),
                degraded: false,
                burned_publishers: Vec::new(),
                rollback_error: Some(format!("{e:#}")),
            }
        }
    }
}

/// Persist the taken path into the run's audit trail: stamp every
/// existing summary under the dist tree; when none exists yet (the
/// pipeline failed before any summary write), create one at the run's
/// canonical summary path so the artifact still states how the failure
/// was handled. Best-effort — recording must never mask the release
/// failure.
fn record_outcome(ctx: &Context, record: &FailurePolicyRecord, log: &StageLogger) {
    let mut warn = |msg: &str| log.warn(msg);
    let updated = record_failure_policy(&ctx.config.dist, record, &mut warn);
    if updated > 0 {
        return;
    }
    let Some(path) = summary_path(ctx) else {
        return;
    };
    let mut summary = RunSummary::from_context(ctx);
    summary.failure_policy = Some(record.clone());
    if let Err(e) = write_summary_json(&summary, &path) {
        log.warn(&format!(
            "could not write failure-policy summary at {}: {e:#}",
            path.display()
        ));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use anodizer_core::config::Config;
    use anodizer_core::context::ContextOptions;
    use anodizer_core::log::Verbosity;
    use anodizer_core::publish_report::{
        PublishReport, PublisherGroup, PublisherOutcome, PublisherResult, SkipReason,
    };

    fn release_opts_fixture() -> ReleaseOpts {
        ReleaseOpts {
            crate_names: vec![],
            all: false,
            force: false,
            snapshot: false,
            nightly: false,
            dry_run: false,
            clean: false,
            skip: vec![],
            publishers: vec![],
            token: None,
            verbose: false,
            debug: false,
            quiet: true,
            config_override: None,
            parallelism: 1,
            single_target: None,
            targets: None,
            host_targets: false,
            release_notes: None,
            release_notes_tmpl: None,
            workspace: None,
            draft: false,
            release_header: None,
            release_header_tmpl: None,
            release_footer: None,
            release_footer_tmpl: None,
            fail_fast: false,
            split: false,
            merge: false,
            publish_only: false,
            strict: false,
            prepare: false,
            announce_only: false,
            resume_release: false,
            replace_existing: false,
            preflight: false,
            no_preflight: true,
            preflight_secrets: false,
            strict_preflight: false,
            no_post_publish_poll: false,
            no_gate_submitter: false,
            rollback: None,
            simulate_failure: vec![],
            rollback_only: false,
            from_run: None,
            allow_rerun: false,
            show_skipped: false,
            allow_nondeterministic: vec![],
            summary_json: None,
            allow_ai_failure: false,
            allow_snapshot_publish: false,
            no_failure_policy: false,
        }
    }

    fn result(name: &str, group: PublisherGroup, outcome: PublisherOutcome) -> PublisherResult {
        PublisherResult {
            name: name.into(),
            group,
            required: true,
            outcome,
            evidence: None,
        }
    }

    /// The full decision table: configured policy × irreversible-landed.
    #[test]
    fn decide_covers_every_policy_and_burn_combination() {
        // publish_only=false: the normal (full-pipeline) decision table.
        let cases = [
            (OnFailureConfig::Rollback, false, FailureAction::Rollback),
            (
                OnFailureConfig::Rollback,
                true,
                FailureAction::Hold { degraded: true },
            ),
            (
                OnFailureConfig::Hold,
                false,
                FailureAction::Hold { degraded: false },
            ),
            (
                OnFailureConfig::Hold,
                true,
                FailureAction::Hold { degraded: false },
            ),
        ];
        for (configured, burned, expected) in cases {
            assert_eq!(
                decide(configured, burned, false),
                expected,
                "decide({configured:?}, irreversible_landed={burned}, publish_only=false)"
            );
        }
    }

    /// In publish-only mode the source-repo tag + bump commit are already
    /// permanent (a prior release created them), so `decide` must NEVER
    /// return `Rollback` — that path reverts the bump and deletes the
    /// released tag. It still surfaces a burned one-way door as a *degraded*
    /// hold (the operator must see what burned); the only publish-only
    /// divergence from a normal run is that a would-be clean rollback (no
    /// burn) holds instead of deleting the tag.
    #[test]
    fn decide_publish_only_never_rolls_back() {
        for configured in [OnFailureConfig::Rollback, OnFailureConfig::Hold] {
            for burned in [false, true] {
                let action = decide(configured, burned, true);
                assert_ne!(
                    action,
                    FailureAction::Rollback,
                    "publish-only decide({configured:?}, irreversible_landed={burned}) \
                     must never roll back the released tag/bump"
                );
                // Degraded only when a one-way door burned under a rollback
                // policy — identical to a normal run; publish-only changes
                // only that the non-burned rollback case holds.
                let expected_degraded = configured == OnFailureConfig::Rollback && burned;
                assert_eq!(
                    action,
                    FailureAction::Hold {
                        degraded: expected_degraded
                    },
                    "publish-only decide({configured:?}, irreversible_landed={burned}) \
                     must hold, degraded iff a one-way door burned"
                );
            }
        }
    }

    /// Failure-point coverage through the evidence layer: the decision
    /// input is "did any Submitter land", derived per failure point.
    #[test]
    fn burn_evidence_tracks_failure_point() {
        let log = StageLogger::new("test", Verbosity::Quiet);
        let dist = tempfile::tempdir().expect("tempdir");

        // Pre-publish failure: no report at all — nothing landed.
        let mut ctx = Context::new(Config::default(), ContextOptions::default());
        ctx.config.dist = dist.path().to_path_buf();
        assert!(!gather_burn_evidence(&ctx, &log).burned());

        // Publish failed before any Submitter landed (reversible-only
        // outcomes + a failed Submitter): rollback stays permitted.
        let mut report = PublishReport::default();
        report.results.push(result(
            "github-release",
            PublisherGroup::Assets,
            PublisherOutcome::Succeeded,
        ));
        report.results.push(result(
            "cargo",
            PublisherGroup::Submitter,
            PublisherOutcome::Failed("boom".into()),
        ));
        report.results.push(result(
            "winget",
            PublisherGroup::Submitter,
            PublisherOutcome::Skipped(SkipReason::SubmitterGated),
        ));
        ctx.set_publish_report(report);
        assert!(!gather_burn_evidence(&ctx, &log).burned());

        // Post-one-way-door failure: a Submitter landed before the
        // failure — the version is burned.
        let mut report = PublishReport::default();
        report.results.push(result(
            "cargo",
            PublisherGroup::Submitter,
            PublisherOutcome::Succeeded,
        ));
        report.results.push(result(
            "winget",
            PublisherGroup::Submitter,
            PublisherOutcome::Failed("validation".into()),
        ));
        ctx.set_publish_report(report);
        let evidence = gather_burn_evidence(&ctx, &log);
        assert!(evidence.burned());
        assert_eq!(evidence.names, vec!["cargo".to_string()]);
    }

    /// A landed Submitter recorded only on disk (a prior crate's run in
    /// per-crate workspace mode) must degrade the decision even though
    /// the live report knows nothing about it.
    #[test]
    fn burn_evidence_unions_per_crate_summaries_from_disk() {
        let log = StageLogger::new("test", Verbosity::Quiet);
        let dist = tempfile::tempdir().expect("tempdir");
        let mut ctx = Context::new(Config::default(), ContextOptions::default());
        ctx.config.dist = dist.path().to_path_buf();

        // Prior crate's persisted summary: cargo landed for crate-a.
        let mut report = PublishReport::default();
        report.results.push(result(
            "cargo",
            PublisherGroup::Submitter,
            PublisherOutcome::Succeeded,
        ));
        let prior = RunSummary::from_context_with_report(&ctx, Some(&report));
        let path = dist
            .path()
            .join("crate-a")
            .join("run-crate-a-v1.0.0")
            .join("summary.json");
        write_summary_json(&prior, &path).expect("write prior crate summary");

        // Live report: the current crate failed reversibly.
        let mut live = PublishReport::default();
        live.results.push(result(
            "github-release",
            PublisherGroup::Assets,
            PublisherOutcome::Failed("upload".into()),
        ));
        ctx.set_publish_report(live);

        let evidence = gather_burn_evidence(&ctx, &log);
        assert!(evidence.burned(), "disk-only burn must be seen");
        assert_eq!(evidence.names, vec!["cargo".to_string()]);
        assert_eq!(
            decide(OnFailureConfig::Rollback, evidence.burned(), false),
            FailureAction::Hold { degraded: true }
        );
    }

    /// A preserved-dist (`--publish-only`) scenario: a prior attempt's
    /// summary for a DIFFERENT version sits under dist. Its burn belongs
    /// to that other release and must not degrade the current rollback.
    #[test]
    fn burn_evidence_ignores_stale_summaries_for_other_versions() {
        let log = StageLogger::new("test", Verbosity::Quiet);
        let dist = tempfile::tempdir().expect("tempdir");
        let mut ctx = Context::new(Config::default(), ContextOptions::default());
        ctx.config.dist = dist.path().to_path_buf();
        ctx.template_vars_mut().set("Version", "2.0.0");
        ctx.template_vars_mut().set("Tag", "v2.0.0");

        // Stale prior-attempt summary: cargo burned v1.0.0, not v2.0.0.
        let mut report = PublishReport::default();
        report.results.push(result(
            "cargo",
            PublisherGroup::Submitter,
            PublisherOutcome::Succeeded,
        ));
        let mut stale = RunSummary::from_context_with_report(&ctx, Some(&report));
        stale.tag = "v1.0.0".to_string();
        let path = dist.path().join("run-v1.0.0").join("summary.json");
        write_summary_json(&stale, &path).expect("write stale summary");

        let evidence = gather_burn_evidence(&ctx, &log);
        assert!(
            !evidence.burned(),
            "a burn recorded for a different version must not degrade this \
             release's rollback; got {evidence:?}"
        );

        // Same summary re-stamped for the CURRENT version: now it counts.
        let mut current = RunSummary::from_context_with_report(&ctx, Some(&report));
        current.tag = "v2.0.0".to_string();
        write_summary_json(&current, &path).expect("rewrite summary");
        let evidence = gather_burn_evidence(&ctx, &log);
        assert!(evidence.burned());
        assert_eq!(evidence.names, vec!["cargo".to_string()]);
        assert_eq!(evidence.sources.len(), 1);
        assert!(
            evidence.sources[0].contains("summary.json") && evidence.sources[0].contains("v2.0.0"),
            "the source must name the file and the release it records: {:?}",
            evidence.sources
        );
    }

    /// A summary with no extractable version stamp stays evidence
    /// (conservative), but its file must be named so a wrong-version
    /// degrade is diagnosable from the operator message.
    #[test]
    fn burn_evidence_keeps_unstamped_summaries_and_names_the_source() {
        let log = StageLogger::new("test", Verbosity::Quiet);
        let dist = tempfile::tempdir().expect("tempdir");
        let mut ctx = Context::new(Config::default(), ContextOptions::default());
        ctx.config.dist = dist.path().to_path_buf();
        ctx.template_vars_mut().set("Version", "2.0.0");

        let mut report = PublishReport::default();
        report.results.push(result(
            "cargo",
            PublisherGroup::Submitter,
            PublisherOutcome::Succeeded,
        ));
        // Tag empty: written by a run that never resolved a tag.
        let unstamped = RunSummary::from_context_with_report(&ctx, Some(&report));
        assert_eq!(unstamped.tag, "", "fixture precondition: no tag stamp");
        let path = dist.path().join("run-unknown").join("summary.json");
        write_summary_json(&unstamped, &path).expect("write unstamped summary");

        let evidence = gather_burn_evidence(&ctx, &log);
        assert!(
            evidence.burned(),
            "unverifiable evidence must still refuse the destructive path"
        );
        assert_eq!(evidence.names, vec!["cargo".to_string()]);
        assert_eq!(evidence.sources.len(), 1);
        assert!(
            evidence.sources[0].contains("summary.json")
                && evidence.sources[0].contains("kept conservatively"),
            "the source must flag the missing version stamp: {:?}",
            evidence.sources
        );
    }

    /// Per-crate sibling evidence must be KEPT: in one release train the
    /// sibling crates carry different tag families AND different versions
    /// (`a-v1.0.0` beside `b-v2.5.0`), so a version-only filter would
    /// silently drop the exact cross-crate evidence the disk pass exists
    /// to union in.
    #[test]
    fn burn_evidence_keeps_per_crate_sibling_summaries() {
        let log = StageLogger::new("test", Verbosity::Quiet);
        let dist = tempfile::tempdir().expect("tempdir");
        let mut ctx = Context::new(Config::default(), ContextOptions::default());
        ctx.config.dist = dist.path().to_path_buf();
        // Current run: crate b at 2.5.0.
        ctx.template_vars_mut().set("Version", "2.5.0");
        ctx.template_vars_mut().set("Tag", "b-v2.5.0");

        // Sibling crate a burned its own (different) version earlier in
        // the same release train.
        let mut report = PublishReport::default();
        report.results.push(result(
            "cargo",
            PublisherGroup::Submitter,
            PublisherOutcome::Succeeded,
        ));
        let mut sibling = RunSummary::from_context_with_report(&ctx, Some(&report));
        sibling.tag = "a-v1.0.0".to_string();
        let path = dist
            .path()
            .join("a")
            .join("run-a-v1.0.0")
            .join("summary.json");
        write_summary_json(&sibling, &path).expect("write sibling summary");

        let evidence = gather_burn_evidence(&ctx, &log);
        assert!(
            evidence.burned(),
            "a sibling crate's burn (different tag family) must be kept; got {evidence:?}"
        );
        assert_eq!(evidence.names, vec!["cargo".to_string()]);
    }

    /// A same-family tag whose base version matches but whose
    /// prerelease/build suffix differs from the current tag's is KEPT: a
    /// suffix-only representation mismatch cannot prove a different
    /// release, and guessing wrong flips the guard fail-open.
    #[test]
    fn burn_evidence_keeps_same_base_version_with_suffix_mismatch() {
        let log = StageLogger::new("test", Verbosity::Quiet);
        let dist = tempfile::tempdir().expect("tempdir");
        let mut ctx = Context::new(Config::default(), ContextOptions::default());
        ctx.config.dist = dist.path().to_path_buf();
        ctx.template_vars_mut().set("Version", "2.0.0");
        ctx.template_vars_mut().set("Tag", "v2.0.0");

        let mut report = PublishReport::default();
        report.results.push(result(
            "cargo",
            PublisherGroup::Submitter,
            PublisherOutcome::Succeeded,
        ));
        let mut summary = RunSummary::from_context_with_report(&ctx, Some(&report));
        summary.tag = "v2.0.0-rc.1".to_string();
        let path = dist.path().join("run-v2.0.0-rc.1").join("summary.json");
        write_summary_json(&summary, &path).expect("write prerelease summary");

        let evidence = gather_burn_evidence(&ctx, &log);
        assert!(
            evidence.burned(),
            "same-family same-base-version evidence must be kept despite a \
             prerelease suffix mismatch; got {evidence:?}"
        );
        assert_eq!(evidence.names, vec!["cargo".to_string()]);
    }

    /// When the current run's tag family cannot be established (no Tag
    /// template var), NOTHING is discarded — with no family to compare
    /// against, no summary can be proven to belong to a different release.
    #[test]
    fn burn_evidence_keeps_everything_without_a_current_tag() {
        let log = StageLogger::new("test", Verbosity::Quiet);
        let dist = tempfile::tempdir().expect("tempdir");
        let mut ctx = Context::new(Config::default(), ContextOptions::default());
        ctx.config.dist = dist.path().to_path_buf();
        ctx.template_vars_mut().set("Version", "2.0.0");

        let mut report = PublishReport::default();
        report.results.push(result(
            "cargo",
            PublisherGroup::Submitter,
            PublisherOutcome::Succeeded,
        ));
        let mut summary = RunSummary::from_context_with_report(&ctx, Some(&report));
        summary.tag = "v1.0.0".to_string();
        let path = dist.path().join("run-v1.0.0").join("summary.json");
        write_summary_json(&summary, &path).expect("write summary");

        let evidence = gather_burn_evidence(&ctx, &log);
        assert!(
            evidence.burned(),
            "with no current tag family the guard must keep everything; got {evidence:?}"
        );
    }

    /// A Tag template var that IS set but does not parse as a family+semver
    /// (a fully custom, non-semver tag template) must be treated the same
    /// as no Tag at all: `current_family` is `None` either way, so nothing
    /// on disk can be proven to belong to a different release and every
    /// summary — including a sibling per-crate burn — is kept.
    #[test]
    fn burn_evidence_keeps_sibling_with_unparseable_current_tag() {
        let log = StageLogger::new("test", Verbosity::Quiet);
        let dist = tempfile::tempdir().expect("tempdir");
        let mut ctx = Context::new(Config::default(), ContextOptions::default());
        ctx.config.dist = dist.path().to_path_buf();
        ctx.template_vars_mut().set("Version", "2.5.0");
        // Not a `<prefix->vX.Y.Z` shape `split_tag_family` can parse.
        ctx.template_vars_mut().set("Tag", "release-of-the-week");

        let mut report = PublishReport::default();
        report.results.push(result(
            "cargo",
            PublisherGroup::Submitter,
            PublisherOutcome::Succeeded,
        ));
        let mut sibling = RunSummary::from_context_with_report(&ctx, Some(&report));
        sibling.tag = "a-v1.0.0".to_string();
        let path = dist
            .path()
            .join("a")
            .join("run-a-v1.0.0")
            .join("summary.json");
        write_summary_json(&sibling, &path).expect("write sibling summary");

        let evidence = gather_burn_evidence(&ctx, &log);
        assert!(
            evidence.burned(),
            "an unparseable current Tag must not disable the sibling-burn guard; got {evidence:?}"
        );
        assert_eq!(evidence.names, vec!["cargo".to_string()]);
    }

    /// Mode gating: only the modes that reach upstream publishers are
    /// governed by the policy.
    #[test]
    fn applies_excludes_non_publishing_modes() {
        assert!(applies(&release_opts_fixture()), "full release applies");
        assert!(
            applies(&ReleaseOpts {
                publish_only: true,
                ..release_opts_fixture()
            }),
            "publish-only applies"
        );
        assert!(
            applies(&ReleaseOpts {
                merge: true,
                ..release_opts_fixture()
            }),
            "merge applies"
        );
        for (label, opts) in [
            (
                "dry-run",
                ReleaseOpts {
                    dry_run: true,
                    ..release_opts_fixture()
                },
            ),
            (
                "snapshot",
                ReleaseOpts {
                    snapshot: true,
                    ..release_opts_fixture()
                },
            ),
            (
                "preflight",
                ReleaseOpts {
                    preflight: true,
                    ..release_opts_fixture()
                },
            ),
            (
                "prepare",
                ReleaseOpts {
                    prepare: true,
                    ..release_opts_fixture()
                },
            ),
            (
                "split",
                ReleaseOpts {
                    split: true,
                    ..release_opts_fixture()
                },
            ),
            (
                "announce-only",
                ReleaseOpts {
                    announce_only: true,
                    ..release_opts_fixture()
                },
            ),
            (
                "rollback-only",
                ReleaseOpts {
                    rollback_only: true,
                    ..release_opts_fixture()
                },
            ),
            (
                // The determinism harness's hermetic replica sets this even
                // with snapshot=false (CI real-version mode), so it must
                // suppress the policy independent of the snapshot flag.
                "no-failure-policy",
                ReleaseOpts {
                    no_failure_policy: true,
                    ..release_opts_fixture()
                },
            ),
        ] {
            assert!(!applies(&opts), "{label} must not trigger the policy");
        }
    }

    /// Root-level resolution holds in all three config modes: the
    /// policy reads only the top-level `release:` block, so a
    /// single-crate config, a lockstep workspace, and a per-crate
    /// workspace resolve identically.
    #[test]
    fn on_failure_resolves_from_root_release_in_every_config_mode() {
        let single: Config = serde_yaml_ng::from_str(
            r#"
project_name: app
release:
  on_failure: hold
crates:
  - name: app
    path: "."
"#,
        )
        .expect("single-crate config parses");
        let lockstep: Config = serde_yaml_ng::from_str(
            r#"
project_name: ws
release:
  on_failure: hold
workspaces:
  - name: ws
    crates:
      - name: a
        path: crates/a
        tag_template: "v{{ Version }}"
      - name: b
        path: crates/b
        tag_template: "v{{ Version }}"
"#,
        )
        .expect("lockstep workspace config parses");
        let per_crate: Config = serde_yaml_ng::from_str(
            r#"
project_name: ws
release:
  on_failure: hold
workspaces:
  - name: ws
    crates:
      - name: a
        path: crates/a
        tag_template: "a-v{{ Version }}"
      - name: b
        path: crates/b
        tag_template: "b-v{{ Version }}"
"#,
        )
        .expect("per-crate workspace config parses");

        for (label, config) in [
            ("single-crate", single),
            ("lockstep", lockstep),
            ("per-crate", per_crate),
        ] {
            let resolved = config
                .release
                .as_ref()
                .map(|r| r.resolved_on_failure())
                .unwrap_or_default();
            assert_eq!(
                resolved,
                OnFailureConfig::Hold,
                "{label}: root release.on_failure must govern"
            );
        }

        let unset: Config = serde_yaml_ng::from_str("project_name: app\n").expect("minimal config");
        assert_eq!(
            unset
                .release
                .as_ref()
                .map(|r| r.resolved_on_failure())
                .unwrap_or_default(),
            OnFailureConfig::Rollback,
            "unset policy defaults to rollback"
        );
    }

    /// Root `on_error:` parses identically in all three config modes —
    /// a root-level hook block like `before:` / `after:`, so single-crate,
    /// lockstep, and per-crate configs resolve the same hook list.
    #[test]
    fn on_error_hooks_parse_in_every_config_mode() {
        for (label, yaml) in [
            (
                "single-crate",
                "project_name: app\non_error:\n  hooks:\n    - ./notify.sh\ncrates:\n  - name: app\n    path: \".\"\n",
            ),
            (
                "lockstep",
                "project_name: ws\non_error:\n  hooks:\n    - ./notify.sh\nworkspaces:\n  - name: ws\n    crates:\n      - name: a\n        path: crates/a\n        tag_template: \"v{{ Version }}\"\n",
            ),
            (
                "per-crate",
                "project_name: ws\non_error:\n  hooks:\n    - ./notify.sh\nworkspaces:\n  - name: ws\n    crates:\n      - name: a\n        path: crates/a\n        tag_template: \"a-v{{ Version }}\"\n",
            ),
        ] {
            let config: Config = serde_yaml_ng::from_str(yaml)
                .unwrap_or_else(|e| panic!("{label}: config must parse: {e}"));
            let hooks = config
                .on_error
                .as_ref()
                .and_then(|h| h.hooks.as_deref())
                .unwrap_or_default();
            assert_eq!(hooks.len(), 1, "{label}: one on_error hook resolves");
        }
    }

    /// The three rollback outcomes map onto three distinct recorded
    /// actions: clean → `rolled-back`, guard refusal → `rollback-refused`
    /// (protection, not breakage), mechanical error → `rollback-failed`.
    #[test]
    fn rollback_record_distinguishes_refusal_from_mechanical_failure() {
        let log = StageLogger::new("test", Verbosity::Quiet);

        let clean = rollback_record(OnFailureConfig::Rollback, Ok(()), &log);
        assert_eq!(clean.action, "rolled-back");
        assert!(clean.rollback_error.is_none());

        let refusal = RollbackRefusal {
            reason: "v0.5.0 is live on crates.io from a prior attempt".into(),
            next_step: "fix the failure and cut the NEXT version".into(),
        };
        let refused = rollback_record(OnFailureConfig::Rollback, Err(refusal.into()), &log);
        assert_eq!(refused.action, "rollback-refused");
        assert!(
            refused
                .rollback_error
                .as_deref()
                .is_some_and(|e| e.contains("crates.io")),
            "the recorded refusal must carry the burn evidence: {refused:?}"
        );

        let failed = rollback_record(
            OnFailureConfig::Rollback,
            Err(anyhow::anyhow!("git push failed: non-fast-forward")),
            &log,
        );
        assert_eq!(failed.action, "rollback-failed");
        assert!(
            failed
                .rollback_error
                .as_deref()
                .is_some_and(|e| e.contains("non-fast-forward")),
            "the recorded failure must carry the mechanical error: {failed:?}"
        );
    }

    /// The refusal classification must survive `anyhow` context wrapping
    /// (downcast walks the whole chain) so a future `with_context` on
    /// the rollback path cannot silently demote refusals to warns.
    #[test]
    fn rollback_refusal_downcast_survives_context_wrapping() {
        let err = anyhow::Error::from(RollbackRefusal {
            reason: "burned".into(),
            next_step: "next version".into(),
        })
        .context("while executing the failure policy");
        assert!(err.downcast_ref::<RollbackRefusal>().is_some());
    }

    /// Root `on_error:` hooks fire on a pipeline failure with the error
    /// text and rollback verdict delivered via `ANODIZER_*` env vars
    /// (never interpolated into the command string).
    #[test]
    #[cfg(unix)]
    fn release_on_error_hooks_fire_with_error_env() {
        use anodizer_core::config::{HookEntry, HooksConfig, StructuredHook};
        let dir = tempfile::tempdir().expect("tempdir");
        let out = dir.path().join("fired.txt");
        let out_str = out.display().to_string();
        let config = Config {
            on_error: Some(HooksConfig {
                hooks: Some(vec![HookEntry::Structured(StructuredHook {
                    cmd: format!(
                        "printf '%s\\n' \"err=$ANODIZER_ERROR rolled=$ANODIZER_ROLLED_BACK\" \
                         >> {out_str}"
                    ),
                    ..Default::default()
                })]),
                post: None,
            }),
            ..Default::default()
        };
        let ctx = Context::new(config, ContextOptions::default());
        let log = StageLogger::new("test", Verbosity::Quiet);
        fire_release_on_error(
            &ctx,
            &anyhow::anyhow!("sign stage failed: boom"),
            true,
            &log,
        );
        let fired = std::fs::read_to_string(&out).expect("hook must have fired");
        assert!(
            fired.contains("err=sign stage failed: boom"),
            "hook must see the pipeline error via env: {fired}"
        );
        assert!(
            fired.contains("rolled=true"),
            "hook must see the rollback verdict via env: {fired}"
        );
    }

    /// With no root `on_error:` configured, a pipeline failure fires
    /// nothing and panics nothing.
    #[test]
    fn release_on_error_without_hooks_is_a_noop() {
        let ctx = Context::new(Config::default(), ContextOptions::default());
        let log = StageLogger::new("test", Verbosity::Quiet);
        fire_release_on_error(&ctx, &anyhow::anyhow!("boom"), false, &log);
    }
}