ossctl-core 0.4.0

Core library for ossctl: contract normalizer, repo-fact detection, audit scoring, release engine, and the versioned protocol DTOs.
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
//! Homebrew distribution adapter: `homebrew-tap` and `homebrew-core`.
//!
//! Updates a Homebrew formula (a custom tap, or a `homebrew-core` bump PR) so
//! `brew install` resolves the new version. A tap/core is not observable through
//! the [`RegistryQuery`](crate::ports::RegistryQuery) port, so `verify` returns
//! [`VerifyOutcome::Unknown`] **explicitly** rather than being excused from the
//! contract (ADR-0002 §1) — an honest "cannot check", never a false `Missing`.
//!
//! ## Three formula paths: create, tap-write, bump-PR
//!
//! A release either **creates** the first `<name>.rb` on an empty tap or
//! **updates** an existing one. This adapter chooses by asking the tap whether the
//! formula already exists (through the injected
//! [`CommandRunner`](crate::ports::CommandRunner), so it is testable with no real
//! network or tap):
//!
//! - **configured tap, formula absent** → the *create* path: generate a
//!   source-build formula (the release tarball's `url` + `sha256`, the license, a
//!   cargo build/install stanza), clone the tap, commit the new file on a branch,
//!   and open a PR.
//! - **configured tap, formula present** → the *tap-write* path
//!   (`FormulaPath::TapWrite`): render the updated `<name>.rb` from the verified
//!   `url` + `sha256`, clone the tap, update the file, commit, and **push
//!   directly to the tap's default branch** — no `brew`, no `bump-formula-pr`, no
//!   `brew audit`. This is deterministic, needs no local `brew`/ruby/gem toolchain
//!   on the cutting machine, and mirrors the manual fallback that has always
//!   worked. It **fails closed** without a verified `sha256` (unlike create, which
//!   can open a draft-PR placeholder, a formula on the tap's *default branch* is
//!   what `brew install` resolves — so an unverified digest would ship a broken
//!   install), and it is a **clean no-op** when the tap already carries exactly
//!   this formula (an idempotent resume/re-run at the target version).
//! - **no configured tap** (a `homebrew-core` target, or a `homebrew-tap` with no
//!   resolved tap) → the *bump-PR* path: `brew bump-formula-pr` carrying the
//!   release tarball's `--url` (+ `--sha256` when a digest is available). First
//!   submission to `homebrew-core` is a human review process where the full core
//!   `brew audit` is appropriate, so the PR path is kept for it.
//!
//! ## Why tap-write replaced `brew bump-formula-pr` for the tap-bump case
//!
//! `brew bump-formula-pr` runs a full `brew audit` internally and aborts the whole
//! bump on any finding — including cosmetic core-lint changes irrelevant to a
//! personal tap the maintainer controls (issue `homebrew-dist-brew-audit-fails`:
//! the first engine dogfood cut failed here with a swallowed audit message). The
//! tap-write path removes that dependency entirely and surfaces any real git/`gh`
//! failure verbatim through the shared `run_all` runner rather than as a black box.

use std::path::PathBuf;
use std::time::Duration;

use crate::contract::schema::Adapter;
use crate::protocol::release::{
    BuildArtifacts, DryRunReport, PlannedCommand, PublishReceipt, VerifyOutcome,
};

use super::{
    make_receipt, run_all, AdapterError, AdapterTarget, EffectCtx, HomebrewFormula, ReleaseAdapter,
    SourceTarball,
};

/// The stable, greppable prefix of the **ownership marker** every ossctl-generated
/// formula carries as its first line. Its presence is how the *tap-write* path tells
/// an ossctl-managed formula (safe to fully regenerate) from a hand-maintained one
/// (never clobber — surgically edit `url`/`sha256` only, or refuse). The prefix
/// deliberately omits the version integer so a future `template-version` bump still
/// reads as "ossctl-managed". See [`render_formula`] (writer) and
/// [`formula_carries_marker`] (reader).
const FORMULA_MARKER_PREFIX: &str = "# Generated by ossctl; do not edit by hand (template-version:";

/// The current formula-template version, embedded in the ownership marker. Bump this
/// when the generated formula's *shape* changes in a way worth recording; the marker
/// still identifies the file as ossctl-managed regardless of the integer.
const FORMULA_TEMPLATE_VERSION: u32 = 1;

/// Whether `bytes` carry the ossctl ownership marker on their **first line** —
/// exactly where [`render_formula`] writes it. The check is deliberately anchored to
/// the first line (not a search anywhere in the file): a hand-maintained formula that
/// merely *quotes* the marker string in a comment, `desc`, `caveats`, or embedded
/// `__END__`/patch data must NOT be mistaken for ossctl output and fully regenerated
/// (that would clobber the hand-authored stanzas this whole path exists to protect).
/// Operates on bytes so a non-UTF-8 formula needs no lossy conversion; a trailing
/// `\r` (CRLF) after the marker is irrelevant to the `starts_with` prefix test. A
/// marked formula is ossctl-managed → safe to fully regenerate; an unmarked one is
/// hand-maintained → the tap-write path must not clobber it.
fn formula_carries_marker(bytes: &[u8]) -> bool {
    let first_line = match bytes.iter().position(|&b| b == b'\n') {
        Some(i) => &bytes[..i],
        None => bytes,
    };
    first_line.starts_with(FORMULA_MARKER_PREFIX.as_bytes())
}

/// The homebrew distribution adapter, operating as `homebrew-tap` or
/// `homebrew-core`.
pub struct HomebrewAdapter {
    adapter: Adapter,
}

/// Which formula operation the adapter resolved for a target.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FormulaPath {
    /// Generate + PR the initial `<name>.rb` (configured tap, no formula yet).
    Create,
    /// Render + write the updated `<name>.rb` directly to the configured tap's
    /// default branch (configured tap, formula already present) — no `brew`, no
    /// PR. See the module docs' *tap-write* path.
    TapWrite,
    /// `brew bump-formula-pr` an already-present formula — the fallback for a
    /// target with no configured tap (`homebrew-core`, or an unconfigured
    /// `homebrew-tap`), where a reviewed PR + full `brew audit` is the right path.
    BumpPr,
}

