tambo 0.18.0

Install and prove the whole AI knowledge-tool kit
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
// Compatibility: retained library imports, persisted paths, environment keys and
// explicit old-command/version probes remain readable during the product rename.
//! Package-manager receipts for stack tools (aegis-6f1).
//!
//! On a host whose stack is delivered by a package manager, that manager is
//! the only writer. On apt hosts that is the root unattended-upgrades lane;
//! automated Tambo runs never call apt or sudo. Tambo still has to judge
//! such a tool, so it reads the package receipt (the package that owns the
//! binary PATH runs, and its version) and compares the upstream version with
//! the reviewed pin: current, ahead (never downgraded) or behind (the package
//! lane will deliver it).

use std::{env, process::Command};

use crate::model::ToolName;

/// What the package manager says about a tool's binary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Receipt {
    pub manager: &'static str,
    pub package: String,
    /// The upstream version, with any Debian epoch and revision removed.
    pub version: String,
}

/// `[epoch:]upstream[-revision]` -> `upstream`. The stack's packages use no
/// epoch and either no revision or a packaging-only one (quipu 0.13.0-2 adds
/// its qp link), so the upstream part is what the reviewed pin names.
#[must_use]
pub fn upstream_version(debian: &str) -> &str {
    let without_epoch = debian.split_once(':').map_or(debian, |(_, rest)| rest);
    without_epoch
        .rsplit_once('-')
        .map_or(without_epoch, |(upstream, _)| upstream)
}

/// The program whose owner decides who manages `tool`, if it has a binary.
#[must_use]
pub fn primary_program(tool: ToolName) -> Option<String> {
    match tool {
        ToolName::Quipu => Some("quipu".into()),
        ToolName::Bobbin => Some("bobbin".into()),
        ToolName::Yupana => Some("yupana".into()),
        ToolName::DesirePath => Some("dp".into()),
        ToolName::Camayoc => None,
        ToolName::Member(name) => {
            crate::members::get(name).and_then(|m| m.programs.first().map(|p| p.name.clone()))
        }
    }
}

/// The apt receipt for the `program` PATH runs, when dpkg owns it.
#[must_use]
pub fn apt_receipt(program: &str) -> Option<Receipt> {
    let path = crate::adapter::which_all(program, env::var_os("PATH").as_deref())
        .into_iter()
        .next()?;
    let package = crate::apt_owned::owner(&path)?;
    let query = env::var_os("CABOODLE_DPKG_QUERY").unwrap_or_else(|| "dpkg-query".into());
    let out = Command::new(query)
        .args(["-W", "-f", "${Version}", &package])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let raw = String::from_utf8_lossy(&out.stdout).trim().to_owned();
    if raw.is_empty() {
        return None;
    }
    Some(Receipt {
        manager: "apt",
        version: upstream_version(&raw).to_owned(),
        package,
    })
}

/// The Homebrew tap that publishes the stack (aegis-em2). A formula installed
/// from any other tap is package-owned but never driven by Tambo.
pub const STACK_TAP: &str = "scbrown/tap";

/// The stack formula for a member tool. caboodle-self is NOT here: on the Mac
/// its installer lane owns it until the Tambo cutover (aegis-6f1 (a)).
#[must_use]
pub fn brew_formula(tool: ToolName) -> Option<&'static str> {
    match tool {
        ToolName::Bobbin => Some("bobbin"),
        ToolName::DesirePath => Some("desire-path"),
        ToolName::Quipu => Some("quipu"),
        ToolName::Yupana => Some("yupana"),
        ToolName::Member("seeds") => Some("seeds"),
        // Chaski needs Python >= 3.11; its formula owns a python@3.12, which a
        // release-fallback wheel on macOS's /usr/bin/python3 (3.9) cannot (aegis-o7n).
        ToolName::Member("chaski") => Some("chaski"),
        _ => None,
    }
}

/// The brew executable, only where Tambo may drive it: macOS by default,
/// or any host that names one explicitly in CABOODLE_BREW (tests use a fake).
#[must_use]
pub fn brew_program() -> Option<std::ffi::OsString> {
    if let Some(explicit) = env::var_os("CABOODLE_BREW") {
        return Some(explicit);
    }
    cfg!(target_os = "macos").then(|| "brew".into())
}

