tambo 0.4.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
use std::{
    collections::HashSet,
    env,
    ffi::OsStr,
    fs,
    path::{Path, PathBuf},
};

use anyhow::{bail, Context, Result};
use serde::Deserialize;

use crate::{
    adapter::{checked, download_https},
    model::{CrewMode, CrewRuntimeState, CrewSelection, State},
};

const SHANTYTOWN_VERSION: &str = "0.4.0";
const SHANTYTOWN_WHEEL_SHA256: &str =
    "afd52cb5e2b8c67eef8fa7e3aa4e8c725419d0f1f3e84184d6a01b52134ca8ac";
const CREEL_REVISION: &str = "0003aee9b1eec512e59d13b64a6c5a4d3b8b55d6";
const CREEL_ARCHIVE_SHA256: &str =
    "951809b5ce49f3180872c5a634c7e34bf57e7be0195da70e1dfe32c50101801c";

#[derive(Debug, Default)]
pub struct CrewEvidence {
    pub creel_doctor: Option<PathBuf>,
    pub creel_admission: Option<PathBuf>,
}

pub fn apply(selection: &CrewSelection, state: &mut State, skip_install: bool) -> Result<()> {
    if selects_shantytown(selection.mode) {
        let observed = shantytown_installed();
        match shantytown_convergence(&observed) {
            Convergence::Current => {}
            Convergence::Decline => {
                // Never install the older reviewed pin over a newer, unknown or
                // unreadable st (aegis-fv4): that is a downgrade on a guess.
                println!("shantytown: {}; not installed", decline_reason(&observed));
                return apply_creel(selection, state, skip_install);
            }
            Convergence::Install => {
                if skip_install {
                    bail!("Shantytown is not installed and --skip-install was selected");
                }
                install_shantytown()?;
            }
        }
        record(state, "shantytown", shantytown_version()?, false);
        println!("shantytown: applied");
    }
    apply_creel(selection, state, skip_install)
}

fn apply_creel(selection: &CrewSelection, state: &mut State, skip_install: bool) -> Result<()> {
    if selects_creel(selection.mode) {
        if skip_install && !creel_root()?.join("REVISION").is_file() {
            bail!("Creel is not installed and --skip-install was selected");
        }
        install_creel()?;
        record(state, "creel", format!("creel {CREEL_REVISION}"), false);
        println!("creel: applied");
    }
    Ok(())
}

pub fn verify(selection: &CrewSelection, evidence: &CrewEvidence, state: &mut State) -> Result<()> {
    if selects_shantytown(selection.mode) {
        let version = shantytown_version()?;
        record(state, "shantytown", version, true);
        println!("shantytown: verified");
    }
    if selects_creel(selection.mode) {
        verify_creel_bundle()?;
        let doctor = evidence.creel_doctor.as_deref().context(
            "Creel verification requires --creel-doctor from the browser capability preflight",
        )?;
        let admission = evidence.creel_admission.as_deref().context(
            "Creel verification requires --creel-admission from the provider-window governor",
        )?;
        validate_doctor(doctor)?;
        validate_admission(admission)?;
        record(state, "creel", format!("creel {CREEL_REVISION}"), true);
        println!("creel: verified");
    }
    Ok(())
}

pub fn check_updates(selection: &CrewSelection) -> bool {
    let mut current = true;
    if selects_shantytown(selection.mode) {
        match (shantytown_version(), shantytown_installed()) {
            (Ok(version), _) => println!("shantytown: current ({version})"),
            (Err(error), Observed::Absent) => {
                current = false;
                println!(
                    "shantytown: missing or drifted ({error:#}); reviewed: st {SHANTYTOWN_VERSION}"
                );
            }
            (Err(_), observed) => {
                current = false;
                println!("shantytown: {}", decline_reason(&observed));
            }
        }
    }
    if selects_creel(selection.mode) {
        match verify_creel_bundle() {
            Ok(()) => println!("creel: current (creel {CREEL_REVISION})"),
            Err(error) => {
                current = false;
                println!("creel: missing or drifted ({error:#}); reviewed: creel {CREEL_REVISION}");
            }
        }
    }
    current
}