impl HomebrewAdapter {
    /// Construct for a resolved homebrew adapter identity.
    #[must_use]
    pub fn new(adapter: Adapter) -> Self {
        debug_assert!(matches!(
            adapter,
            Adapter::HomebrewTap | Adapter::HomebrewCore
        ));
        Self { adapter }
    }

    /// The destination tap slug (`owner/repo`) for a `homebrew-tap` create, when
    /// the contract configured one. `None` for `homebrew-core` or an unconfigured
    /// tap — which pins the adapter to the bump path (no bootstrap destination).
    fn tap<'a>(&self, artifacts: Option<&'a HomebrewFormula>) -> Option<&'a str> {
        if self.adapter != Adapter::HomebrewTap {
            return None;
        }
        artifacts.and_then(|h| h.tap.as_deref())
    }

    /// Decide the formula path for `target`. A `homebrew-tap` with a configured
    /// tap probes the tap for the formula: absent → [`FormulaPath::Create`],
    /// present → [`FormulaPath::TapWrite`] (direct write to the tap). Every other
    /// case (no configured tap: `homebrew-core`, or an unconfigured tap) is
    /// [`FormulaPath::BumpPr`].
    ///
    /// The probe runs through the injected runner (`gh api …/contents/…`); a
    /// non-zero exit (a `404`, typically) reads as *absent* → create. A spawn
    /// failure is a real error and is propagated.
    fn resolve_path(
        &self,
        ctx: &EffectCtx<'_>,
        t: &AdapterTarget,
    ) -> Result<FormulaPath, AdapterError> {
        let homebrew = ctx.artifacts.homebrew.as_ref();
        match self.tap(homebrew) {
            Some(tap) => {
                if Self::formula_exists(ctx, tap, &t.package)? {
                    Ok(FormulaPath::TapWrite)
                } else {
                    Ok(FormulaPath::Create)
                }
            }
            None => Ok(FormulaPath::BumpPr),
        }
    }

    /// Ask the tap whether `Formula/<name>.rb` already exists, through the runner.
    ///
    /// Uses `gh api` against the tap's contents endpoint so no local checkout is
    /// needed for the probe. Only three outcomes are safe to act on:
    ///
    /// - exit `0` (the file is served) ⇒ **present** → bump.
    /// - a genuine `404` (`gh` renders it as `Not Found (HTTP 404)`) ⇒ **absent**
    ///   → create.
    /// - **anything else** — auth failure, rate-limit, network error, a private or
    ///   renamed tap, a 5xx — is an [`AdapterError::Command`], **not** "absent".
    ///   Treating an infrastructure error as absence would trigger a spurious
    ///   create that clones the tap and could overwrite an existing formula.
    ///
    /// A spawn failure (the port could not run `gh`) is a genuine
    /// [`AdapterError::Io`].
    fn formula_exists(ctx: &EffectCtx<'_>, tap: &str, name: &str) -> Result<bool, AdapterError> {
        let endpoint = format!("repos/{tap}/contents/Formula/{name}.rb");
        let cmd = PlannedCommand::new("gh", &["api", "--silent", &endpoint]);
        let out = ctx
            .runner
            .run("gh", &["api", "--silent", &endpoint], ctx.repo_root)
            .map_err(|e| AdapterError::Io {
                command: cmd.rendered(),
                source: e.to_string(),
            })?;
        if out.status == Some(0) {
            return Ok(true);
        }
        // A 404 is the only non-zero exit that means "absent". `gh` prints
        // `Not Found (HTTP 404)`; match the stable `404` token on either stream.
        if out.stderr.contains("404") || out.stdout.contains("404") {
            return Ok(false);
        }
        let detail = if out.stderr.trim().is_empty() {
            out.stdout
        } else {
            out.stderr
        };
        Err(AdapterError::Command {
            command: cmd.rendered(),
            code: out.status,
            stderr: detail,
        })
    }

    /// The `brew bump-formula-pr` command for an existing formula, carrying the
    /// threaded release tarball `--url` (+ `--sha256` when a digest is present).
    /// Options precede the `--` terminator so a formula name is never parsed as a
    /// flag. Unchanged from the pre-bootstrap behaviour.
    fn bump_command(&self, tarball: Option<&SourceTarball>, name: &str) -> PlannedCommand {
        let mut args: Vec<String> = match self.adapter {
            Adapter::HomebrewCore => vec!["bump-formula-pr".into(), "--no-fork".into()],
            _ => vec!["bump-formula-pr".into()],
        };
        if let Some(tarball) = tarball {
            args.push("--url".into());
            args.push(tarball.url.clone());
            if let Some(sha256) = &tarball.sha256 {
                args.push("--sha256".into());
                args.push(sha256.clone());
            }
        }
        args.push("--".into());
        args.push(name.to_string());
        PlannedCommand {
            program: "brew".into(),
            args,
        }
    }

    /// A **fresh, unpredictable** scratch checkout the create path clones the tap
    /// into. Unique per attempt (pid + a monotonic-ish nanosecond stamp) so:
    /// concurrent cuts/tests never collide; a retry never trips over a prior
    /// attempt's leftover dir (the old "deterministic" path made `gh repo clone`
    /// fail into a non-empty dir); and the unpredictable name defeats the classic
    /// world-writable-`/tmp` symlink pre-creation (TOCTOU) attack. The file write
    /// additionally uses create-new semantics (see [`Self::write_formula`]).
    fn fresh_workdir(name: &str, version: &str) -> PathBuf {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_nanos());
        std::env::temp_dir().join(format!(
            "ossctl-homebrew-{name}-{version}-{}-{nanos}",
            std::process::id()
        ))
    }

    /// The branch the create path commits the new formula on.
    fn create_branch(name: &str, version: &str) -> String {
        format!("ossctl-homebrew-{name}-{version}")
    }

    /// The commit/PR title for a first formula.
    fn create_title(name: &str, version: &str) -> String {
        format!("{name} {version} (new formula)")
    }

    /// The ordered git/`gh` commands the create path runs (clone → branch → add →
    /// commit → push → PR), into the pre-computed `workdir`. The generated `.rb`
    /// is written to disk *between* the clone and the `add` (see
    /// [`Self::publish`]); these are only the process steps, shared by
    /// [`Self::dry_run`]'s preview and [`Self::publish`].
    ///
    /// `sha256_present` gates two things: a **draft** PR and a blocker in the body.
    /// When the source-tarball digest is not yet known (the coordinator threads
    /// `sha256: None` pre-tag), the generated formula carries only a `sha256`
    /// TODO and would fail `brew audit` / cannot install — so the PR is opened as a
    /// draft whose body states the one remaining manual step, rather than a
    /// mergeable-looking PR that is silently broken.
    fn create_commands(
        tap: &str,
        name: &str,
        version: &str,
        workdir: &str,
        sha256_present: bool,
    ) -> Vec<PlannedCommand> {
        let branch = Self::create_branch(name, version);
        let title = Self::create_title(name, version);
        let formula_rel = format!("Formula/{name}.rb");
        let body = if sha256_present {
            "Automated first-formula bootstrap by ossctl.".to_string()
        } else {
            "Automated first-formula bootstrap by ossctl.\n\n**Blocked:** the \
             `sha256` of the published release tarball is not yet known at cut \
             time (the tag archive does not exist until after publish). Fill in \
             the `sha256` once the tag is pushed, then mark this PR ready."
                .to_string()
        };
        let mut pr = vec![
            "pr".to_string(),
            "create".to_string(),
            "--repo".to_string(),
            tap.to_string(),
            "--head".to_string(),
            branch.clone(),
            "--title".to_string(),
            title.clone(),
            "--body".to_string(),
            body,
        ];
        if !sha256_present {
            pr.push("--draft".to_string());
        }
        vec![
            PlannedCommand::new("gh", &["repo", "clone", tap, workdir, "--", "--depth", "1"]),
            PlannedCommand::new("git", &["-C", workdir, "checkout", "-b", &branch]),
            PlannedCommand::new("git", &["-C", workdir, "add", &formula_rel]),
            // Set the commit identity explicitly (via `-c`): the freshly-cloned tap
            // inherits no `user.name`/`user.email`, so on a clean CI runner an
            // identity-less `git commit` fails with "Author identity unknown".
            // Disable `commit.gpgsign` so a machine with global signing on cannot
            // hang the automated commit waiting for a passphrase / missing GPG.
            PlannedCommand::new(
                "git",
                &[
                    "-C",
                    workdir,
                    "-c",
                    "user.name=ossctl",
                    "-c",
                    "user.email=ossctl@users.noreply.github.com",
                    "-c",
                    "commit.gpgsign=false",
                    "commit",
                    "-m",
                    &title,
                ],
            ),
            PlannedCommand::new(
                "git",
                &["-C", workdir, "push", "--set-upstream", "origin", &branch],
            ),
            PlannedCommand {
                program: "gh".to_string(),
                args: pr,
            },
        ]
    }

    /// Run the create path: generate the initial formula, clone the tap, write the
    /// file, commit it on a branch, and open a PR — all effects through the runner
    /// except the single filesystem write of the generated `.rb`.
    fn run_create(
        ctx: &EffectCtx<'_>,
        t: &AdapterTarget,
        tap: &str,
    ) -> Result<PublishReceipt, AdapterError> {
        // The package name reaches a filesystem path and a git pathspec; reject any
        // traversal/separator before it can escape the checkout or the `Formula/` dir.
        validate_package_name(&t.package)?;
        let tarball =
            ctx.artifacts
                .source_tarball
                .as_ref()
                .ok_or_else(|| AdapterError::Command {
                    command: "homebrew first-formula".into(),
                    code: None,
                    stderr: "cannot generate a first Homebrew formula without a resolvable GitHub \
                         source-tarball URL (no `origin` GitHub remote?)"
                        .into(),
                })?;
        let license = ctx
            .artifacts
            .homebrew
            .as_ref()
            .and_then(|h| h.license.as_deref());
        let homepage_slug = ctx.artifacts.repo_slug.as_deref();
        let formula = render_formula(
            &t.package,
            homepage_slug,
            &tarball.url,
            tarball.sha256.as_deref(),
            license,
        );

        // One workdir, computed once, used by both the clone and the write.
        let workdir = Self::fresh_workdir(&t.package, &t.version);
        let workdir_str = workdir.to_string_lossy().to_string();
        let commands = Self::create_commands(
            tap,
            &t.package,
            &t.version,
            &workdir_str,
            tarball.sha256.is_some(),
        );
        // 1. clone the tap.
        run_all(ctx, &commands[..1])?;
        // 2. write the generated formula into the checkout (create-new: refuses to
        //    overwrite a formula that already exists in the clone — the last-line
        //    guard against a probe/clone race or a mis-detected "absent").
        Self::write_formula(&workdir, &t.package, &formula, WriteMode::CreateNew)?;
        // 3. branch → add → commit → push → PR.
        let outputs = run_all(ctx, &commands[1..])?;

        // Record the PR URL `gh pr create` prints as the receipt's `remote_url`
        // (the field already existed — recording it is not a JSON-shape change).
        // `gh` can precede the URL with status lines, so take the last line that
        // looks like a URL rather than the whole stdout blob.
        let remote_url = outputs.last().and_then(|o| {
            o.stdout
                .lines()
                .rev()
                .map(str::trim)
                .find(|line| line.starts_with("https://"))
                .map(str::to_string)
        });
        Ok(make_receipt(ctx, t, None, remote_url))
    }

    /// The commit title for a tap-write formula update.
    fn update_title(name: &str, version: &str) -> String {
        format!("{name} {version}")
    }

    /// The ordered git/`gh` commands the *tap-write* path runs: clone → add →
    /// commit → push **to the tap's default branch** (no branch, no PR — the
    /// generated `.rb` is what `brew install` resolves). The rendered formula is
    /// overwritten onto disk *between* the clone (`commands[..1]`) and the `add`
    /// (`commands[1..]`), exactly like [`Self::create_commands`]; these are only
    /// the process steps, shared by [`Self::dry_run`]'s preview and
    /// [`Self::run_tap_write`].
    ///
    /// `git push origin HEAD` publishes the freshly-committed default branch (the
    /// clone checks the default branch out, so `HEAD` is it) — matching the manual
    /// fallback that pushed the formula straight to the tap.
    fn update_commands(tap: &str, name: &str, version: &str, workdir: &str) -> Vec<PlannedCommand> {
        let title = Self::update_title(name, version);
        let formula_rel = format!("Formula/{name}.rb");
        vec![
            PlannedCommand::new("gh", &["repo", "clone", tap, workdir, "--", "--depth", "1"]),
            PlannedCommand::new("git", &["-C", workdir, "add", &formula_rel]),
            // Set the commit identity explicitly (via `-c`): the freshly-cloned tap
            // inherits no `user.name`/`user.email`, so on a clean CI runner an
            // identity-less `git commit` fails with "Author identity unknown".
            // Disable `commit.gpgsign` so a machine with global signing on cannot
            // hang the automated commit waiting for a passphrase / missing GPG.
            PlannedCommand::new(
                "git",
                &[
                    "-C",
                    workdir,
                    "-c",
                    "user.name=ossctl",
                    "-c",
                    "user.email=ossctl@users.noreply.github.com",
                    "-c",
                    "commit.gpgsign=false",
                    "commit",
                    "-m",
                    &title,
                ],
            ),
            PlannedCommand::new("git", &["-C", workdir, "push", "origin", "HEAD"]),
        ]
    }

    /// Run the *tap-write* path: render the updated formula from the **verified**
    /// `url` + `sha256`, clone the tap, overwrite `Formula/<name>.rb`, commit, and
    /// push to the tap's default branch.
    ///
    /// **Fail-closed contract.** This path pushes to the tap's default branch — the
    /// ref `brew install <tap>/<name>` resolves — so it refuses to write a formula
    /// without a verified `sha256`: a missing tarball, an absent digest, or one that
    /// is not exactly 64 hex chars is a hard [`AdapterError::Command`], never a TODO
    /// placeholder. Unlike the create path's draft PR, there is no human review gate
    /// here, so a guessed/absent/malformed digest would ship a broken install.
    ///
    /// **Must already exist.** `resolve_path` chose this path from a `gh api` probe
    /// that reported the formula present; after cloning, this re-checks that the tap
    /// actually carries `Formula/<name>.rb` as a *regular file* before overwriting.
    /// If a probe/clone race left it absent (or it is a symlink/dir), it fails closed
    /// rather than *synthesize* a new formula straight onto the default branch — that
    /// would bypass the create path's PR review gate (and, for a symlink, clobber a
    /// file outside the checkout).
    ///
    /// **Ownership-marker safety** (issue `homebrew-tapwrite-preserve-formula`). It
    /// never blindly overwrites the existing formula. If the tap's current file
    /// carries the ossctl ownership marker (see [`render_formula`]), it *is* ossctl
    /// output and is safe to fully regenerate. If it does not (a hand-maintained
    /// formula with extra `depends_on`s, `resource`s, `caveats`, a custom `test`, …),
    /// this path performs a **surgical** edit — replacing only the single `url` and
    /// `sha256` lines via [`surgical_url_sha_edit`] and preserving everything else —
    /// and fails closed if that formula's shape cannot be edited safely, rather than
    /// clobbering hand-authored content.
    ///
    /// **Idempotent.** It compares the resulting content (regenerated or surgically
    /// edited) against the tap's current bytes; an exact match is a clean no-op
    /// success (a resume/re-run at the target version), so it neither rewrites the
    /// file nor pushes an empty commit.
    fn run_tap_write(
        ctx: &EffectCtx<'_>,
        t: &AdapterTarget,
        tap: &str,
    ) -> Result<PublishReceipt, AdapterError> {
        // The package name reaches a filesystem path and a git pathspec; reject any
        // traversal/separator before it can escape the checkout or the `Formula/` dir.
        validate_package_name(&t.package)?;
        let tarball =
            ctx.artifacts
                .source_tarball
                .as_ref()
                .ok_or_else(|| AdapterError::Command {
                    command: "homebrew formula update".into(),
                    code: None,
                    stderr: "cannot update the Homebrew formula without a resolvable GitHub \
                         source-tarball URL (no `origin` GitHub remote?)"
                        .into(),
                })?;
        let sha256 = tarball
            .sha256
            .as_deref()
            .filter(|s| is_sha256_hex(s))
            .ok_or_else(|| AdapterError::Command {
                command: "homebrew formula update".into(),
                code: None,
                stderr:
                    "refusing to push a Homebrew formula to the tap's default branch without a \
                     verified sha256 — the digest is absent or not a 64-char hex string (the tag \
                     archive was not fetched and hashed). A formula on the default branch is what \
                     `brew install` resolves, so an unverified digest would ship a broken install"
                        .into(),
            })?;
        let license = ctx
            .artifacts
            .homebrew
            .as_ref()
            .and_then(|h| h.license.as_deref());
        let homepage_slug = ctx.artifacts.repo_slug.as_deref();

        let workdir = Self::fresh_workdir(&t.package, &t.version);
        let workdir_str = workdir.to_string_lossy().to_string();
        let commands = Self::update_commands(tap, &t.package, &t.version, &workdir_str);
        // 1. clone the tap (its default branch).
        run_all(ctx, &commands[..1])?;
        // 2. the formula must already be a regular file in the clone (see the
        //    "Must already exist" contract above) — read its current bytes.
        let formula_path = workdir.join("Formula").join(format!("{}.rb", t.package));
        let current = Self::read_existing_formula(&formula_path, &t.package)?;
        // 3. ownership marker (issue `homebrew-tapwrite-preserve-formula`): only a
        //    formula ossctl itself generated (carrying the marker) is safe to fully
        //    regenerate. An unmarked, hand-maintained formula must NOT be clobbered —
        //    surgically edit only its `url`/`sha256` values (fail-closed on a shape we
        //    cannot safely parse), preserving every hand-authored stanza.
        //
        //    MIGRATION: a formula generated by the *pre-marker* renderer is unmarked,
        //    so it takes the surgical path on the first cut after this change and stays
        //    on it (the surgical edit deliberately does NOT inject the marker — doing so
        //    would silently claim ownership of a genuinely hand-maintained formula). For
        //    an ossctl-managed tap this is harmless (its formula's url/sha still update);
        //    to opt a legacy formula back into full regeneration, add the marker line by
        //    hand. A newly *created* formula always carries the marker, so this only
        //    affects formulas that predate the marker.
        let updated = if formula_carries_marker(&current) {
            render_formula(
                &t.package,
                homepage_slug,
                &tarball.url,
                Some(sha256),
                license,
            )
        } else {
            let current_str = std::str::from_utf8(&current).map_err(|_| AdapterError::Command {
                command: "homebrew formula update".into(),
                code: None,
                stderr: "refusing to edit the hand-maintained tap formula: it is not valid \
                             UTF-8, so a safe surgical `url`/`sha256` edit cannot be applied \
                             (no ossctl ownership marker present to authorise a full rewrite)"
                    .into(),
            })?;
            surgical_url_sha_edit(current_str, &tarball.url, sha256)?
        };
        // 4. idempotent no-op: the tap already carries exactly this content.
        let remote_url = Some(format!(
            "https://github.com/{tap}/blob/HEAD/Formula/{}.rb",
            t.package
        ));
        if current == updated.as_bytes() {
            return Ok(make_receipt(ctx, t, Some(sha256.to_string()), remote_url));
        }
        // 5. overwrite the existing formula, then add → commit → push.
        Self::write_formula(&workdir, &t.package, &updated, WriteMode::Overwrite)?;
        run_all(ctx, &commands[1..])?;
        Ok(make_receipt(ctx, t, Some(sha256.to_string()), remote_url))
    }

    /// Read the tap's current `Formula/<name>.rb` bytes, enforcing the tap-write
    /// invariant that it is an **already-present regular file**. A missing file (a
    /// probe/clone race) or a non-regular node (a symlink the overwrite would follow
    /// out of the checkout, or a directory) is a fail-closed [`AdapterError`] — never
    /// a silent create. Uses `symlink_metadata` so a symlink is *detected*, not
    /// traversed.
    fn read_existing_formula(path: &std::path::Path, name: &str) -> Result<Vec<u8>, AdapterError> {
        let meta = std::fs::symlink_metadata(path).map_err(|e| AdapterError::Command {
            command: "homebrew formula update".into(),
            code: None,
            stderr: format!(
                "the tap was probed as carrying `{name}.rb` but the cloned checkout does not \
                 (`{}`: {e}) — refusing to synthesize a formula on the default branch without the \
                 create-path review gate",
                path.display()
            ),
        })?;
        if !meta.file_type().is_file() {
            return Err(AdapterError::Filesystem {
                path: path.to_string_lossy().to_string(),
                source: "not a regular file (symlink or directory) — refusing to overwrite".into(),
            });
        }
        std::fs::read(path).map_err(|e| AdapterError::Filesystem {
            path: path.to_string_lossy().to_string(),
            source: e.to_string(),
        })
    }

    /// Write the generated formula to `<workdir>/Formula/<name>.rb`, creating the
    /// `Formula/` directory if the freshly-cloned tap does not carry it yet.
    ///
    /// This is the one direct-filesystem effect in the adapter — Homebrew has no
    /// "add a formula" CLI; a new formula *is* a committed file, so `run_all`
    /// (which only *runs processes*) cannot express it. It is deliberately scoped:
    /// it writes exactly one file into a private, unpredictable [`Self::fresh_workdir`]
    /// the calling path just cloned into. A general filesystem port on `EffectCtx`
    /// is the cleaner long-term home (issue `homebrew-adapter-fs-port`); until then
    /// this is mapped to a distinct [`AdapterError::Filesystem`] so the effect is
    /// explicit, not hidden.
    ///
    /// [`WriteMode`] gates the open semantics:
    /// - [`WriteMode::CreateNew`] (the create path) uses **create-new** (`O_EXCL`)
    ///   so it never follows a symlink onto, or truncates, an existing file — which
    ///   also fails loudly if the tap already carries the formula (a last-line guard
    ///   against a mis-detected "absent" formula).
    /// - [`WriteMode::Overwrite`] (the tap-write path) truncates the already-present
    ///   formula **without** `create` — the caller ([`Self::run_tap_write`]) has
    ///   already verified via [`Self::read_existing_formula`] that it is an existing
    ///   regular file, so an open failure here means it vanished under us (a race),
    ///   which is a fail-closed error rather than a silent create.
    fn write_formula(
        workdir: &std::path::Path,
        name: &str,
        formula: &str,
        mode: WriteMode,
    ) -> Result<(), AdapterError> {
        let dir = workdir.join("Formula");
        std::fs::create_dir_all(&dir).map_err(|e| AdapterError::Filesystem {
            path: dir.to_string_lossy().to_string(),
            source: e.to_string(),
        })?;
        let path = dir.join(format!("{name}.rb"));
        let mut opts = std::fs::OpenOptions::new();
        opts.write(true);
        match mode {
            WriteMode::CreateNew => {
                opts.create_new(true);
            }
            WriteMode::Overwrite => {
                opts.truncate(true);
            }
        }
        let mut file = opts.open(&path).map_err(|e| AdapterError::Filesystem {
            path: path.to_string_lossy().to_string(),
            source: e.to_string(),
        })?;
        std::io::Write::write_all(&mut file, formula.as_bytes()).map_err(|e| {
            AdapterError::Filesystem {
                path: path.to_string_lossy().to_string(),
                source: e.to_string(),
            }
        })
    }
}