/// `brew info --json=v2 <tap>/<formula>`: the installed version, and only when
/// the formula really comes from the stack tap.
///
/// NOT `--installed` (aegis-fv4, measured on the Mac 2026-10-16): with that
/// flag brew ignores the formula argument and lists EVERY installed formula, so
/// the first entry was an unrelated `homebrew/core` package and no stack member
/// could ever produce a receipt ("brew receipt after install" on every run).
fn brew_info(brew: &std::ffi::OsStr, formula: &str) -> Option<String> {
    let out = Command::new(brew)
        .args(["info", "--json=v2", &format!("{STACK_TAP}/{formula}")])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    installed_version(&out.stdout, formula)
}

/// The installed version of exactly `<STACK_TAP>/<formula>` in brew's v2 JSON.
/// Selects the entry by full name rather than position, so extra or reordered
/// entries can never stand in for the member.
fn installed_version(json: &[u8], formula: &str) -> Option<String> {
    let info: serde_json::Value = serde_json::from_slice(json).ok()?;
    let wanted = format!("{STACK_TAP}/{formula}");
    let entry =
        info.get("formulae")?.as_array()?.iter().find(|entry| {
            entry.get("full_name").and_then(|v| v.as_str()) == Some(wanted.as_str())
        })?;
    if entry.get("tap")?.as_str()? != STACK_TAP {
        return None;
    }
    let version = entry
        .get("installed")?
        .as_array()?
        .first()?
        .get("version")?
        .as_str()?;
    // Homebrew marks rebuilds as `<version>_<n>`; the pin names the upstream.
    Some(version.split('_').next()?.to_owned())
}

/// The brew receipt for a member tool installed from the stack tap.
#[must_use]
pub fn brew_receipt(tool: ToolName) -> Option<Receipt> {
    let formula = brew_formula(tool)?;
    let version = brew_info(&brew_program()?, formula)?;
    Some(Receipt {
        manager: "brew",
        package: format!("{STACK_TAP}/{formula}"),
        version,
    })
}

/// The tap's current stable version for a member, when brew can read it.
#[must_use]
pub fn brew_available(tool: ToolName) -> Option<String> {
    let formula = brew_formula(tool)?;
    let out = Command::new(brew_program()?)
        .args(["info", "--json=v2", &format!("{STACK_TAP}/{formula}")])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let info: serde_json::Value = serde_json::from_slice(&out.stdout).ok()?;
    let entry = info.get("formulae")?.as_array()?.first()?;
    if entry.get("tap")?.as_str()? != STACK_TAP {
        return None;
    }
    Some(entry.get("versions")?.get("stable")?.as_str()?.to_owned())
}

/// Current stable channel and pin selected by Homebrew for one stack formula.
#[derive(Debug, PartialEq, Eq)]
pub struct BrewChannel {
    pub installed: Option<String>,
    pub stable: String,
    pub pinned: bool,
    /// Brew reported `linked_keg: null` for an installed keg: it is off PATH.
    /// A missing key (older brew, fixtures) is not read as unlinked.
    pub unlinked: bool,
}

fn channel_from_json(bytes: &[u8], formula: &str) -> anyhow::Result<Option<BrewChannel>> {
    use anyhow::Context;
    let info: serde_json::Value = serde_json::from_slice(bytes).context("brew channel JSON")?;
    let wanted = format!("{STACK_TAP}/{formula}");
    let entries = info
        .get("formulae")
        .and_then(serde_json::Value::as_array)
        .context("brew channel formula list")?;
    let Some(entry) = entries.iter().find(|entry| {
        entry.get("full_name").and_then(serde_json::Value::as_str) == Some(wanted.as_str())
            && entry.get("tap").and_then(serde_json::Value::as_str) == Some(STACK_TAP)
    }) else {
        return Ok(None);
    };
    let stable = entry
        .get("versions")
        .and_then(|v| v.get("stable"))
        .and_then(serde_json::Value::as_str)
        .filter(|v| !v.is_empty())
        .context("brew stable channel version")?
        .to_owned();
    let pinned = entry
        .get("pinned")
        .and_then(serde_json::Value::as_bool)
        .context("brew formula pin status")?;
    let installed = entry
        .get("installed")
        .and_then(serde_json::Value::as_array)
        .context("brew installed receipt list")?
        .first()
        .map(|receipt| {
            receipt
                .get("version")
                .and_then(serde_json::Value::as_str)
                .filter(|v| !v.is_empty())
                .map(|v| v.split('_').next().unwrap_or(v).to_owned())
                .context("brew installed version")
        })
        .transpose()?;
    let unlinked = installed.is_some()
        && entry
            .get("linked_keg")
            .is_some_and(serde_json::Value::is_null);
    Ok(Some(BrewChannel {
        installed,
        stable,
        pinned,
        unlinked,
    }))
}

