anodizer-core 0.25.1

Core configuration, context, and template engine for the anodizer release tool
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
//! Per-publisher run evidence (the `evidence.json` shape).
//!
//! [`PublishEvidence`] captures what a publisher actually pushed plus
//! the operator-public coordinates a later `anodizer tag rollback`
//! consumes. The [`extra`] slot used to be a free-form
//! `serde_json::Value`; it is now a typed enum
//! ([`PublishEvidenceExtra`]) so the type system structurally
//! prevents credential leakage — a publisher cannot serialize a
//! credential-shaped field into evidence because the variant struct
//! has no such field to hold it.
//!
//! Wire format is preserved: `#[serde(untagged)]` on the enum keeps
//! the rendered JSON identical to the prior free-form
//! `{ "<publisher>_targets": [...] }` shape, so consumers of
//! `dist/run-<id>/report.json` and `summary.json` see the same bytes.
//!
//! [`extra`]: PublishEvidence::extra

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::PathBuf;

/// One entry in [`HomebrewExtra::homebrew_targets`] — the operator-public
/// snapshot of a single tap push. Mirrors the serialized field set of
/// `HomebrewTarget` in `stage-publish/src/homebrew/publisher.rs`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct HomebrewTargetSnapshot {
    /// Per-target label — formula name, cask name, or `homebrew_casks`
    /// for the top-level path.
    pub target: String,
    /// HTTPS clone URL of the tap repo.
    pub repo_url: String,
    /// Branch the publish path pushed to. `None` means default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
    /// Env var NAME to consult for the rollback re-clone token.
    /// NEVER the token VALUE.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_env_var: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct HomebrewExtra {
    pub homebrew_targets: Vec<HomebrewTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ScoopTargetSnapshot {
    pub target: String,
    pub repo_url: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_env_var: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ScoopExtra {
    pub scoop_targets: Vec<ScoopTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct NixTargetSnapshot {
    pub target: String,
    pub repo_url: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_env_var: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct NixExtra {
    pub nix_targets: Vec<NixTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct WingetTargetSnapshot {
    pub target: String,
    pub crate_name: String,
    pub package_id: String,
    pub version: String,
    pub upstream_owner: String,
    pub upstream_repo: String,
    pub fork_owner: String,
    pub branch: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct WingetExtra {
    pub winget_targets: Vec<WingetTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ChocolateyTargetSnapshot {
    pub target: String,
    pub crate_name: String,
    pub package_id: String,
    pub version: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ChocolateyExtra {
    pub chocolatey_targets: Vec<ChocolateyTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct KrewTargetSnapshot {
    pub target: String,
    pub upstream_owner: String,
    pub upstream_repo: String,
    pub fork_owner: String,
    pub branch: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_env_var: Option<String>,
}

// NOTE: no `deny_unknown_fields` here (every sibling extra struct has it).
// An intra-branch iteration carried a `bot_template_pre_image_shas` field
// that was removed before any release tag. Tolerating unknown keys lets a
// `report.json` written by such a build still deserialize for rollback;
// the orphan key is simply ignored. Adding it back would resurrect a field
// that never shipped, so the lenient decode is the durable fix.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct KrewExtra {
    /// One entry per crate whose krew publish opened a PR against the
    /// upstream krew-index (the `PrDirect` initial-submission flow).
    /// Empty for plugins already in krew-index, which take the
    /// self-contained webhook path: the krew-release-bot server owns
    /// the krew-index PR there, so anodizer has no PR to roll back.
    pub krew_targets: Vec<KrewTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct AurTargetSnapshot {
    pub target: String,
    /// AUR SSH URL — operator-public coordinate.
    pub git_url: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct AurExtra {
    pub aur_our_targets: Vec<AurTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct AurSourceTargetSnapshot {
    pub target: String,
    pub package: String,
    pub tag: String,
    pub git_url: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct AurSourceExtra {
    pub aur_source_targets: Vec<AurSourceTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct McpTargetSnapshot {
    pub target: String,
    pub server_name: String,
    pub registry_url: String,
    pub version: String,
    /// MCP auth method — operator-public; carries no credential bytes.
    /// Serializes as `"none"` / `"github"` / `"github-oidc"` per the
    /// rename annotations on [`crate::config::McpAuthMethod`].
    pub auth_method: crate::config::McpAuthMethod,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct McpExtra {
    pub mcp_targets: Vec<McpTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct DockerhubTargetSnapshot {
    pub target: String,
    pub repo_url: String,
    pub namespace: String,
    pub name: String,
    /// DockerHub login — operator-public.
    pub username: String,
    /// Env var NAME the rollback path consults to re-resolve the password.
    /// NEVER the password VALUE.
    pub secret_env_var: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub snapshot_description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub snapshot_full_description: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct DockerhubExtra {
    pub dockerhub_targets: Vec<DockerhubTargetSnapshot>,
}

/// One crate whose `cargo publish` SUCCEEDED during this run, recorded
/// at the moment of success so rollback can yank exactly what went live.
///
/// `version` is the per-crate version actually published (workspaces with
/// mixed cadences publish different versions per crate). `registry` /
/// `index` mirror the `publish.cargo.registry` / `publish.cargo.index`
/// the publish used so the yank targets the SAME registry — both are
/// operator-public identifiers (a registry name, an index URL), never
/// credential bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct CargoYankTargetSnapshot {
    pub name: String,
    pub version: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub registry: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub index: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct CargoExtra {
    pub cargo_yank_targets: Vec<CargoYankTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ArtifactoryTargetSnapshot {
    pub entry: String,
    pub url: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ArtifactoryExtra {
    pub artifactory_targets: Vec<ArtifactoryTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct CloudsmithTargetSnapshot {
    pub org: String,
    pub repo: String,
    pub filename: String,
    #[serde(default)]
    pub slug: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct CloudsmithExtra {
    pub cloudsmith_targets: Vec<CloudsmithTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct BlobTargetSnapshot {
    pub provider: String,
    pub bucket: String,
    pub key: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct BlobExtra {
    pub blob_targets: Vec<BlobTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct SnapcraftTargetSnapshot {
    pub crate_name: String,
    pub package_name: String,
    #[serde(default)]
    pub channel: Option<String>,
    /// The snapcraft architecture this entry's revision was minted for
    /// (`amd64`, `arm64`, …). A dual-arch snap mints one Snap Store revision
    /// per architecture, so the evidence carries one entry per arch and a
    /// `promote --from-run` releases every arch's recorded revision. `None`
    /// on a planned-but-unprocessed snapshot or an older report predating the
    /// per-arch model.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub arch: Option<String>,
    #[serde(default)]
    pub revision: Option<String>,
    /// The version this run uploaded, so post-publish verification can probe
    /// the store's channel map for it.
    #[serde(default)]
    pub version: Option<String>,
    /// The Snap Store answered the upload with a manual-review hold: the
    /// binary was accepted but is NOT live in any channel until a human
    /// approves it. Recorded so the verify-release landing check and
    /// `anodizer tag rollback` consumers see the unresolved state
    /// instead of a silent "uploaded".
    #[serde(default)]
    pub held_for_review: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct SnapcraftExtra {
    pub snapcraft_targets: Vec<SnapcraftTargetSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct GithubReleaseTargetSnapshot {
    pub crate_name: String,
    pub owner: String,
    pub repo: String,
    pub tag: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub release_id: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct GithubReleaseExtra {
    pub github_release_targets: Vec<GithubReleaseTargetSnapshot>,
}

/// Operator-public snapshot of a single NPM `package@version` publish.
/// Stored in [`NpmExtra::npm_targets`] so a later `anodizer tag rollback`
/// has the exact coordinates required to attempt `npm unpublish` within
/// the 72-hour window.
///
/// **CREDENTIAL CONTRACT**: no token field — the auth token is resolved
/// at publish/rollback time from the env var named by `token_env_var`
/// (default `NPM_TOKEN`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct NpmTargetSnapshot {
    /// Per-target label — the package name (scoped or unscoped).
    pub target: String,
    /// NPM package name as published (e.g. `@scope/foo`).
    pub package: String,
    /// Published version (semver string, no `v` prefix).
    pub version: String,
    /// Registry endpoint URL (e.g. `https://registry.npmjs.org`).
    pub registry: String,
    /// Dist-tag the version was pushed under (default `latest`).
    pub dist_tag: String,
    /// Env var NAME to consult for the rollback `npm unpublish` token.
    /// NEVER the token VALUE.
    pub token_env_var: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct NpmExtra {
    pub npm_targets: Vec<NpmTargetSnapshot>,
}

/// Operator-public snapshot of a single GemFury push of one artifact file.
/// Stored in [`GemFuryExtra::gemfury_targets`] so a later
/// `anodizer tag rollback` has the exact coordinates required to
/// issue `DELETE https://api.fury.io/<account>/packages/<name>/versions/<version>`
/// against the Fury delete API.
///
/// **CREDENTIAL CONTRACT**: no token fields — push and delete tokens are
/// resolved at publish/rollback time from the env vars named by
/// `push_token_env_var` (default `FURY_PUSH_TOKEN`) and `api_token_env_var`
/// (default `FURY_API_TOKEN`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct GemFuryTargetSnapshot {
    /// Per-target label — `<account>/<package>` for log lines.
    pub target: String,
    /// GemFury account name (operator-public; the `<account>` segment of
    /// `https://push.fury.io/<account>`).
    pub account: String,
    /// Package basename pushed (e.g. `mytool_1.2.3_amd64.deb`).
    pub package: String,
    /// Published version (semver string, no `v` prefix).
    pub version: String,
    /// Artifact format as detected from the filename extension
    /// (`deb` / `rpm` / `apk`).
    pub format: String,
    /// Env var NAME the rollback path consults to re-resolve the push
    /// token. NEVER the token VALUE.
    pub push_token_env_var: String,
    /// Env var NAME the rollback path consults to re-resolve the API
    /// (delete) token. NEVER the token VALUE.
    pub api_token_env_var: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct GemFuryExtra {
    pub gemfury_targets: Vec<GemFuryTargetSnapshot>,
}

/// Operator-public snapshot of a single file uploaded to a PyPI-compatible
/// index (one wheel or one sdist). Stored in [`PypiExtra::pypi_files`].
/// PyPI uploads are one-way — a published filename can NEVER be re-uploaded,
/// even after deletion — so these snapshots exist for the audit trail and
/// the run report, not for a programmatic rollback.
///
/// **CREDENTIAL CONTRACT**: no token field — the upload token is resolved
/// at publish time from config / `PYPI_TOKEN` / `MATURIN_PYPI_TOKEN` and is
/// never persisted.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct PypiFileSnapshot {
    /// Uploaded filename (e.g. `my_tool-1.2.3-py3-none-manylinux_2_28_x86_64.whl`).
    pub filename: String,
    /// Wheel platform tag (e.g. `manylinux_2_28_x86_64`), or `source` for an
    /// sdist.
    pub platform_tag: String,
    /// Hex SHA-256 of the uploaded file.
    pub sha256: String,
    /// Upload endpoint URL the file was sent to.
    pub repository: String,
    /// `true` when the index rejected the file as already existing and the
    /// entry's `skip_existing` treated that as an idempotent skip — the file
    /// was already live from an earlier run, not placed by this one.
    pub skipped_existing: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct PypiExtra {
    pub pypi_files: Vec<PypiFileSnapshot>,
}

/// Operator-public snapshot of a single SchemaStore registration PR — the
/// fork branch anodizer pushed and the upstream it opened the PR against.
/// Stored in [`SchemastoreExtra::schemastore_targets`] so a later
/// `anodizer tag rollback` can find and close the open PR.
///
/// **CREDENTIAL CONTRACT**: no token field — the rollback token is
/// resolved at rollback time from the env var named by `token_env_var`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct SchemastoreTargetSnapshot {
    /// Upstream `SchemaStore/schemastore` owner the PR targets.
    pub upstream_owner: String,
    /// Upstream repo name (`schemastore`).
    pub upstream_repo: String,
    /// Login of the fork the branch was pushed to.
    pub fork_owner: String,
    /// Branch pushed to the fork (the PR head).
    pub branch: String,
    /// Env var NAME the rollback path consults for the close-PR token.
    /// NEVER the token VALUE.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_env_var: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct SchemastoreExtra {
    pub schemastore_targets: Vec<SchemastoreTargetSnapshot>,
}

/// Operator-public snapshot of a single homebrew-core formula bump — the
/// branch anodizer committed the rewritten formula to and the upstream the
/// PR targets. Stored in [`HomebrewCoreExtra::homebrew_core_targets`] so a
/// later `anodizer tag rollback` can find and close the open PR.
///
/// **CREDENTIAL CONTRACT**: no token field — the rollback token is
/// resolved at rollback time from the env var named by `token_env_var`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct HomebrewCoreTargetSnapshot {
    /// Formula name that was bumped (e.g. `my-tool`).
    pub formula: String,
    /// Version the formula was bumped to.
    pub version: String,
    /// Owner of the formula repository the PR targets (`Homebrew` for core).
    pub upstream_owner: String,
    /// Name of the formula repository (`homebrew-core` for core).
    pub upstream_repo: String,
    /// Login of the repo the bump branch was pushed to — the fork owner on
    /// the fork+PR path, the upstream owner on the same-repo-branch path.
    pub head_owner: String,
    /// Branch carrying the bump commit (the PR head branch). Empty on the
    /// `direct_commit` path, where the bump landed on the base branch.
    pub branch: String,
    /// `true` when the bump was committed straight to the base branch
    /// (`direct_commit: true`) — nothing to close on rollback.
    pub direct_commit: bool,
    /// URL of the opened pull request, when one was opened.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pr_url: Option<String>,
    /// Env var NAME the rollback path consults for the close-PR token.
    /// NEVER the token VALUE.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_env_var: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct HomebrewCoreExtra {
    pub homebrew_core_targets: Vec<HomebrewCoreTargetSnapshot>,
}

/// Typed `extra` payload for [`PublishEvidence`]. Untagged on the wire —
/// each variant's JSON shape matches the prior free-form
/// `serde_json::json!({"<publisher>_targets": [...]})` form so existing
/// consumers of `dist/run-<id>/report.json` and `summary.json` see no
/// byte-shape change.
///
/// **CREDENTIAL CONTRACT**: every variant's inner struct exposes ONLY
/// operator-public fields. Credential VALUES (token bytes, passwords,
/// SSH key material) have no field to land in — the type system rejects
/// any future leak attempt at the compile boundary. Per-publisher
/// runtime credentials (resolved from env / config at publish time)
/// live in crate-local `*Target` structs with `#[serde(skip)]`
/// discipline; they convert into the snapshots above at the encode
/// boundary, dropping the secret fields by definition.
///
/// The [`Empty`](Self::Empty) variant covers publishers that have no
/// per-evidence operator-public fields (or that no-op'd the run).
/// Serializes as `null` on the wire and is the deserialization
/// fallback for the same shape.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(untagged)]
pub enum PublishEvidenceExtra {
    Homebrew(HomebrewExtra),
    Scoop(ScoopExtra),
    Nix(NixExtra),
    Winget(WingetExtra),
    Chocolatey(ChocolateyExtra),
    Krew(KrewExtra),
    Aur(AurExtra),
    AurSource(AurSourceExtra),
    Mcp(McpExtra),
    Dockerhub(DockerhubExtra),
    Cargo(CargoExtra),
    Artifactory(ArtifactoryExtra),
    Cloudsmith(CloudsmithExtra),
    Blob(BlobExtra),
    Snapcraft(SnapcraftExtra),
    GithubRelease(GithubReleaseExtra),
    Npm(NpmExtra),
    GemFury(GemFuryExtra),
    Pypi(PypiExtra),
    Schemastore(SchemastoreExtra),
    HomebrewCore(HomebrewCoreExtra),
    /// Default for publishers with no per-evidence operator-public fields,
    /// or for runs that no-op'd. Serializes as JSON `null`.
    #[default]
    Empty,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PublishEvidence {
    pub schema_version: u32,
    pub publisher: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub primary_ref: Option<String>,
    pub artifact_paths: Vec<PathBuf>,
    /// Content-hash snapshot (artifact NAME → `sha256:<hex>`) taken from
    /// each in-scope [`crate::artifact::Artifact`]'s `Checksum` metadata
    /// at publish time. Used by the ledger fast-path: a later reconcile
    /// consults this map to tell "rebuilt identical bytes" (safe to
    /// short-circuit) apart from "rebuilt different bytes, same version"
    /// (must fall through to the network probe). `#[serde(default)]` so
    /// v1 `summary.json` files written before this field existed still
    /// deserialize — a reader that hard-failed on a missing field would
    /// silently degrade every reconcile to a network round-trip.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub artifact_digests: BTreeMap<String, String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nondeterministic: Option<String>,
    /// Operator-public metadata for the publisher run.
    ///
    /// **CREDENTIAL CONTRACT**: this field is persisted to
    /// `dist/run-<id>/report.json`, summarised in `summary.json`, and
    /// may be attached to the GitHub Release body via the announce
    /// stage. It carries only operator-public identifiers (URLs,
    /// env-var NAMES, PR numbers, tag strings, branch names). Token
    /// VALUES, private keys, passwords, OAuth secrets, SSH key
    /// material have no variant field to land in — the
    /// [`PublishEvidenceExtra`] enum's per-variant struct list is the
    /// schema, and serde rejects fields it does not name.
    ///
    /// Per-publisher rollback state (runtime-only credentials read
    /// from env / config at publish time) lives in crate-local
    /// `*Target` structs with `#[serde(skip)]` discipline; those
    /// convert into the [`PublishEvidenceExtra`] variant snapshots at
    /// the encode boundary, dropping the secret fields by definition.
    #[serde(default, deserialize_with = "deserialize_extra_compat")]
    pub extra: PublishEvidenceExtra,
}

/// Deserialize the `extra:` field with backwards-compatibility for
/// reports written before the typed [`PublishEvidenceExtra`] enum
/// landed. Those reports carried `extra: {}` (an empty object) where
/// the typed enum's [`Empty`](PublishEvidenceExtra::Empty) variant
/// serializes as `null`. With `#[serde(untagged)]` neither null nor
/// the typed struct variants match `{}`, so a literal `{}` from an
/// older report fails to deserialize. This shim coerces null and `{}`
/// to `Empty`; any other shape goes through the normal untagged
/// dispatch.
fn deserialize_extra_compat<'de, D>(deserializer: D) -> Result<PublishEvidenceExtra, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = serde_json::Value::deserialize(deserializer)?;
    if value.is_null() {
        return Ok(PublishEvidenceExtra::Empty);
    }
    if let Some(map) = value.as_object()
        && map.is_empty()
    {
        return Ok(PublishEvidenceExtra::Empty);
    }
    serde_json::from_value(value).map_err(serde::de::Error::custom)
}

impl PublishEvidence {
    /// Version of the evidence wire format. Operators reading the
    /// constant know whether their installed anodizer matches the
    /// producer that wrote a given `report.json` blob; a format change
    /// bumps this alongside the corresponding decoder update.
    pub const CURRENT_SCHEMA_VERSION: u32 = 2;

    pub fn new(publisher: impl Into<String>) -> Self {
        Self {
            schema_version: Self::CURRENT_SCHEMA_VERSION,
            publisher: publisher.into(),
            primary_ref: None,
            artifact_paths: Vec::new(),
            artifact_digests: BTreeMap::new(),
            nondeterministic: None,
            extra: PublishEvidenceExtra::Empty,
        }
    }
}

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

    #[test]
    fn publish_evidence_roundtrips_through_json() {
        let mut e = PublishEvidence::new("homebrew");
        e.primary_ref = Some("refs/heads/main".to_string());
        e.artifact_paths.push(PathBuf::from("dist/foo.tar.gz"));
        e.nondeterministic = Some("timestamp".to_string());
        e.extra = PublishEvidenceExtra::Homebrew(HomebrewExtra {
            homebrew_targets: vec![HomebrewTargetSnapshot {
                target: "demo".into(),
                repo_url: "https://github.com/acme/homebrew-tap.git".into(),
                branch: Some("main".into()),
                token_env_var: Some("HOMEBREW_TAP_TOKEN".into()),
            }],
        });

        let s = serde_json::to_string(&e).expect("serialize");
        let back: PublishEvidence = serde_json::from_str(&s).expect("deserialize");
        assert_eq!(e, back);
    }

    #[test]
    fn cargo_extra_roundtrips_and_omits_none_registry_index() {
        let mut e = PublishEvidence::new("cargo");
        e.extra = PublishEvidenceExtra::Cargo(CargoExtra {
            cargo_yank_targets: vec![
                CargoYankTargetSnapshot {
                    name: "crate-a".into(),
                    version: "1.0.0".into(),
                    registry: Some("my-registry".into()),
                    index: None,
                },
                CargoYankTargetSnapshot {
                    name: "crate-b".into(),
                    version: "2.0.0".into(),
                    registry: None,
                    index: None,
                },
            ],
        });

        let s = serde_json::to_string(&e).expect("serialize");
        // None registry/index are omitted; the variant key is the typed shape.
        assert!(
            s.contains("cargo_yank_targets"),
            "wire carries variant key: {s}"
        );
        assert!(s.contains("my-registry"), "registry preserved: {s}");
        assert!(
            !s.contains("\"index\""),
            "None index omitted on the wire: {s}"
        );

        let back: PublishEvidence = serde_json::from_str(&s).expect("deserialize");
        assert_eq!(e, back);
        // Untagged disjointness: a Cargo payload decodes to the Cargo
        // variant, not an earlier `*_targets` variant.
        assert!(matches!(back.extra, PublishEvidenceExtra::Cargo(_)));
    }

    #[test]
    fn artifact_digests_defaults_empty_on_v1_json_missing_the_field() {
        let v1 = r#"{
            "schema_version": 1,
            "publisher": "cargo",
            "primary_ref": null,
            "artifact_paths": [],
            "nondeterministic": null,
            "extra": null
        }"#;
        let e: PublishEvidence = serde_json::from_str(v1).expect("v1 summaries must still parse");
        assert!(e.artifact_digests.is_empty());
    }

    #[test]
    fn artifact_digests_roundtrips_through_json() {
        let mut e = PublishEvidence::new("cargo");
        e.artifact_digests
            .insert("myapp-x86_64.tar.gz".into(), "sha256:abc123".into());
        let s = serde_json::to_string(&e).expect("serialize");
        assert!(s.contains("myapp-x86_64.tar.gz"), "{s}");
        let back: PublishEvidence = serde_json::from_str(&s).expect("deserialize");
        assert_eq!(e, back);
    }

    #[test]
    fn publish_evidence_omits_none_fields_on_serialize() {
        let e = PublishEvidence::new("homebrew");
        let s = serde_json::to_string(&e).expect("serialize");
        assert!(
            !s.contains("primary_ref"),
            "primary_ref should be omitted when None: {s}"
        );
        assert!(
            !s.contains("nondeterministic"),
            "nondeterministic should be omitted when None: {s}"
        );
        let back: PublishEvidence = serde_json::from_str(&s).expect("deserialize");
        assert_eq!(e, back);
    }

    #[test]
    fn publish_evidence_rejects_unknown_fields() {
        let bad = r#"{
            "schema_version": 1,
            "publisher": "homebrew",
            "primary_ref": null,
            "artifact_paths": [],
            "nondeterministic": null,
            "extra": null,
            "future_field": "boom"
        }"#;
        let r: Result<PublishEvidence, _> = serde_json::from_str(bad);
        assert!(r.is_err(), "deny_unknown_fields should reject future_field");
    }

    #[test]
    fn empty_variant_serializes_as_null() {
        // The Empty variant is the default for newly constructed evidence;
        // pinning its wire shape ensures back-compat with the prior `{}` /
        // null default and avoids accidental shape drift.
        let e = PublishEvidence::new("homebrew");
        let s = serde_json::to_string(&e).expect("serialize");
        let v: serde_json::Value = serde_json::from_str(&s).expect("parse");
        assert_eq!(v["extra"], serde_json::Value::Null);
    }

    #[test]
    fn empty_variant_deserializes_from_null() {
        // Untagged enum: null lands on Empty (the unit variant is the
        // only one that accepts a null payload). Pin the wire shape
        // so a future variant addition that breaks this path fails
        // here.
        let from_null = serde_json::from_str::<PublishEvidenceExtra>("null").expect("null");
        assert_eq!(from_null, PublishEvidenceExtra::Empty);
    }

    #[test]
    fn krew_extra_roundtrips_pr_direct_targets() {
        // The PrDirect flow records one `KrewTargetSnapshot` per crate
        // whose publish opened a krew-index PR; the BotWebhook flow
        // records none. Pin the round-trip so the rollback consumer
        // always reads back the coordinates it needs to close the PR.
        let extra = KrewExtra {
            krew_targets: vec![KrewTargetSnapshot {
                target: "mytool".into(),
                upstream_owner: "kubernetes-sigs".into(),
                upstream_repo: "krew-index".into(),
                fork_owner: "acme".into(),
                branch: "mytool-v1.2.3".into(),
                token_env_var: Some("KREW_INDEX_TOKEN".into()),
            }],
        };
        let json = serde_json::to_string(&extra).expect("serialize");
        let back: KrewExtra = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back, extra);
    }

    #[test]
    fn krew_extra_empty_targets_serializes() {
        // The BotWebhook flow records no targets — an empty `KrewExtra`
        // must still round-trip cleanly.
        let extra = KrewExtra {
            krew_targets: vec![],
        };
        let json = serde_json::to_string(&extra).expect("serialize");
        let back: KrewExtra = serde_json::from_str(&json).expect("deserialize");
        assert!(back.krew_targets.is_empty());
    }

    #[test]
    fn krew_extra_tolerates_orphan_bot_template_key() {
        // A `report.json` written by an intra-branch build that still
        // carried the since-removed `bot_template_pre_image_shas` field
        // must still deserialize for rollback — the orphan key is ignored.
        let blob = r#"{
            "krew_targets": [{
                "target": "mytool",
                "upstream_owner": "kubernetes-sigs",
                "upstream_repo": "krew-index",
                "fork_owner": "acme",
                "branch": "mytool-v1.2.3"
            }],
            "bot_template_pre_image_shas": {"plugins/mytool.yaml": "deadbeef"}
        }"#;
        let back: KrewExtra = serde_json::from_str(blob).expect("orphan key must be tolerated");
        assert_eq!(back.krew_targets.len(), 1);
        assert_eq!(back.krew_targets[0].target, "mytool");

        // The same blob must deserialize through the full untagged
        // `PublishEvidenceExtra` dispatch (the path rollback actually
        // takes), landing in the Krew variant.
        let via_enum: PublishEvidenceExtra =
            serde_json::from_str(blob).expect("untagged dispatch must tolerate orphan key");
        assert!(matches!(via_enum, PublishEvidenceExtra::Krew(_)));
    }

    #[test]
    fn publish_evidence_schema_version_is_two() {
        // The constant is the operator-visible signal for the evidence
        // wire format. A future bump must update this test alongside
        // the constant.
        assert_eq!(PublishEvidence::CURRENT_SCHEMA_VERSION, 2);
    }

    #[test]
    fn publish_evidence_extra_json_shape_matches_pre_typed_form() {
        // Wire-format pin: downstream consumers of
        // `dist/run-<id>/report.json` see the same byte shape that
        // shipped pre-typed-enum. A variant addition that drifts the
        // shape (e.g. wraps the homebrew_targets array in an extra
        // object) fails this test.
        let e = PublishEvidence {
            extra: PublishEvidenceExtra::Homebrew(HomebrewExtra {
                homebrew_targets: vec![HomebrewTargetSnapshot {
                    target: "demo".into(),
                    repo_url: "https://github.com/owner/tap".into(),
                    branch: Some("anodize-update".into()),
                    token_env_var: Some("ANODIZER_GITHUB_TOKEN".into()),
                }],
            }),
            ..PublishEvidence::new("homebrew")
        };
        let s = serde_json::to_string(&e).expect("serialize");
        let v: serde_json::Value = serde_json::from_str(&s).expect("parse");
        let t = &v["extra"]["homebrew_targets"][0];
        assert_eq!(t["target"], "demo");
        assert_eq!(t["repo_url"], "https://github.com/owner/tap");
        assert_eq!(t["branch"], "anodize-update");
        assert_eq!(t["token_env_var"], "ANODIZER_GITHUB_TOKEN");
        // Defense-in-depth: no credential-shaped keys in the rendered
        // form (matches the per-publisher `*_extra_carries_no_secret_material`
        // tests but pinned at the core wire-format level).
        assert!(!s.contains("\"token\":"), "{s}");
        assert!(!s.contains("\"password\":"), "{s}");
        assert!(!s.contains("\"pat\":"), "{s}");
        assert!(!s.contains("\"private_key\":"), "{s}");
        assert!(!s.contains("\"secret\":"), "{s}");
        assert!(!s.contains("\"api_key\":"), "{s}");
    }
}