/// How [`HomebrewAdapter::write_formula`] opens the target `.rb`: create-new
/// (`O_EXCL`, the first-formula create) or truncate-an-existing-file (the tap-write
/// bump, whose caller has already proven the file is a present regular file).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WriteMode {
    /// Refuse to open an existing file (`O_EXCL`) — the create path's guard.
    CreateNew,
    /// Truncate an existing file; **no** `create`, so a vanished file is an error,
    /// not a silent create — the tap-write path replacing an existing formula.
    Overwrite,
}

impl ReleaseAdapter for HomebrewAdapter {
    fn adapter(&self) -> Adapter {
        self.adapter
    }

    fn dry_run(
        &self,
        ctx: &EffectCtx<'_>,
        t: &AdapterTarget,
    ) -> Result<DryRunReport, AdapterError> {
        let tarball = ctx.artifacts.source_tarball.as_ref();
        let path = self.resolve_path(ctx, t)?;
        let (planned_commands, mut notes) = match path {
            FormulaPath::Create => {
                // `tap` is Some whenever resolve_path returned Create.
                let tap = self
                    .tap(ctx.artifacts.homebrew.as_ref())
                    .unwrap_or_default();
                let workdir = Self::fresh_workdir(&t.package, &t.version);
                let sha256_present = tarball.and_then(|tb| tb.sha256.as_deref()).is_some();
                (
                    Self::create_commands(
                        tap,
                        &t.package,
                        &t.version,
                        &workdir.to_string_lossy(),
                        sha256_present,
                    ),
                    vec![format!(
                        "create path: `{}` has no `{}.rb` yet — generating the initial \
                         source-build formula and opening a{} PR",
                        tap,
                        t.package,
                        if sha256_present { "" } else { " draft" }
                    )],
                )
            }
            FormulaPath::TapWrite => {
                // `tap` is Some whenever resolve_path returned TapWrite.
                let tap = self
                    .tap(ctx.artifacts.homebrew.as_ref())
                    .unwrap_or_default();
                let workdir = Self::fresh_workdir(&t.package, &t.version);
                let mut notes = vec![format!(
                    "tap-write path: `{}` already serves `{}.rb` — rendering the updated \
                     formula and pushing it directly to the tap's default branch (no \
                     `brew`, no PR)",
                    tap, t.package,
                )];
                // Surface the fail-closed requirement rather than let publish fail
                // late: this path refuses to push without a verified 64-hex sha256,
                // which the coordinator threads only in the post-tag dist phase.
                if tarball.and_then(|tb| tb.sha256.as_deref()).is_none() {
                    notes.push(
                        "publish will require a verified post-tag sha256 (absent in this \
                         pre-tag preview); the coordinator supplies it after the tag is pushed"
                            .to_string(),
                    );
                }
                (
                    Self::update_commands(tap, &t.package, &t.version, &workdir.to_string_lossy()),
                    notes,
                )
            }
            FormulaPath::BumpPr => (
                vec![self.bump_command(tarball, &t.package)],
                vec![
                    "bump-PR path: no configured tap — `brew bump-formula-pr` opens a reviewed PR"
                        .to_string(),
                ],
            ),
        };
        match tarball {
            Some(tb) => {
                // The bump-PR path lets `brew` derive the digest from `--url`; the
                // create / tap-write paths get a verified digest threaded post-tag.
                let sha = tb.sha256.as_deref().unwrap_or({
                    if path == FormulaPath::BumpPr {
                        "(computed by brew from --url)"
                    } else {
                        "(resolved and verified by the coordinator post-tag)"
                    }
                });
                notes.push(format!("url: {} ; sha256: {sha}", tb.url));
            }
            None => notes
                .push("source tarball url is resolved by the coordinator at cut time".to_string()),
        }
        Ok(DryRunReport {
            adapter: self.adapter,
            planned_commands,
            notes,
        })
    }