fn selects_shantytown(mode: CrewMode) -> bool {
    matches!(mode, CrewMode::Shantytown | CrewMode::Both)
}

fn selects_creel(mode: CrewMode) -> bool {
    matches!(mode, CrewMode::Creel | CrewMode::Both)
}

fn record(state: &mut State, name: &str, version: String, verified: bool) {
    let remains_verified = state
        .crew
        .get(name)
        .is_some_and(|old| old.version == version && old.verified);
    state.crew.insert(
        name.to_owned(),
        CrewRuntimeState {
            version,
            applied: true,
            verified: verified || remains_verified,
        },
    );
}

fn home() -> Result<PathBuf> {
    env::var_os("HOME")
        .map(PathBuf::from)
        .context("HOME is required to install crew runtimes")
}

fn install_shantytown() -> Result<()> {
    if shantytown_version().is_ok() {
        return Ok(());
    }
    let download = tempfile::tempdir().context("create Shantytown download directory")?;
    let wheel = download
        .path()
        .join(format!("shantytown-{SHANTYTOWN_VERSION}-py3-none-any.whl"));
    download_https(
        &format!(
            "https://github.com/scbrown/shantytown/releases/download/v{SHANTYTOWN_VERSION}/shantytown-{SHANTYTOWN_VERSION}-py3-none-any.whl"
        ),
        &wheel,
    )?;
    verify_fixed_checksum(&wheel, SHANTYTOWN_WHEEL_SHA256, "Shantytown wheel")?;
    let root = home()?
        .join(".local/share/caboodle/shantytown")
        .join(format!("v{SHANTYTOWN_VERSION}"));
    if !root.join("bin/python").exists() {
        fs::create_dir_all(root.parent().context("Shantytown root has no parent")?)?;
        checked(
            "python3",
            [OsStr::new("-m"), OsStr::new("venv"), root.as_os_str()],
            None,
        )?;
        checked(
            root.join("bin/pip")
                .to_str()
                .context("Shantytown pip path is not UTF-8")?,
            [
                OsStr::new("install"),
                OsStr::new("--no-deps"),
                wheel.as_os_str(),
            ],
            None,
        )?;
    }
    link_binary(&root.join("bin/st"), "st")
}

#[derive(Debug, PartialEq, Eq)]
enum Convergence {
    Current,
    Install,
    Decline,
}

/// Absent -> install; exactly the reviewed pin -> current; strictly older ->
/// converge upward; newer or not comparable -> decline (aegis-fv4).
fn shantytown_convergence(observed: &Observed) -> Convergence {
    let installed = match observed {
        Observed::Absent => return Convergence::Install,
        Observed::Unreadable(_) => return Convergence::Decline,
        Observed::Version(version) => version,
    };
    if installed.starts_with(&format!("st {SHANTYTOWN_VERSION}")) {
        return Convergence::Current;
    }
    match crate::release_update::behind_reviewed(installed, &format!("st {SHANTYTOWN_VERSION}")) {
        Some(true) => Convergence::Install,
        Some(false) | None => Convergence::Decline,
    }
}

/// What is on this host. Only a CONFIRMED absence may install: an st that is
/// present but cannot report its version is unknown, not missing.
#[derive(Debug, PartialEq, Eq)]
enum Observed {
    Absent,
    Unreadable(String),
    Version(String),
}

fn decline_reason(observed: &Observed) -> String {
    let reviewed = format!("st {SHANTYTOWN_VERSION}");
    match observed {
        Observed::Version(installed) => format!(
            "{} (installed: {installed}); reviewed: {reviewed}",
            crate::engine::reviewed_drift_status(installed, &reviewed)
        ),
        Observed::Unreadable(error) => format!(
            "present but its version is unreadable ({error}); reviewed: {reviewed}; refusing to replace it"
        ),
        Observed::Absent => format!("missing; reviewed: {reviewed}"),
    }
}

