Skip to main content

caboodle/
package.rs

1// Compatibility: retained library imports, persisted paths, environment keys and
2// explicit old-command/version probes remain readable during the product rename.
3//! Package-manager receipts for stack tools (aegis-6f1).
4//!
5//! On a host whose stack is delivered by a package manager, that manager is
6//! the only writer. On apt hosts that is the root unattended-upgrades lane;
7//! automated Tambo runs never call apt or sudo. Tambo still has to judge
8//! such a tool, so it reads the package receipt (the package that owns the
9//! binary PATH runs, and its version) and compares the upstream version with
10//! the reviewed pin: current, ahead (never downgraded) or behind (the package
11//! lane will deliver it).
12
13use std::{env, process::Command};
14
15use crate::model::ToolName;
16
17/// What the package manager says about a tool's binary.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Receipt {
20    pub manager: &'static str,
21    pub package: String,
22    /// The upstream version, with any Debian epoch and revision removed.
23    pub version: String,
24}
25
26/// `[epoch:]upstream[-revision]` -> `upstream`. The stack's packages use no
27/// epoch and either no revision or a packaging-only one (quipu 0.13.0-2 adds
28/// its qp link), so the upstream part is what the reviewed pin names.
29#[must_use]
30pub fn upstream_version(debian: &str) -> &str {
31    let without_epoch = debian.split_once(':').map_or(debian, |(_, rest)| rest);
32    without_epoch
33        .rsplit_once('-')
34        .map_or(without_epoch, |(upstream, _)| upstream)
35}
36
37/// The program whose owner decides who manages `tool`, if it has a binary.
38#[must_use]
39pub fn primary_program(tool: ToolName) -> Option<String> {
40    match tool {
41        ToolName::Quipu => Some("quipu".into()),
42        ToolName::Bobbin => Some("bobbin".into()),
43        ToolName::Yupana => Some("yupana".into()),
44        ToolName::DesirePath => Some("dp".into()),
45        ToolName::Camayoc => None,
46        ToolName::Member(name) => {
47            crate::members::get(name).and_then(|m| m.programs.first().map(|p| p.name.clone()))
48        }
49    }
50}
51
52/// The apt receipt for the `program` PATH runs, when dpkg owns it.
53#[must_use]
54pub fn apt_receipt(program: &str) -> Option<Receipt> {
55    let path = crate::adapter::which_all(program, env::var_os("PATH").as_deref())
56        .into_iter()
57        .next()?;
58    let package = crate::apt_owned::owner(&path)?;
59    let query = env::var_os("CABOODLE_DPKG_QUERY").unwrap_or_else(|| "dpkg-query".into());
60    let out = Command::new(query)
61        .args(["-W", "-f", "${Version}", &package])
62        .output()
63        .ok()?;
64    if !out.status.success() {
65        return None;
66    }
67    let raw = String::from_utf8_lossy(&out.stdout).trim().to_owned();
68    if raw.is_empty() {
69        return None;
70    }
71    Some(Receipt {
72        manager: "apt",
73        version: upstream_version(&raw).to_owned(),
74        package,
75    })
76}
77
78/// The Homebrew tap that publishes the stack (aegis-em2). A formula installed
79/// from any other tap is package-owned but never driven by Tambo.
80pub const STACK_TAP: &str = "scbrown/tap";
81
82/// The stack formula for a member tool. caboodle-self is NOT here: on the Mac
83/// its installer lane owns it until the Tambo cutover (aegis-6f1 (a)).
84#[must_use]
85pub fn brew_formula(tool: ToolName) -> Option<&'static str> {
86    match tool {
87        ToolName::Bobbin => Some("bobbin"),
88        ToolName::DesirePath => Some("desire-path"),
89        ToolName::Quipu => Some("quipu"),
90        ToolName::Yupana => Some("yupana"),
91        ToolName::Member("seeds") => Some("seeds"),
92        // Chaski needs Python >= 3.11; its formula owns a python@3.12, which a
93        // release-fallback wheel on macOS's /usr/bin/python3 (3.9) cannot (aegis-o7n).
94        ToolName::Member("chaski") => Some("chaski"),
95        _ => None,
96    }
97}
98
99/// The brew executable, only where Tambo may drive it: macOS by default,
100/// or any host that names one explicitly in CABOODLE_BREW (tests use a fake).
101#[must_use]
102pub fn brew_program() -> Option<std::ffi::OsString> {
103    if let Some(explicit) = env::var_os("CABOODLE_BREW") {
104        return Some(explicit);
105    }
106    cfg!(target_os = "macos").then(|| "brew".into())
107}
108
109/// `brew info --json=v2 <tap>/<formula>`: the installed version, and only when
110/// the formula really comes from the stack tap.
111///
112/// NOT `--installed` (aegis-fv4, measured on the Mac 2026-10-16): with that
113/// flag brew ignores the formula argument and lists EVERY installed formula, so
114/// the first entry was an unrelated `homebrew/core` package and no stack member
115/// could ever produce a receipt ("brew receipt after install" on every run).
116fn brew_info(brew: &std::ffi::OsStr, formula: &str) -> Option<String> {
117    let out = Command::new(brew)
118        .args(["info", "--json=v2", &format!("{STACK_TAP}/{formula}")])
119        .output()
120        .ok()?;
121    if !out.status.success() {
122        return None;
123    }
124    installed_version(&out.stdout, formula)
125}
126
127/// The installed version of exactly `<STACK_TAP>/<formula>` in brew's v2 JSON.
128/// Selects the entry by full name rather than position, so extra or reordered
129/// entries can never stand in for the member.
130fn installed_version(json: &[u8], formula: &str) -> Option<String> {
131    let info: serde_json::Value = serde_json::from_slice(json).ok()?;
132    let wanted = format!("{STACK_TAP}/{formula}");
133    let entry =
134        info.get("formulae")?.as_array()?.iter().find(|entry| {
135            entry.get("full_name").and_then(|v| v.as_str()) == Some(wanted.as_str())
136        })?;
137    if entry.get("tap")?.as_str()? != STACK_TAP {
138        return None;
139    }
140    let version = entry
141        .get("installed")?
142        .as_array()?
143        .first()?
144        .get("version")?
145        .as_str()?;
146    // Homebrew marks rebuilds as `<version>_<n>`; the pin names the upstream.
147    Some(version.split('_').next()?.to_owned())
148}
149
150/// The brew receipt for a member tool installed from the stack tap.
151#[must_use]
152pub fn brew_receipt(tool: ToolName) -> Option<Receipt> {
153    let formula = brew_formula(tool)?;
154    let version = brew_info(&brew_program()?, formula)?;
155    Some(Receipt {
156        manager: "brew",
157        package: format!("{STACK_TAP}/{formula}"),
158        version,
159    })
160}
161
162/// The tap's current stable version for a member, when brew can read it.
163#[must_use]
164pub fn brew_available(tool: ToolName) -> Option<String> {
165    let formula = brew_formula(tool)?;
166    let out = Command::new(brew_program()?)
167        .args(["info", "--json=v2", &format!("{STACK_TAP}/{formula}")])
168        .output()
169        .ok()?;
170    if !out.status.success() {
171        return None;
172    }
173    let info: serde_json::Value = serde_json::from_slice(&out.stdout).ok()?;
174    let entry = info.get("formulae")?.as_array()?.first()?;
175    if entry.get("tap")?.as_str()? != STACK_TAP {
176        return None;
177    }
178    Some(entry.get("versions")?.get("stable")?.as_str()?.to_owned())
179}
180
181/// Current stable channel and pin selected by Homebrew for one stack formula.
182#[derive(Debug, PartialEq, Eq)]
183pub struct BrewChannel {
184    pub installed: Option<String>,
185    pub stable: String,
186    pub pinned: bool,
187    /// Brew reported `linked_keg: null` for an installed keg: it is off PATH.
188    /// A missing key (older brew, fixtures) is not read as unlinked.
189    pub unlinked: bool,
190}
191
192fn channel_from_json(bytes: &[u8], formula: &str) -> anyhow::Result<Option<BrewChannel>> {
193    use anyhow::Context;
194    let info: serde_json::Value = serde_json::from_slice(bytes).context("brew channel JSON")?;
195    let wanted = format!("{STACK_TAP}/{formula}");
196    let entries = info
197        .get("formulae")
198        .and_then(serde_json::Value::as_array)
199        .context("brew channel formula list")?;
200    let Some(entry) = entries.iter().find(|entry| {
201        entry.get("full_name").and_then(serde_json::Value::as_str) == Some(wanted.as_str())
202            && entry.get("tap").and_then(serde_json::Value::as_str) == Some(STACK_TAP)
203    }) else {
204        return Ok(None);
205    };
206    let stable = entry
207        .get("versions")
208        .and_then(|v| v.get("stable"))
209        .and_then(serde_json::Value::as_str)
210        .filter(|v| !v.is_empty())
211        .context("brew stable channel version")?
212        .to_owned();
213    let pinned = entry
214        .get("pinned")
215        .and_then(serde_json::Value::as_bool)
216        .context("brew formula pin status")?;
217    let installed = entry
218        .get("installed")
219        .and_then(serde_json::Value::as_array)
220        .context("brew installed receipt list")?
221        .first()
222        .map(|receipt| {
223            receipt
224                .get("version")
225                .and_then(serde_json::Value::as_str)
226                .filter(|v| !v.is_empty())
227                .map(|v| v.split('_').next().unwrap_or(v).to_owned())
228                .context("brew installed version")
229        })
230        .transpose()?;
231    let unlinked = installed.is_some()
232        && entry
233            .get("linked_keg")
234            .is_some_and(serde_json::Value::is_null);
235    Ok(Some(BrewChannel {
236        installed,
237        stable,
238        pinned,
239        unlinked,
240    }))
241}
242
243/// Refresh once per selected update, before judging installed versions. An
244/// unreadable/stale channel must not be silently reported as converged.
245pub fn brew_refresh() -> anyhow::Result<()> {
246    let brew = brew_program().ok_or_else(|| anyhow::anyhow!("brew is not available"))?;
247    match crate::brew_bound::run(
248        &brew,
249        ["update", "--quiet"],
250        crate::brew_bound::Output::Inherit,
251        crate::brew_bound::Bound::Step,
252    )? {
253        Ok(done) if done.status.success() => Ok(()),
254        Ok(done) => anyhow::bail!("brew update failed ({})", done.status),
255        Err(timed_out) => anyhow::bail!("brew update {timed_out}"),
256    }
257}
258
259pub fn brew_channel(tool: ToolName) -> anyhow::Result<Option<BrewChannel>> {
260    let Some(formula) = brew_formula(tool) else {
261        return Ok(None);
262    };
263    let brew = brew_program().ok_or_else(|| anyhow::anyhow!("brew is not available"))?;
264    let out = match crate::brew_bound::run(
265        &brew,
266        ["info", "--json=v2", &format!("{STACK_TAP}/{formula}")],
267        crate::brew_bound::Output::Capture,
268        crate::brew_bound::Bound::Step,
269    )? {
270        Ok(done) => done,
271        Err(timed_out) => anyhow::bail!("brew channel read for {formula} {timed_out}"),
272    };
273    if !out.status.success() {
274        anyhow::bail!("brew channel read failed for {formula} ({})", out.status);
275    }
276    channel_from_json(&out.stdout, formula)
277}
278
279/// Install or upgrade a member from the stack tap. Brew runs as the user (no
280/// root), so Tambo drives it directly (aegis-6f1 ruling).
281///
282/// The step is bounded (aegis-f0ne). When it fails or times out, the keg brew
283/// had already unlinked is linked again, so the previous version stays on PATH,
284/// and the error names the member. Its first line is
285/// `<tool> brew delivery timed out after <N>s ...`, which the Mac consumer
286/// reports as a member timeout.
287pub fn brew_converge(tool: ToolName, upgrade: bool) -> anyhow::Result<()> {
288    let formula = brew_formula(tool).ok_or_else(|| anyhow::anyhow!("no stack formula"))?;
289    let brew = brew_program().ok_or_else(|| anyhow::anyhow!("brew is not available"))?;
290    let verb = if upgrade { "upgrade" } else { "install" };
291    let full = format!("{STACK_TAP}/{formula}");
292    match crate::brew_bound::run(
293        &brew,
294        [verb, full.as_str()],
295        crate::brew_bound::Output::Inherit,
296        crate::brew_bound::Bound::Step,
297    )? {
298        Ok(done) if done.status.success() => Ok(()),
299        Ok(done) => {
300            let link = restore_link(&brew, formula);
301            anyhow::bail!("brew {verb} {full} failed ({}); {link}", done.status)
302        }
303        Err(timed_out) => {
304            let link = restore_link(&brew, formula);
305            anyhow::bail!(
306                "{} brew delivery {timed_out} during `brew {verb} {full}`; {link}",
307                tool.as_str()
308            )
309        }
310    }
311}
312
313/// Link the installed keg again if an interrupted brew step left it unlinked.
314/// Returns what it found and did, for the error message.
315fn restore_link(brew: &std::ffi::OsStr, formula: &str) -> String {
316    match restore_link_with(brew, formula) {
317        Ok(text) | Err(text) => text,
318    }
319}
320
321/// Link `tool`'s installed keg when brew reports it unlinked (aegis-f0ne):
322/// an earlier interrupted step leaves the keg installed but off PATH, and a
323/// later `brew upgrade` preserves that state. `Ok` says what was done; `Err`
324/// says why the keg is still not linked, so the caller can fail the member
325/// with that text rather than reach an opaque verify error (eph-review-07aef5).
326pub fn brew_relink(tool: ToolName) -> Result<String, String> {
327    match (brew_formula(tool), brew_program()) {
328        (Some(formula), Some(brew)) => restore_link_with(&brew, formula),
329        _ => Err("no stack formula or brew".into()),
330    }
331}
332
333fn restore_link_with(brew: &std::ffi::OsStr, formula: &str) -> Result<String, String> {
334    let full = format!("{STACK_TAP}/{formula}");
335    let read = || -> Option<(Option<String>, Option<String>)> {
336        let done = crate::brew_bound::run(
337            brew,
338            ["info", "--json=v2", full.as_str()],
339            crate::brew_bound::Output::Capture,
340            crate::brew_bound::Bound::Repair,
341        )
342        .ok()?
343        .ok()?;
344        done.status.success().then_some(())?;
345        link_state(&done.stdout, formula)
346    };
347    let Some((installed, linked)) = read() else {
348        return Err(format!(
349            "keg link state for {full} is UNKNOWN (brew info unreadable)"
350        ));
351    };
352    let Some(installed) = installed else {
353        return Err(format!("no {full} keg is installed"));
354    };
355    if let Some(linked) = linked {
356        return Ok(format!("keg {linked} is still linked"));
357    }
358    match crate::brew_bound::run(
359        brew,
360        ["link", full.as_str()],
361        crate::brew_bound::Output::Inherit,
362        crate::brew_bound::Bound::Repair,
363    ) {
364        Ok(Ok(done)) if done.status.success() => match read() {
365            Some((_, Some(linked))) => Ok(format!("relinked keg {linked}")),
366            _ => Err(format!(
367                "`brew link {full}` ran but keg {installed} is still NOT linked"
368            )),
369        },
370        Ok(Ok(done)) => Err(format!(
371            "keg {installed} is NOT linked; `brew link {full}` failed ({})",
372            done.status
373        )),
374        Ok(Err(timed_out)) => Err(format!(
375            "keg {installed} is NOT linked; `brew link {full}` {timed_out}"
376        )),
377        Err(error) => Err(format!(
378            "keg {installed} is NOT linked; `brew link {full}`: {error}"
379        )),
380    }
381}
382
383/// The installed and linked versions of exactly `<STACK_TAP>/<formula>`.
384fn link_state(json: &[u8], formula: &str) -> Option<(Option<String>, Option<String>)> {
385    let info: serde_json::Value = serde_json::from_slice(json).ok()?;
386    let wanted = format!("{STACK_TAP}/{formula}");
387    let entry = info.get("formulae")?.as_array()?.iter().find(|entry| {
388        entry.get("full_name").and_then(serde_json::Value::as_str) == Some(wanted.as_str())
389    })?;
390    let installed = entry
391        .get("installed")?
392        .as_array()?
393        .first()
394        .and_then(|receipt| receipt.get("version")?.as_str())
395        .map(str::to_owned);
396    let linked = entry
397        .get("linked_keg")
398        .and_then(serde_json::Value::as_str)
399        .map(str::to_owned);
400    Some((installed, linked))
401}
402
403/// How a package-owned tool stands against its reviewed pin.
404#[derive(Debug, PartialEq, Eq)]
405pub enum Standing {
406    Current,
407    Ahead,
408    Behind,
409    /// One of the versions has no comparable semantic version.
410    Unknown,
411}
412
413#[must_use]
414pub fn standing(receipt_version: &str, desired: &str) -> Standing {
415    let installed = format!("pkg {receipt_version}");
416    match (
417        crate::release_update::behind_reviewed(&installed, desired),
418        crate::release_update::behind_reviewed(desired, &installed),
419    ) {
420        (Some(true), _) => Standing::Behind,
421        (Some(false), Some(true)) => Standing::Ahead,
422        (Some(false), Some(false)) => Standing::Current,
423        _ => Standing::Unknown,
424    }
425}
426
427#[cfg(test)]
428mod tests {
429    use super::installed_version;
430
431    fn entry(full_name: &str, tap: &str, installed: &[&str]) -> serde_json::Value {
432        serde_json::json!({
433            "full_name": full_name,
434            "tap": tap,
435            "installed": installed.iter().map(|v| serde_json::json!({"version": v})).collect::<Vec<_>>(),
436        })
437    }
438
439    fn info(entries: Vec<serde_json::Value>) -> Vec<u8> {
440        serde_json::to_vec(&serde_json::json!({"formulae": entries, "casks": []})).unwrap()
441    }
442
443    #[test]
444    fn receipt_reads_the_named_member_not_the_first_installed_formula() {
445        // aegis-fv4: `--installed` made brew list every formula; abseil came first.
446        let listing = info(vec![
447            entry("abseil", "homebrew/core", &["20250814.1"]),
448            entry("scbrown/tap/quipu", "scbrown/tap", &["0.14.1"]),
449        ]);
450        assert_eq!(
451            installed_version(&listing, "quipu").as_deref(),
452            Some("0.14.1")
453        );
454        assert_eq!(installed_version(&listing, "bobbin"), None);
455    }
456
457    #[test]
458    fn receipt_refuses_uninstalled_foreign_tap_and_malformed_answers() {
459        assert_eq!(
460            installed_version(
461                &info(vec![entry("scbrown/tap/bobbin", "scbrown/tap", &[])]),
462                "bobbin"
463            ),
464            None
465        );
466        assert_eq!(
467            installed_version(
468                &info(vec![entry("scbrown/tap/bobbin", "other/tap", &["1.0.0"])]),
469                "bobbin"
470            ),
471            None
472        );
473        assert_eq!(installed_version(b"not json", "bobbin"), None);
474        assert_eq!(
475            installed_version(
476                &info(vec![entry(
477                    "scbrown/tap/yupana",
478                    "scbrown/tap",
479                    &["0.13.0_1"]
480                )]),
481                "yupana"
482            )
483            .as_deref(),
484            Some("0.13.0")
485        );
486    }
487
488    use super::*;
489
490    #[test]
491    fn debian_revision_and_epoch_are_not_part_of_the_pinned_version() {
492        assert_eq!(upstream_version("0.13.0"), "0.13.0");
493        assert_eq!(upstream_version("0.13.0-2"), "0.13.0");
494        assert_eq!(upstream_version("1:0.13.0-2"), "0.13.0");
495        assert_eq!(upstream_version("0.12.1-3"), "0.12.1");
496    }
497
498    #[test]
499    fn caboodle_self_and_untapped_tools_have_no_stack_formula() {
500        assert_eq!(brew_formula(ToolName::Bobbin), Some("bobbin"));
501        assert_eq!(brew_formula(ToolName::DesirePath), Some("desire-path"));
502        assert_eq!(brew_formula(ToolName::Member("seeds")), Some("seeds"));
503        assert_eq!(brew_formula(ToolName::Member("chaski")), Some("chaski"));
504        assert_eq!(brew_formula(ToolName::Camayoc), None);
505        assert_eq!(brew_formula(ToolName::Member("shuttle")), None);
506    }
507
508    #[test]
509    fn package_standing_never_reads_ahead_as_an_update() {
510        assert_eq!(standing("0.13.0", "quipu 0.13.0"), Standing::Current);
511        assert_eq!(standing("0.12.1", "quipu 0.13.0"), Standing::Behind);
512        assert_eq!(standing("0.28.0", "bobbin 0.27.3"), Standing::Ahead);
513        assert_eq!(standing("dev", "bobbin 0.27.3"), Standing::Unknown);
514        assert_eq!(standing("0.7.1", "dp v0.3.2 (1f457ec)"), Standing::Ahead);
515    }
516}
517
518#[cfg(test)]
519mod channel_tests {
520    use super::*;
521    use serde_json::json;
522
523    #[test]
524    fn stable_channel_selects_exact_stack_formula_and_retains_pin() {
525        let bytes=serde_json::to_vec(&json!({"formulae":[
526            {"full_name":"other/bobbin","tap":"other","versions":{"stable":"99.0.0"},"installed":[{"version":"99.0.0"}],"pinned":false},
527            {"full_name":"scbrown/tap/bobbin","tap":"scbrown/tap","versions":{"stable":"0.29.0"},"installed":[{"version":"0.28.0_2"}],"pinned":true}
528        ]})).unwrap();
529        assert_eq!(
530            channel_from_json(&bytes, "bobbin").unwrap(),
531            Some(BrewChannel {
532                installed: Some("0.28.0".into()),
533                stable: "0.29.0".into(),
534                pinned: true,
535                unlinked: false
536            })
537        );
538        assert_eq!(channel_from_json(&bytes, "quipu").unwrap(), None);
539    }
540
541    #[test]
542    fn malformed_channel_cannot_stand_in_for_a_receipt() {
543        for raw in [
544            r#"{"formulae":[{"full_name":"scbrown/tap/bobbin","tap":"scbrown/tap","versions":{"stable":"0.29.0"},"installed":[] }]}"#,
545            r#"{"formulae":[{"full_name":"scbrown/tap/bobbin","tap":"scbrown/tap","pinned":false,"installed":[] }]}"#,
546            r#"{"formulae":[{"full_name":"scbrown/tap/bobbin","tap":"scbrown/tap","pinned":false,"versions":{"stable":"0.29.0"},"installed":[{}]}]}"#,
547            r#"{"formulae":null}"#,
548            "not JSON",
549        ] {
550            assert!(
551                channel_from_json(raw.as_bytes(), "bobbin").is_err(),
552                "{raw}"
553            );
554        }
555    }
556}