    fn build(
        &self,
        _ctx: &EffectCtx<'_>,
        _t: &AdapterTarget,
    ) -> Result<BuildArtifacts, AdapterError> {
        // Homebrew has no build phase of its own — it repackages an existing
        // release artifact. Return an empty manifest rather than shelling out.
        Ok(BuildArtifacts {
            adapter: self.adapter,
            artifacts: vec![],
            notes: vec!["homebrew has no build phase (formula create/update only)".to_string()],
        })
    }

    fn publish(
        &self,
        ctx: &EffectCtx<'_>,
        t: &AdapterTarget,
    ) -> Result<PublishReceipt, AdapterError> {
        // PER-TARGET IRREVERSIBLE (pushes a formula to the tap, or opens a PR).
        match self.resolve_path(ctx, t)? {
            FormulaPath::Create => {
                let tap = self
                    .tap(ctx.artifacts.homebrew.as_ref())
                    .expect("resolve_path returns Create only when a tap is configured");
                Self::run_create(ctx, t, tap)
            }
            FormulaPath::TapWrite => {
                let tap = self
                    .tap(ctx.artifacts.homebrew.as_ref())
                    .expect("resolve_path returns TapWrite only when a tap is configured");
                Self::run_tap_write(ctx, t, tap)
            }
            FormulaPath::BumpPr => {
                let cmd = self.bump_command(ctx.artifacts.source_tarball.as_ref(), &t.package);
                run_all(ctx, &[cmd])?;
                Ok(make_receipt(ctx, t, None, None))
            }
        }
    }