/// Refresh once per selected update, before judging installed versions. An
/// unreadable/stale channel must not be silently reported as converged.
pub fn brew_refresh() -> anyhow::Result<()> {
    let brew = brew_program().ok_or_else(|| anyhow::anyhow!("brew is not available"))?;
    match crate::brew_bound::run(
        &brew,
        ["update", "--quiet"],
        crate::brew_bound::Output::Inherit,
        crate::brew_bound::Bound::Step,
    )? {
        Ok(done) if done.status.success() => Ok(()),
        Ok(done) => anyhow::bail!("brew update failed ({})", done.status),
        Err(timed_out) => anyhow::bail!("brew update {timed_out}"),
    }
}

pub fn brew_channel(tool: ToolName) -> anyhow::Result<Option<BrewChannel>> {
    let Some(formula) = brew_formula(tool) else {
        return Ok(None);
    };
    let brew = brew_program().ok_or_else(|| anyhow::anyhow!("brew is not available"))?;
    let out = match crate::brew_bound::run(
        &brew,
        ["info", "--json=v2", &format!("{STACK_TAP}/{formula}")],
        crate::brew_bound::Output::Capture,
        crate::brew_bound::Bound::Step,
    )? {
        Ok(done) => done,
        Err(timed_out) => anyhow::bail!("brew channel read for {formula} {timed_out}"),
    };
    if !out.status.success() {
        anyhow::bail!("brew channel read failed for {formula} ({})", out.status);
    }
    channel_from_json(&out.stdout, formula)
}

/// Install or upgrade a member from the stack tap. Brew runs as the user (no
/// root), so Tambo drives it directly (aegis-6f1 ruling).
///
/// The step is bounded (aegis-f0ne). When it fails or times out, the keg brew
/// had already unlinked is linked again, so the previous version stays on PATH,
/// and the error names the member. Its first line is
/// `<tool> brew delivery timed out after <N>s ...`, which the Mac consumer
/// reports as a member timeout.
pub fn brew_converge(tool: ToolName, upgrade: bool) -> anyhow::Result<()> {
    let formula = brew_formula(tool).ok_or_else(|| anyhow::anyhow!("no stack formula"))?;
    let brew = brew_program().ok_or_else(|| anyhow::anyhow!("brew is not available"))?;
    let verb = if upgrade { "upgrade" } else { "install" };
    let full = format!("{STACK_TAP}/{formula}");
    match crate::brew_bound::run(
        &brew,
        [verb, full.as_str()],
        crate::brew_bound::Output::Inherit,
        crate::brew_bound::Bound::Step,
    )? {
        Ok(done) if done.status.success() => Ok(()),
        Ok(done) => {
            let link = restore_link(&brew, formula);
            anyhow::bail!("brew {verb} {full} failed ({}); {link}", done.status)
        }
        Err(timed_out) => {
            let link = restore_link(&brew, formula);
            anyhow::bail!(
                "{} brew delivery {timed_out} during `brew {verb} {full}`; {link}",
                tool.as_str()
            )
        }
    }
}

/// Link the installed keg again if an interrupted brew step left it unlinked.
/// Returns what it found and did, for the error message.
fn restore_link(brew: &std::ffi::OsStr, formula: &str) -> String {
    match restore_link_with(brew, formula) {
        Ok(text) | Err(text) => text,
    }
}

/// Link `tool`'s installed keg when brew reports it unlinked (aegis-f0ne):
/// an earlier interrupted step leaves the keg installed but off PATH, and a
/// later `brew upgrade` preserves that state. `Ok` says what was done; `Err`
/// says why the keg is still not linked, so the caller can fail the member
/// with that text rather than reach an opaque verify error (eph-review-07aef5).
pub fn brew_relink(tool: ToolName) -> Result<String, String> {
    match (brew_formula(tool), brew_program()) {
        (Some(formula), Some(brew)) => restore_link_with(&brew, formula),
        _ => Err("no stack formula or brew".into()),
    }
}