fn shantytown_installed() -> Observed {
    if crate::adapter::which_all("st", env::var_os("PATH").as_deref()).is_empty() {
        return Observed::Absent;
    }
    match checked("st", ["--version"], None) {
        Ok(output) => Observed::Version(String::from_utf8_lossy(&output.stdout).trim().to_owned()),
        Err(error) => Observed::Unreadable(format!("{error:#}")),
    }
}

fn shantytown_version() -> Result<String> {
    let output = checked("st", ["--version"], None)?;
    let version = String::from_utf8_lossy(&output.stdout).trim().to_owned();
    if !version.starts_with(&format!("st {SHANTYTOWN_VERSION}")) {
        bail!("Shantytown version is incompatible: {version}");
    }
    Ok(version)
}

fn install_creel() -> Result<()> {
    let root = creel_root()?;
    if root.join("REVISION").exists() {
        return Ok(());
    }
    let download = tempfile::tempdir().context("create Creel download directory")?;
    let archive = download.path().join("creel.tar.gz");
    download_https(
        &format!("https://github.com/scbrown/creel/archive/{CREEL_REVISION}.tar.gz"),
        &archive,
    )?;
    verify_fixed_checksum(&archive, CREEL_ARCHIVE_SHA256, "Creel archive")?;
    fs::create_dir_all(&root)?;
    checked(
        "tar",
        [
            OsStr::new("-xzf"),
            archive.as_os_str(),
            OsStr::new("--strip-components=1"),
            OsStr::new("-C"),
            root.as_os_str(),
        ],
        None,
    )?;
    fs::write(root.join("REVISION"), format!("{CREEL_REVISION}\n"))?;
    Ok(())
}

fn creel_root() -> Result<PathBuf> {
    if let Some(path) = env::var_os("CABOODLE_CREEL_ROOT") {
        return Ok(PathBuf::from(path));
    }
    Ok(home()?
        .join(".local/share/caboodle/creel")
        .join(CREEL_REVISION))
}

fn verify_creel_bundle() -> Result<()> {
    let root = creel_root()?;
    let revision = fs::read_to_string(root.join("REVISION")).context("read Creel revision")?;
    if revision.trim() != CREEL_REVISION {
        bail!("installed Creel revision does not match the reviewed bundle");
    }
    for path in [
        "app/index.html",
        "app/sw.js",
        "app/wasm/pkg/creel_quipu_provider_bg.wasm",
    ] {
        if !root.join(path).is_file() {
            bail!("installed Creel bundle is missing {path}");
        }
    }
    Ok(())
}

fn verify_fixed_checksum(path: &Path, expected: &str, label: &str) -> Result<()> {
    let output = checked("sha256sum", [path.as_os_str()], None)?;
    let actual = String::from_utf8_lossy(&output.stdout)
        .split_whitespace()
        .next()
        .context("sha256sum returned no digest")?
        .to_owned();
    if actual != expected {
        bail!("{label} checksum mismatch");
    }
    Ok(())
}

fn link_binary(target: &Path, name: &str) -> Result<()> {
    let bin_dir = env::var_os("CARGO_HOME")
        .map(PathBuf::from)
        .unwrap_or(home()?.join(".cargo"))
        .join("bin");
    fs::create_dir_all(&bin_dir)?;
    let link = bin_dir.join(name);
    if link.exists() || link.symlink_metadata().is_ok() {
        bail!("refusing to replace existing {}", link.display());
    }
    #[cfg(unix)]
    std::os::unix::fs::symlink(target, &link)
        .with_context(|| format!("link {name} into {}", bin_dir.display()))?;
    #[cfg(not(unix))]
    bail!("crew runtime installation currently requires a Unix host");
    Ok(())
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct DoctorContract {
    schema_version: u32,
    overall: CheckStatus,
    checks: Vec<DoctorCheck>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct DoctorCheck {
    id: String,
    status: CheckStatus,
    severity: Severity,
    evidence: String,
    remediation: String,
    redacted: bool,
}

#[derive(Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum CheckStatus {
    Pass,
    Fail,
    Unknown,
}

#[derive(Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum Severity {
    Required,
    Advisory,
}