    fn verify(
        &self,
        _ctx: &EffectCtx<'_>,
        _receipt: &PublishReceipt,
    ) -> Result<VerifyOutcome, AdapterError> {
        // A tap/core formula is not observable through RegistryQuery; report the
        // honest "cannot check" rather than a false Missing (ADR-0002 §1).
        Ok(VerifyOutcome::Unknown)
    }

    fn timeout(&self) -> Duration {
        Duration::from_secs(600)
    }
}

/// Render a source-build Homebrew formula for `name` at `url`.
///
/// Produces the same shape as ossctl's own hand-written 0.1.0 formula: a cargo
/// source build (`depends_on "rust" => :build` + `cargo install`). The install
/// stanza is deliberately Rust-specific — the two consumers (`ossctl`,
/// `issuectl`) are cargo CLIs, and the issue this implements reproduces that
/// formula; a non-Rust source build is a documented follow-up.
///
/// `sha256`/`license` are optional: an absent `sha256` (the coordinator cannot
/// hash the pushed tag archive before it exists — see the coordinator's
/// `source_tarball` docs) emits a `TODO` placeholder the maintainer completes,
/// mirroring the 0.1.0 hand-fill; an absent `license` omits the stanza.
///
/// Every generated formula opens with the [`FORMULA_MARKER_PREFIX`] ownership
/// marker as its first line, so a later tap-write can recognise its own output and
/// fully regenerate it — while refusing to clobber a hand-maintained (unmarked)
/// formula.
///
/// `pub(super)` so the adapter tests can compute the exact expected bytes when
/// seeding a fake tap clone (the tap-write idempotency no-op is a byte-compare).
pub(super) fn render_formula(
    name: &str,
    homepage_slug: Option<&str>,
    url: &str,
    sha256: Option<&str>,
    license: Option<&str>,
) -> String {
    let class = formula_class(name);
    // Every value interpolated into a Ruby double-quoted literal is escaped, so a
    // `"` / `\` in a contract-supplied value cannot break out of the string (or
    // inject Ruby). `name` reaches only `desc` and the `bin/"…"` test — the class
    // name is already alphanumeric-only.
    let name_lit = ruby_escape(name);
    let homepage = homepage_slug.map_or_else(
        || ruby_escape(url),
        |s| ruby_escape(&format!("https://github.com/{s}")),
    );
    let url_lit = ruby_escape(url);
    let sha_line = match sha256 {
        Some(sha) => format!("  sha256 \"{}\"", ruby_escape(sha)),
        None => "  # TODO: sha256 of the published release tarball \
                 (unavailable at cut time — fill in after the tag archive exists)"
            .to_string(),
    };
    let license_line = license
        .map(|l| format!("  license \"{}\"\n", ruby_escape(l)))
        .unwrap_or_default();
    let marker = format!("{FORMULA_MARKER_PREFIX} {FORMULA_TEMPLATE_VERSION})");
    format!(
        "{marker}\n\
         class {class} < Formula\n\
         \x20 desc \"{name_lit}\"\n\
         \x20 homepage \"{homepage}\"\n\
         \x20 url \"{url_lit}\"\n\
         {sha_line}\n\
         {license_line}\
         \n\
         \x20 depends_on \"rust\" => :build\n\
         \n\
         \x20 def install\n\
         \x20   system \"cargo\", \"install\", *std_cargo_args\n\
         \x20 end\n\
         \n\
         \x20 test do\n\
         \x20   system bin/\"{name_lit}\", \"--version\"\n\
         \x20 end\n\
         end\n"
    )
}