fn restore_link_with(brew: &std::ffi::OsStr, formula: &str) -> Result<String, String> {
    let full = format!("{STACK_TAP}/{formula}");
    let read = || -> Option<(Option<String>, Option<String>)> {
        let done = crate::brew_bound::run(
            brew,
            ["info", "--json=v2", full.as_str()],
            crate::brew_bound::Output::Capture,
            crate::brew_bound::Bound::Repair,
        )
        .ok()?
        .ok()?;
        done.status.success().then_some(())?;
        link_state(&done.stdout, formula)
    };
    let Some((installed, linked)) = read() else {
        return Err(format!(
            "keg link state for {full} is UNKNOWN (brew info unreadable)"
        ));
    };
    let Some(installed) = installed else {
        return Err(format!("no {full} keg is installed"));
    };
    if let Some(linked) = linked {
        return Ok(format!("keg {linked} is still linked"));
    }
    match crate::brew_bound::run(
        brew,
        ["link", full.as_str()],
        crate::brew_bound::Output::Inherit,
        crate::brew_bound::Bound::Repair,
    ) {
        Ok(Ok(done)) if done.status.success() => match read() {
            Some((_, Some(linked))) => Ok(format!("relinked keg {linked}")),
            _ => Err(format!(
                "`brew link {full}` ran but keg {installed} is still NOT linked"
            )),
        },
        Ok(Ok(done)) => Err(format!(
            "keg {installed} is NOT linked; `brew link {full}` failed ({})",
            done.status
        )),
        Ok(Err(timed_out)) => Err(format!(
            "keg {installed} is NOT linked; `brew link {full}` {timed_out}"
        )),
        Err(error) => Err(format!(
            "keg {installed} is NOT linked; `brew link {full}`: {error}"
        )),
    }
}

/// The installed and linked versions of exactly `<STACK_TAP>/<formula>`.
fn link_state(json: &[u8], formula: &str) -> Option<(Option<String>, Option<String>)> {
    let info: serde_json::Value = serde_json::from_slice(json).ok()?;
    let wanted = format!("{STACK_TAP}/{formula}");
    let entry = info.get("formulae")?.as_array()?.iter().find(|entry| {
        entry.get("full_name").and_then(serde_json::Value::as_str) == Some(wanted.as_str())
    })?;
    let installed = entry
        .get("installed")?
        .as_array()?
        .first()
        .and_then(|receipt| receipt.get("version")?.as_str())
        .map(str::to_owned);
    let linked = entry
        .get("linked_keg")
        .and_then(serde_json::Value::as_str)
        .map(str::to_owned);
    Some((installed, linked))
}

/// How a package-owned tool stands against its reviewed pin.
#[derive(Debug, PartialEq, Eq)]
pub enum Standing {
    Current,
    Ahead,
    Behind,
    /// One of the versions has no comparable semantic version.
    Unknown,
}