fn validate_doctor(path: &Path) -> Result<()> {
    let contract: DoctorContract = read_json(path, "Creel doctor")?;
    if contract.schema_version != 1 {
        bail!(
            "unsupported Creel doctor schema {}",
            contract.schema_version
        );
    }
    if contract.checks.is_empty() {
        bail!("Creel doctor returned no checks");
    }
    let mut ids = HashSet::new();
    for check in &contract.checks {
        if check.id.trim().is_empty() || !ids.insert(&check.id) {
            bail!("Creel doctor check IDs must be non-empty and unique");
        }
        if !check.redacted
            || check.evidence.trim().is_empty()
            || check.remediation.trim().is_empty()
        {
            bail!(
                "Creel doctor check {} lacks redacted evidence/remediation",
                check.id
            );
        }
        if check.severity == Severity::Required && check.status != CheckStatus::Pass {
            bail!("Creel required doctor check {} did not pass", check.id);
        }
    }
    if contract.overall != CheckStatus::Pass {
        bail!("Creel doctor aggregate is not pass");
    }
    Ok(())
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct AdmissionContract {
    schema_version: u32,
    verdict: AdmissionVerdict,
    provider_window: AdmissionSignal,
    device_tab_cap: AdmissionSignal,
    signal_freshness: AdmissionSignal,
    reason: String,
    redacted: bool,
}

#[derive(Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum AdmissionVerdict {
    Admit,
    Refuse,
    Unknown,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct AdmissionSignal {
    status: CheckStatus,
    evidence: String,
}

fn validate_admission(path: &Path) -> Result<()> {
    let contract: AdmissionContract = read_json(path, "Creel admission")?;
    if contract.schema_version != 1 {
        bail!(
            "unsupported Creel admission schema {}",
            contract.schema_version
        );
    }
    if !contract.redacted || contract.reason.trim().is_empty() {
        bail!("Creel admission reason must be present and redacted");
    }
    for (name, signal) in [
        ("provider_window", &contract.provider_window),
        ("device_tab_cap", &contract.device_tab_cap),
        ("signal_freshness", &contract.signal_freshness),
    ] {
        if signal.status != CheckStatus::Pass || signal.evidence.trim().is_empty() {
            bail!("Creel admission signal {name} is not a measured pass");
        }
    }
    if contract.verdict != AdmissionVerdict::Admit {
        bail!("Creel governor did not admit this launch");
    }
    Ok(())
}

fn read_json<T: for<'de> Deserialize<'de>>(path: &Path, label: &str) -> Result<T> {
    let body = fs::read_to_string(path).with_context(|| format!("read {label} contract"))?;
    serde_json::from_str(&body).with_context(|| format!("parse {label} contract"))
}

#[cfg(test)]
mod convergence_tests {
    use super::{shantytown_convergence, Convergence, Observed};

    #[test]
    fn shantytown_never_converges_downward_or_on_a_guess() {
        let v = |s: &str| Observed::Version(s.to_owned());
        assert_eq!(
            shantytown_convergence(&Observed::Absent),
            Convergence::Install
        );
        assert_eq!(
            shantytown_convergence(&Observed::Unreadable("exit status 42".into())),
            Convergence::Decline
        );
        assert_eq!(shantytown_convergence(&v("st 0.4.0")), Convergence::Current);
        assert_eq!(shantytown_convergence(&v("st 0.3.9")), Convergence::Install);
        for ahead_or_unknown in ["st 0.7.0 (a9a0136-dirty)", "st 0.5.0", "st dev", "st"] {
            assert_eq!(
                shantytown_convergence(&v(ahead_or_unknown)),
                Convergence::Decline,
                "{ahead_or_unknown}"
            );
        }
    }
}