/// Escape a value for inclusion in a Ruby double-quoted string literal:
/// backslashes first, then double quotes, then `#`. Prevents a contract-supplied
/// `"` or `\` from terminating the literal, and — critically — escaping `#` closes
/// Ruby's `#{…}` string **interpolation**, which would otherwise evaluate arbitrary
/// Ruby (code execution when `brew` loads the formula) from a value like
/// `#{system('…')}`. `\#` renders as a literal `#`, so escaping every `#` is safe.
fn ruby_escape(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('#', "\\#")
}

/// Surgically update **only** the double-quoted value of the single `url "…"` and
/// `sha256 "…"` stanzas of a hand-maintained (unmarked) formula, preserving every
/// other byte verbatim — `depends_on`s, `resource` blocks, `caveats`, `service`,
/// custom `test`, comments, blank lines, the file's indentation, any trailing
/// stanza options (`url "…", using: :git`, `sha256 "…" => :arm64`), inline `#`
/// comments, and the original line endings (LF or CRLF).
///
/// **Only the quoted value is rewritten, in place** (not the whole line): the bytes
/// before the opening quote (indent + keyword + spacing) and everything after the
/// closing quote are copied through untouched. This is what keeps trailing options,
/// comments, and a CRLF `\r` intact, so an already-current formula stays a
/// byte-for-byte no-op.
///
/// **Fail-closed.** The tap-write path pushes straight to the tap's default branch,
/// so this refuses to guess. A stanza matches only Homebrew's canonical
/// `<indent><keyword> "<value>"` shape (keyword as a whole token, its argument the
/// immediately-following double-quoted literal); anything else — `url = x`,
/// `url(...)`, a parenthesized/heredoc form — simply does not match. It then requires
/// **exactly one** `url` line and **exactly one** `sha256` line, and every matched
/// literal to be properly closed. Zero matches (no editable stanza), multiple matches
/// (a `resource` block's own pair, an arch-conditional bottle/`sha256` set), or an
/// unterminated literal (a continuation line) is a hard [`AdapterError`] — never a
/// partial or ambiguous rewrite. The interpolated `url`/`sha256` are [`ruby_escape`]d
/// exactly as the full renderer escapes them.
fn surgical_url_sha_edit(current: &str, url: &str, sha256: &str) -> Result<String, AdapterError> {
    // A canonical stanza line: `<indent><keyword> "<value>"…` — the keyword is a
    // whole token (whitespace follows it, so `url` never matches `urls`/`url_x`), and
    // its argument is the immediately-following double-quoted literal (so `url = x`
    // and `url(...)` do not match and are left for the fail-closed hit-count guard).
    fn is_stanza_line(line: &str, keyword: &str) -> bool {
        let trimmed = line.trim_start();
        let Some(rest) = trimmed.strip_prefix(keyword) else {
            return false;
        };
        rest.starts_with(|c: char| c.is_ascii_whitespace()) && rest.trim_start().starts_with('"')
    }

    // Replace the contents of the first double-quoted literal on `line` with
    // `new_value` (ruby-escaped), preserving the prefix (indent + keyword + spacing)
    // and the entire suffix after the closing quote (trailing options, `# comments`,
    // and the CRLF `\r`). Returns `None` if the literal is not closed (a malformed or
    // continuation line) so the caller can fail closed. The closing quote is the next
    // un-escaped `"`; `"`/`\` are ASCII, so byte scanning never splits a UTF-8 char.
    fn rewrite_quoted_value(line: &str, new_value: &str) -> Option<String> {
        let open = line.find('"')?;
        let after = &line[open + 1..];
        let bytes = after.as_bytes();
        let mut i = 0;
        let close = loop {
            match bytes.get(i)? {
                b'\\' => i += 2, // skip the escaped char (a trailing `\` runs off → None)
                b'"' => break i,
                _ => i += 1,
            }
        };
        let prefix = &line[..open];
        let suffix = &after[close + 1..];
        Some(format!("{prefix}\"{}\"{suffix}", ruby_escape(new_value)))
    }

    let mut url_hits = 0usize;
    let mut sha_hits = 0usize;
    let mut malformed = false;
    // Preserve the input's exact line structure — indentation, blank lines, a
    // trailing newline (a final empty segment rejoins to reproduce it), and each
    // line's own `\r` — by splitting on '\n' and writing back with '\n'.
    let mut rebuilt = String::with_capacity(current.len() + 64);
    for (idx, line) in current.split('\n').enumerate() {
        if idx > 0 {
            rebuilt.push('\n');
        }
        let (hits, new_value) = if is_stanza_line(line, "url") {
            (Some(&mut url_hits), url)
        } else if is_stanza_line(line, "sha256") {
            (Some(&mut sha_hits), sha256)
        } else {
            (None, "")
        };
        if let Some(counter) = hits {
            *counter += 1;
            if let Some(rewritten) = rewrite_quoted_value(line, new_value) {
                rebuilt.push_str(&rewritten);
            } else {
                malformed = true;
                rebuilt.push_str(line);
            }
        } else {
            rebuilt.push_str(line);
        }
    }

    if url_hits != 1 || sha_hits != 1 || malformed {
        return Err(AdapterError::Command {
            command: "homebrew formula update".into(),
            code: None,
            stderr: format!(
                "refusing to update the hand-maintained tap formula: it carries no ossctl \
                 ownership marker, and a safe surgical `url`/`sha256` edit needs exactly one \
                 canonical `url \"\"` line and one `sha256 \"\"` line with a properly closed \
                 literal, but found {url_hits} `url` and {sha_hits} `sha256`{} — update the \
                 formula by hand, or add the ossctl marker \
                 (`{FORMULA_MARKER_PREFIX} {FORMULA_TEMPLATE_VERSION})`) as the first line to \
                 opt into full regeneration",
                if malformed {
                    " (a matched stanza's quoted value was not closed on its line)"
                } else {
                    ""
                }
            ),
        });
    }
    Ok(rebuilt)
}