#[must_use]
pub fn standing(receipt_version: &str, desired: &str) -> Standing {
    let installed = format!("pkg {receipt_version}");
    match (
        crate::release_update::behind_reviewed(&installed, desired),
        crate::release_update::behind_reviewed(desired, &installed),
    ) {
        (Some(true), _) => Standing::Behind,
        (Some(false), Some(true)) => Standing::Ahead,
        (Some(false), Some(false)) => Standing::Current,
        _ => Standing::Unknown,
    }
}

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

    fn entry(full_name: &str, tap: &str, installed: &[&str]) -> serde_json::Value {
        serde_json::json!({
            "full_name": full_name,
            "tap": tap,
            "installed": installed.iter().map(|v| serde_json::json!({"version": v})).collect::<Vec<_>>(),
        })
    }

    fn info(entries: Vec<serde_json::Value>) -> Vec<u8> {
        serde_json::to_vec(&serde_json::json!({"formulae": entries, "casks": []})).unwrap()
    }

    #[test]
    fn receipt_reads_the_named_member_not_the_first_installed_formula() {
        // aegis-fv4: `--installed` made brew list every formula; abseil came first.
        let listing = info(vec![
            entry("abseil", "homebrew/core", &["20250814.1"]),
            entry("scbrown/tap/quipu", "scbrown/tap", &["0.14.1"]),
        ]);
        assert_eq!(
            installed_version(&listing, "quipu").as_deref(),
            Some("0.14.1")
        );
        assert_eq!(installed_version(&listing, "bobbin"), None);
    }

    #[test]
    fn receipt_refuses_uninstalled_foreign_tap_and_malformed_answers() {
        assert_eq!(
            installed_version(
                &info(vec![entry("scbrown/tap/bobbin", "scbrown/tap", &[])]),
                "bobbin"
            ),
            None
        );
        assert_eq!(
            installed_version(
                &info(vec![entry("scbrown/tap/bobbin", "other/tap", &["1.0.0"])]),
                "bobbin"
            ),
            None
        );
        assert_eq!(installed_version(b"not json", "bobbin"), None);
        assert_eq!(
            installed_version(
                &info(vec![entry(
                    "scbrown/tap/yupana",
                    "scbrown/tap",
                    &["0.13.0_1"]
                )]),
                "yupana"
            )
            .as_deref(),
            Some("0.13.0")
        );
    }

    use super::*;

    #[test]
    fn debian_revision_and_epoch_are_not_part_of_the_pinned_version() {
        assert_eq!(upstream_version("0.13.0"), "0.13.0");
        assert_eq!(upstream_version("0.13.0-2"), "0.13.0");
        assert_eq!(upstream_version("1:0.13.0-2"), "0.13.0");
        assert_eq!(upstream_version("0.12.1-3"), "0.12.1");
    }

    #[test]
    fn caboodle_self_and_untapped_tools_have_no_stack_formula() {
        assert_eq!(brew_formula(ToolName::Bobbin), Some("bobbin"));
        assert_eq!(brew_formula(ToolName::DesirePath), Some("desire-path"));
        assert_eq!(brew_formula(ToolName::Member("seeds")), Some("seeds"));
        assert_eq!(brew_formula(ToolName::Member("chaski")), Some("chaski"));
        assert_eq!(brew_formula(ToolName::Camayoc), None);
        assert_eq!(brew_formula(ToolName::Member("shuttle")), None);
    }

    #[test]
    fn package_standing_never_reads_ahead_as_an_update() {
        assert_eq!(standing("0.13.0", "quipu 0.13.0"), Standing::Current);
        assert_eq!(standing("0.12.1", "quipu 0.13.0"), Standing::Behind);
        assert_eq!(standing("0.28.0", "bobbin 0.27.3"), Standing::Ahead);
        assert_eq!(standing("dev", "bobbin 0.27.3"), Standing::Unknown);
        assert_eq!(standing("0.7.1", "dp v0.3.2 (1f457ec)"), Standing::Ahead);
    }
}

#[cfg(test)]
mod channel_tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn stable_channel_selects_exact_stack_formula_and_retains_pin() {
        let bytes=serde_json::to_vec(&json!({"formulae":[
            {"full_name":"other/bobbin","tap":"other","versions":{"stable":"99.0.0"},"installed":[{"version":"99.0.0"}],"pinned":false},
            {"full_name":"scbrown/tap/bobbin","tap":"scbrown/tap","versions":{"stable":"0.29.0"},"installed":[{"version":"0.28.0_2"}],"pinned":true}
        ]})).unwrap();
        assert_eq!(
            channel_from_json(&bytes, "bobbin").unwrap(),
            Some(BrewChannel {
                installed: Some("0.28.0".into()),
                stable: "0.29.0".into(),
                pinned: true,
                unlinked: false
            })
        );
        assert_eq!(channel_from_json(&bytes, "quipu").unwrap(), None);
    }

    #[test]
    fn malformed_channel_cannot_stand_in_for_a_receipt() {
        for raw in [
            r#"{"formulae":[{"full_name":"scbrown/tap/bobbin","tap":"scbrown/tap","versions":{"stable":"0.29.0"},"installed":[] }]}"#,
            r#"{"formulae":[{"full_name":"scbrown/tap/bobbin","tap":"scbrown/tap","pinned":false,"installed":[] }]}"#,
            r#"{"formulae":[{"full_name":"scbrown/tap/bobbin","tap":"scbrown/tap","pinned":false,"versions":{"stable":"0.29.0"},"installed":[{}]}]}"#,
            r#"{"formulae":null}"#,
            "not JSON",
        ] {
            assert!(
                channel_from_json(raw.as_bytes(), "bobbin").is_err(),
                "{raw}"
            );
        }
    }
}