/// Whether `s` is a syntactically valid SHA-256 digest: exactly 64 ASCII hex
/// characters. The tap-write fail-closed check rejects an absent OR malformed digest
/// (`Some("")`, `Some("garbage")`, a wrong length) — `Some(_)` alone is not proof of
/// a verified hash.
fn is_sha256_hex(s: &str) -> bool {
    s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())
}

/// Reject a package name that could escape the `Formula/` directory or the git
/// pathspec when interpolated into `Formula/<name>.rb` / `<name>.rb` — an empty
/// name, a path separator (`/`, `\`), a `..` traversal component, or a leading `.`.
/// The name is otherwise trusted (it reaches `desc`/`bin` via [`ruby_escape`]); this
/// guards only the filesystem/path uses.
fn validate_package_name(name: &str) -> Result<(), AdapterError> {
    let bad = name.is_empty()
        || name.starts_with('.')
        || name.contains('/')
        || name.contains('\\')
        || name.split(['/', '\\']).any(|seg| seg == "..");
    if bad {
        return Err(AdapterError::Filesystem {
            path: name.to_string(),
            source: "invalid Homebrew package name — must not be empty, start with `.`, or \
                     contain a path separator or `..` traversal component"
                .into(),
        });
    }
    Ok(())
}

/// Homebrew's formula class name for `name`: alphanumeric runs capitalised and
/// concatenated (`my-tool` → `MyTool`, `ossctl` → `Ossctl`). A small, faithful
/// subset of Homebrew's `Formulary.class_s` — enough for the ordinary tap names
/// this generator targets.
///
/// A Ruby constant may not begin with a digit, so a leading-digit name is
/// prefixed with `X` (as Homebrew itself does: `2fa` → `X2fa`); a name that
/// reduces to nothing falls back to `Formula` so the output is always a legal
/// constant rather than a syntax error.
fn formula_class(name: &str) -> String {
    let mut out = String::new();
    for segment in name.split(|c: char| !c.is_ascii_alphanumeric()) {
        let mut chars = segment.chars();
        if let Some(first) = chars.next() {
            out.extend(first.to_uppercase());
            out.push_str(chars.as_str());
        }
    }
    if out.is_empty() {
        return "Formula".to_string();
    }
    if out.starts_with(|c: char| c.is_ascii_digit()) {
        out.insert(0, 'X');
    }
    out
}