Skip to main content

caboodle/
adapter.rs

1// Compatibility: retained library imports, persisted paths, environment keys and
2// explicit old-command/version probes remain readable during the product rename.
3use std::{
4    env,
5    ffi::{OsStr, OsString},
6    fs,
7    path::{Path, PathBuf},
8    process::{Command, Output},
9    time::{SystemTime, UNIX_EPOCH},
10};
11
12use anyhow::{bail, Context, Result};
13use serde_json::{json, Value};
14
15use crate::model::{QuipuFlavor, ToolName};
16
17mod manifest;
18mod quipu_alias;
19pub(crate) use manifest::{
20    find_program, identify_member, prove_release, release_target, single_program, stage, verify_at,
21};
22
23pub trait Adapter {
24    fn name(&self) -> ToolName;
25    /// Release identity reviewed and pinned by this Tambo build.
26    fn desired_version(&self) -> String;
27    fn install(&self) -> Result<()>;
28    fn version(&self) -> Result<String>;
29    fn verify(&self) -> Result<()>;
30
31    /// Bind package verification to the executables PATH actually runs. Most
32    /// adapters already use PATH; Quipu and manifest members normally prefer
33    /// their managed Cargo install.
34    fn package_adapter(&self) -> Result<Option<Box<dyn Adapter>>> {
35        Ok(None)
36    }
37
38    fn is_current(&self, installed: &str) -> bool {
39        installed == self.desired_version()
40    }
41}
42
43/// Why `install` cannot fetch a reviewed artifact for this host, if it cannot.
44/// Read-only: it inspects the platform, never the network. The same target
45/// functions drive the installers, so the answer cannot drift from them.
46pub fn release_blocker(name: ToolName, quipu_flavor: QuipuFlavor) -> Option<String> {
47    let result = match name {
48        ToolName::Quipu if quipu_flavor == QuipuFlavor::Release => quipu_release_target(),
49        ToolName::Bobbin => bobbin_release_target(),
50        ToolName::Yupana => yupana_release_target(),
51        ToolName::Member(name) => match crate::members::get(name) {
52            Some(m) => manifest::release_target(m),
53            None => return Some(format!("unknown stack member {name}")),
54        },
55        // Camayoc is a source archive, Desire Path and the lancedb Quipu
56        // flavor are source builds: their blockers are missing prerequisites.
57        // Named, never a wildcard: a new variant must decide (aegis-1i5h1j).
58        ToolName::Quipu | ToolName::Camayoc | ToolName::DesirePath => return None,
59    };
60    result.err().map(|error| format!("{error:#}"))
61}
62
63/// Host commands the install and verification steps of one tool shell out to.
64pub fn prerequisites(name: ToolName, quipu_flavor: QuipuFlavor) -> &'static [&'static str] {
65    match name {
66        ToolName::Quipu if quipu_flavor == QuipuFlavor::Lancedb => &["cargo"],
67        ToolName::Quipu => &["curl", "tar"],
68        // Camayoc's bootstrap is bash + python3, and it talks to Quipu with curl.
69        ToolName::Camayoc => &["curl", "tar", "sha256sum", "bash", "python3"],
70        ToolName::Bobbin => &["curl", "tar", "git"],
71        ToolName::Yupana => &["curl", "tar"],
72        ToolName::DesirePath => &["go"],
73        ToolName::Member(name) => crate::members::prerequisites(name),
74    }
75}
76
77/// The reviewed source build to run by hand where no release exists for a host.
78pub fn source_install_command(name: ToolName) -> Option<String> {
79    match name {
80        ToolName::Quipu => Some(format!("cargo {}", quipu_install_args(QuipuFlavor::Release).join(" "))),
81        ToolName::Yupana => Some(format!(
82            "cargo install --git https://github.com/scbrown/yupana --tag v{YUPANA_VERSION} --locked --features mcp"
83        )),
84        // A member installs only its reviewed release; there is no source path.
85        ToolName::Camayoc | ToolName::Bobbin | ToolName::DesirePath | ToolName::Member(_) => None,
86    }
87}
88
89/// Executables a tool puts on PATH, in the order a shell would look them up.
90pub fn programs(name: ToolName) -> &'static [&'static str] {
91    match name {
92        ToolName::Quipu => &["qp", "quipu", "quipu-server"],
93        ToolName::Camayoc => &[],
94        ToolName::Bobbin => &["bobbin"],
95        ToolName::Yupana => &["yupana"],
96        ToolName::DesirePath => &["dp"],
97        ToolName::Member(name) => crate::members::programs(name),
98    }
99}
100
101/// Every executable named `program` on `path`, in lookup order.
102pub fn which_all(program: &str, path: Option<&std::ffi::OsStr>) -> Vec<PathBuf> {
103    let Some(path) = path else {
104        return Vec::new();
105    };
106    let mut found: Vec<PathBuf> = Vec::new();
107    let mut targets: Vec<PathBuf> = Vec::new();
108    for candidate in env::split_paths(path).map(|directory| directory.join(program)) {
109        if !is_executable(&candidate) {
110            continue;
111        }
112        // A directory listed twice, or a symlink to a copy already seen, is the
113        // same binary rather than a shadowing one.
114        let target = candidate
115            .canonicalize()
116            .unwrap_or_else(|_| candidate.clone());
117        if !targets.contains(&target) {
118            targets.push(target);
119            found.push(candidate);
120        }
121    }
122    found
123}
124
125pub(crate) fn is_executable(path: &Path) -> bool {
126    let Ok(metadata) = path.metadata() else {
127        return false;
128    };
129    if !metadata.is_file() {
130        return false;
131    }
132    #[cfg(unix)]
133    {
134        use std::os::unix::fs::PermissionsExt;
135        metadata.permissions().mode() & 0o111 != 0
136    }
137    #[cfg(not(unix))]
138    true
139}
140
141/// What a shell actually runs for one managed program (aegis-70qlhs).
142///
143/// Versions are read from the MANAGED copy (`$CARGO_HOME/bin`), so a stale
144/// binary earlier on PATH can make `verify` report a tool current while the
145/// user runs something else. That happened: a fresh `cargo install` exited 0,
146/// the new binary sat on disk, and an older copy in `~/.local/bin` kept
147/// answering. Nothing said which copy ran.
148#[derive(Debug, PartialEq, Eq)]
149pub enum PathResolution {
150    /// PATH runs the managed copy, or there is no managed copy to compare.
151    Managed,
152    /// The program is not on PATH at all.
153    NotOnPath,
154    /// PATH runs a different file that reports the same `--version`.
155    SameBuild { runs: PathBuf, managed: PathBuf },
156    /// PATH runs a different file that reports a different `--version`.
157    Shadowed {
158        runs: PathBuf,
159        runs_version: String,
160        managed: PathBuf,
161        managed_version: String,
162    },
163}
164
165/// Resolve `program` the way a shell would, against the managed copy.
166pub fn path_resolution(program: &str, path: Option<&OsStr>) -> PathResolution {
167    let Some(managed) = managed_bin_dir().map(|dir| dir.join(program)) else {
168        return PathResolution::Managed;
169    };
170    if !is_executable(&managed) {
171        return PathResolution::Managed;
172    }
173    let Some(runs) = which_all(program, path).into_iter().next() else {
174        return PathResolution::NotOnPath;
175    };
176    let canonical = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
177    if canonical(&runs) == canonical(&managed) {
178        return PathResolution::Managed;
179    }
180    let version = |p: &Path| {
181        p.to_str()
182            .and_then(|s| read_version(s).ok())
183            .unwrap_or_else(|| "unreadable".to_owned())
184    };
185    let (runs_version, managed_version) = (version(&runs), version(&managed));
186    if runs_version == managed_version {
187        PathResolution::SameBuild { runs, managed }
188    } else {
189        PathResolution::Shadowed {
190            runs,
191            runs_version,
192            managed,
193            managed_version,
194        }
195    }
196}
197
198/// Where the release and cargo installers write binaries.
199pub fn managed_bin_dir() -> Option<PathBuf> {
200    env::var_os("CARGO_HOME")
201        .map(PathBuf::from)
202        .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".cargo")))
203        .map(|home| home.join("bin"))
204}
205
206pub fn adapter(name: ToolName, quipu_flavor: QuipuFlavor) -> Box<dyn Adapter> {
207    match name {
208        ToolName::Quipu => Box::new(Quipu {
209            flavor: quipu_flavor,
210            external: None,
211        }),
212        ToolName::Camayoc => Box::new(Camayoc),
213        ToolName::Bobbin => Box::new(Bobbin),
214        ToolName::Yupana => Box::new(Yupana),
215        ToolName::DesirePath => Box::new(DesirePath),
216        ToolName::Member(name) => Box::new(manifest::ManifestAdapter(
217            crate::members::get(name)
218                .expect("a Member name is only minted for an embedded manifest"),
219        )),
220    }
221}
222
223/// Resolve external binaries once so identity and round trips use the same files.
224pub fn adapter_for_plan(name: ToolName, plan: &crate::model::Plan) -> Result<Box<dyn Adapter>> {
225    if name != ToolName::Quipu || !plan.external_quipu {
226        return Ok(adapter(name, plan.quipu_flavor));
227    }
228    let path = env::var_os("PATH");
229    let resolve = |name| -> Result<PathBuf> {
230        which_all(name, path.as_deref())
231            .into_iter()
232            .next()
233            .with_context(|| format!("external Quipu requires {name} on PATH"))?
234            .canonicalize()
235            .with_context(|| format!("resolve external {name}"))
236    };
237    Ok(Box::new(Quipu {
238        flavor: plan.quipu_flavor,
239        external: Some((resolve("quipu")?, resolve("quipu-server")?)),
240    }))
241}
242
243fn output<P, I, S>(program: P, args: I, cwd: Option<&Path>) -> Result<Output>
244where
245    P: AsRef<OsStr>,
246    I: IntoIterator<Item = S>,
247    S: AsRef<OsStr>,
248{
249    let args: Vec<OsString> = args
250        .into_iter()
251        .map(|arg| arg.as_ref().to_os_string())
252        .collect();
253    let program = program.as_ref();
254    let mut command = Command::new(program);
255    command.args(&args);
256    if let Some(cwd) = cwd {
257        command.current_dir(cwd);
258    }
259    command.output().with_context(|| {
260        format!(
261            "run {} {}",
262            program.to_string_lossy(),
263            args.iter()
264                .map(|arg| arg.to_string_lossy())
265                .collect::<Vec<_>>()
266                .join(" ")
267        )
268    })
269}
270
271pub(crate) fn checked<P, I, S>(program: P, args: I, cwd: Option<&Path>) -> Result<Output>
272where
273    P: AsRef<OsStr>,
274    I: IntoIterator<Item = S>,
275    S: AsRef<OsStr>,
276{
277    let program = program.as_ref();
278    let result = output(program, args, cwd)?;
279    if !result.status.success() {
280        bail!(
281            "{} failed ({})\nstdout:\n{}\nstderr:\n{}",
282            program.to_string_lossy(),
283            result.status,
284            String::from_utf8_lossy(&result.stdout).trim(),
285            String::from_utf8_lossy(&result.stderr).trim()
286        );
287    }
288    Ok(result)
289}
290
291fn read_version(program: &str) -> Result<String> {
292    let result = checked(program, ["--version"], None)?;
293    let version = String::from_utf8_lossy(&result.stdout).trim().to_owned();
294    if version.is_empty() {
295        bail!("{} --version returned no version", program);
296    }
297    Ok(version)
298}
299
300fn read_cargo_version(program: &str) -> Result<String> {
301    let program_path = cargo_program(program);
302    read_version(
303        program_path
304            .to_str()
305            .with_context(|| format!("{} path is not valid UTF-8", program_path.display()))?,
306    )
307}
308
309fn cargo_program(program: &str) -> PathBuf {
310    let cargo_home = env::var_os("CARGO_HOME")
311        .map(PathBuf::from)
312        .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".cargo")));
313    if let Some(path) = cargo_home.map(|home| home.join("bin").join(program)) {
314        if path.is_file() {
315            return path;
316        }
317    }
318    PathBuf::from(program)
319}
320
321fn require_minimum_version(output: &str, minimum: (u64, u64, u64), program: &str) -> Result<()> {
322    let raw = output
323        .split_whitespace()
324        .nth(1)
325        .with_context(|| format!("{program} --version omitted a semantic version"))?;
326    let mut parts = raw.trim_start_matches('v').split('.');
327    let found = (
328        parts.next().and_then(|value| value.parse().ok()),
329        parts.next().and_then(|value| value.parse().ok()),
330        parts.next().and_then(|value| value.parse().ok()),
331    );
332    let found = match found {
333        (Some(major), Some(minor), Some(patch)) => (major, minor, patch),
334        _ => bail!("{program} returned an invalid semantic version: {raw}"),
335    };
336    if found < minimum {
337        bail!(
338            "{program} {}.{}.{} is too old; Tambo requires at least {}.{}.{}",
339            found.0,
340            found.1,
341            found.2,
342            minimum.0,
343            minimum.1,
344            minimum.2
345        );
346    }
347    Ok(())
348}
349
350struct Quipu {
351    flavor: QuipuFlavor,
352    external: Option<(PathBuf, PathBuf)>,
353}
354
355const QUIPU_VERSION: &str = "0.9.0";
356
357/// The reviewed feature set per flavor. Both flavors build the identical
358/// pinned revision — only the feature list differs — so choosing `lancedb`
359/// can never smuggle in an unreviewed Quipu.
360fn quipu_features(flavor: QuipuFlavor) -> &'static str {
361    match flavor {
362        QuipuFlavor::Release => "full",
363        QuipuFlavor::Lancedb => "full,lancedb",
364    }
365}
366
367impl Adapter for Quipu {
368    fn package_adapter(&self) -> Result<Option<Box<dyn Adapter>>> {
369        let path = env::var_os("PATH");
370        let resolve = |name| {
371            which_all(name, path.as_deref())
372                .into_iter()
373                .next()
374                .with_context(|| format!("package Quipu requires {name} on PATH"))
375        };
376        // Keep the package-manager symlinks rather than the old Cellar targets:
377        // brew may replace both targets during this same update.
378        Ok(Some(Box::new(Self {
379            flavor: self.flavor,
380            external: Some((resolve("quipu")?, resolve("quipu-server")?)),
381        })))
382    }
383
384    fn name(&self) -> ToolName {
385        ToolName::Quipu
386    }
387
388    fn desired_version(&self) -> String {
389        match self.flavor {
390            QuipuFlavor::Release => format!("quipu {QUIPU_VERSION}; quipu-server {QUIPU_VERSION}"),
391            QuipuFlavor::Lancedb => {
392                format!("quipu {QUIPU_VERSION}; quipu-server {QUIPU_VERSION} (+lancedb)")
393            }
394        }
395    }
396
397    fn is_current(&self, _installed: &str) -> bool {
398        // version() already enforces the reviewed minimum for both binaries;
399        // a newer compatible Quipu release is not a downgrade candidate.
400        // Flavor drift is invisible here — `quipu --version` cannot say which
401        // features were compiled in — so verify() is what catches it.
402        true
403    }
404
405    fn install(&self) -> Result<()> {
406        if self.external.is_some() {
407            bail!("external Quipu is not owned by Tambo; installation refused");
408        }
409        preflight_owned_quipu_alias()?;
410        match self.flavor {
411            QuipuFlavor::Release => install_quipu_release(),
412            // The published archive is the reviewed `full` build. LanceDB is
413            // an explicit non-default flavor and still needs a source build
414            // until Quipu publishes a separately identifiable artifact.
415            QuipuFlavor::Lancedb => {
416                let mut args: Vec<OsString> = quipu_install_args(self.flavor)
417                    .iter()
418                    .map(OsString::from)
419                    .collect();
420                args.push("--root".into());
421                args.push(
422                    owned_quipu_bin()?
423                        .parent()
424                        .context("cargo bin has no root")?
425                        .as_os_str()
426                        .into(),
427                );
428                checked("cargo", args, None)?;
429                ensure_owned_quipu_alias()
430            }
431        }
432    }
433
434    fn version(&self) -> Result<String> {
435        // `cargo install` writes these binaries under CARGO_HOME, which may be
436        // later on PATH than a legacy Quipu install. Read back the location we
437        // actually update so a successful install cannot be reported as stale.
438        let client = if let Some((client, _)) = &self.external {
439            read_version(
440                client
441                    .to_str()
442                    .context("external Quipu path is not UTF-8")?,
443            )?
444        } else {
445            read_cargo_version("quipu")?
446        };
447        require_minimum_version(&client, (0, 3, 27), "quipu")?;
448        let server = if let Some((_, server)) = &self.external {
449            read_version(
450                server
451                    .to_str()
452                    .context("external server path is not UTF-8")?,
453            )?
454        } else {
455            read_cargo_version("quipu-server")?
456        };
457        require_minimum_version(&server, (0, 3, 27), "quipu-server")?;
458        Ok(match &self.external {
459            Some((c, s)) => format!(
460                "{client}; {server}; external executables: {} | {}",
461                c.display(),
462                s.display()
463            ),
464            None => format!("{client}; {server}"),
465        })
466    }
467
468    fn verify(&self) -> Result<()> {
469        let client = self
470            .external
471            .as_ref()
472            .map(|(c, _)| c.clone())
473            .map(Ok)
474            .unwrap_or_else(selected_quipu_client)?;
475        verify_quipu_alias(&client)?;
476        self.verify_core()
477    }
478}
479
480impl Quipu {
481    fn verify_core(&self) -> Result<()> {
482        if self.flavor == QuipuFlavor::Lancedb {
483            verify_quipu_lancedb_feature()?;
484        }
485        let client = self
486            .external
487            .as_ref()
488            .map(|(client, _)| client.as_path())
489            .unwrap_or_else(|| Path::new("quipu"));
490        let root = tempfile::tempdir().context("create quipu verification directory")?;
491        let db = root.path().join("verify.db");
492        let episode = root.path().join("episode.json");
493        let marker = "tambo-verify-roundtrip";
494        fs::write(
495            &episode,
496            format!(
497                r#"{{"name":"Tambo verification","episode_body":"functional round trip","source":"caboodle","group_id":"caboodle-verification","nodes":[{{"name":"{marker}","type":"Verification","description":"Tambo isolated verification"}}],"edges":[]}}"#
498            ),
499        )
500        .context("write quipu verification episode")?;
501
502        let query = format!(
503            "SELECT ?s ?label WHERE {{ ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label . FILTER(?label = \"{marker}\") }}"
504        );
505        let before = checked(
506            client,
507            [
508                OsStr::new("read"),
509                OsStr::new(&query),
510                OsStr::new("--db"),
511                db.as_os_str(),
512            ],
513            None,
514        )?;
515        if String::from_utf8_lossy(&before.stdout).contains(marker) {
516            bail!("quipu negative control unexpectedly found the verification node");
517        }
518
519        checked(
520            client,
521            [
522                OsStr::new("episode"),
523                episode.as_os_str(),
524                OsStr::new("--db"),
525                db.as_os_str(),
526            ],
527            None,
528        )?;
529        let after = checked(
530            client,
531            [
532                OsStr::new("read"),
533                OsStr::new(&query),
534                OsStr::new("--db"),
535                db.as_os_str(),
536            ],
537            None,
538        )?;
539        if !String::from_utf8_lossy(&after.stdout).contains(marker) {
540            bail!("quipu episode landed but read-back did not find the verification node");
541        }
542        // The stack's shared vocabulary rides with Quipu: the pinned Quechua
543        // release must load and resolve a term, with an absent-term control.
544        crate::vocabulary::verify_at(client).context("Quechua vocabulary verification")?;
545        Ok(())
546    }
547}
548
549/// Prove exactly the selected pair, using a throwaway client store, never a live server.
550pub(crate) fn verify_quipu_pair(client: &Path, server: &Path) -> Result<()> {
551    Quipu {
552        flavor: QuipuFlavor::Release,
553        external: Some((client.to_path_buf(), server.to_path_buf())),
554    }
555    .verify_core()?;
556    let help = checked(server, ["--help"], None)?;
557    let help = String::from_utf8_lossy(&help.stdout);
558    if !help.contains("--db") || !help.contains("--bind") {
559        bail!("Quipu server omitted isolated database/bind command contract");
560    }
561    Ok(())
562}
563
564pub(crate) fn quipu_release_target() -> Result<&'static str> {
565    quipu_release_target_for(env::consts::ARCH, env::consts::OS)
566}
567
568fn quipu_release_target_for(arch: &str, os: &str) -> Result<&'static str> {
569    match (arch, os) {
570        ("x86_64", "linux") => Ok("x86_64-unknown-linux-gnu"),
571        ("aarch64", "linux") => Ok("aarch64-unknown-linux-gnu"),
572        ("x86_64", "macos") => Ok("x86_64-apple-darwin"),
573        ("aarch64", "macos") => Ok("aarch64-apple-darwin"),
574        (arch, os) => bail!("Quipu has no checksummed Tambo release for {arch}-{os}"),
575    }
576}
577
578fn fetch_quipu_release(target: &str, download: &Path) -> Result<PathBuf> {
579    // release-please tags the crate package; the release workflow prefixes
580    // that complete tag again for both the asset and its top-level directory.
581    let tag = format!("quipu-ai-v{QUIPU_VERSION}");
582    let directory = format!("quipu-{tag}-{target}");
583    let archive_name = format!("{directory}.tar.gz");
584    let base = format!("https://github.com/scbrown/quipu/releases/download/{tag}");
585    let archive = download.join(&archive_name);
586    let checksum = download.join(format!("{archive_name}.sha256"));
587    download_https(&format!("{base}/{archive_name}"), &archive)?;
588    download_https(&format!("{base}/{archive_name}.sha256"), &checksum)?;
589    verify_checksum(&archive, &checksum)?;
590
591    let unpacked = download.join(directory);
592    checked(
593        "tar",
594        [
595            OsStr::new("-xzf"),
596            archive.as_os_str(),
597            OsStr::new("-C"),
598            download.as_os_str(),
599        ],
600        None,
601    )?;
602    for program in ["quipu", "quipu-server"] {
603        if !unpacked.join(program).is_file() {
604            bail!("Quipu release archive omitted {program}");
605        }
606    }
607    Ok(unpacked)
608}
609
610fn install_quipu_release() -> Result<()> {
611    let target = quipu_release_target()?;
612    let download = tempfile::tempdir().context("create Quipu download directory")?;
613    let unpacked = fetch_quipu_release(target, download.path())?;
614    let home = env::var_os("HOME").context("HOME is required to install Quipu")?;
615    let bin = env::var_os("CARGO_HOME")
616        .map(PathBuf::from)
617        .unwrap_or_else(|| PathBuf::from(home).join(".cargo"))
618        .join("bin");
619    fs::create_dir_all(&bin).with_context(|| format!("create {}", bin.display()))?;
620    for program in ["quipu", "quipu-server"] {
621        let source = unpacked.join(program);
622        if !source.is_file() {
623            bail!("Quipu release archive omitted {}", source.display());
624        }
625        fs::copy(&source, bin.join(program))
626            .with_context(|| format!("install checksummed Quipu binary {program}"))?;
627    }
628    ensure_owned_quipu_alias()
629}
630
631fn owned_quipu_bin() -> Result<PathBuf> {
632    env::var_os("CARGO_HOME")
633        .map(PathBuf::from)
634        .or_else(|| env::var_os("HOME").map(|h| PathBuf::from(h).join(".cargo")))
635        .map(|root| root.join("bin"))
636        .context("HOME or CARGO_HOME is required for owned Quipu installation")
637}
638
639pub(crate) fn preflight_owned_quipu_alias() -> Result<()> {
640    quipu_alias::preflight(&owned_quipu_bin()?).map_err(anyhow::Error::msg)
641}
642
643pub(crate) fn ensure_owned_quipu_alias() -> Result<()> {
644    quipu_alias::ensure(&owned_quipu_bin()?).map_err(anyhow::Error::msg)
645}
646
647/// Post-install self-healing for the owned Quipu directory only; an externally
648/// installed Quipu elsewhere is never touched (aegis-61f).
649#[cfg(unix)]
650pub fn repair_owned_quipu_alias() -> Result<String> {
651    use quipu_alias::Repair;
652    let bin = owned_quipu_bin()?;
653    let qp = bin.join("qp");
654    Ok(
655        match quipu_alias::repair(&bin).map_err(anyhow::Error::msg)? {
656            Repair::NoQuipu => format!("no owned quipu in {}; nothing to repair", bin.display()),
657            Repair::Current => format!("{} -> quipu already current", qp.display()),
658            Repair::Created => format!("created {} -> quipu", qp.display()),
659            Repair::Retargeted => format!("retargeted {} -> quipu", qp.display()),
660            Repair::ForeignPreserved => format!(
661                "{} is not a symlink; preserved it, qp NOT repaired",
662                qp.display()
663            ),
664            Repair::PackageManaged(package) => format!(
665                "quipu in {} is managed by apt (package {package}); qp left to the package",
666                bin.display()
667            ),
668        },
669    )
670}
671
672fn selected_quipu_client() -> Result<PathBuf> {
673    let owned = cargo_program("quipu");
674    if owned.is_file() {
675        return Ok(owned);
676    }
677    which_all("quipu", env::var_os("PATH").as_deref())
678        .into_iter()
679        .next()
680        .context("Quipu CLI is not on PATH")
681}
682
683pub(crate) fn ensure_existing_quipu_alias() -> Result<()> {
684    let client = selected_quipu_client()?;
685    let bin = client
686        .parent()
687        .context("selected Quipu CLI has no directory")?;
688    quipu_alias::ensure(bin).map_err(anyhow::Error::msg)
689}
690
691pub(crate) fn verify_existing_quipu_alias() -> Result<()> {
692    verify_quipu_alias(&selected_quipu_client()?)
693}
694
695fn verify_quipu_alias(client: &Path) -> Result<()> {
696    let bin = client.parent().context("Quipu CLI has no directory")?;
697    let alias = bin.join("qp");
698    let resolved = client.canonicalize()?;
699    let resolved_bin = resolved.parent().context("Quipu CLI has no directory")?;
700    // The relative link may sit beside the selected quipu or beside the file it
701    // resolves to: a package manager (Homebrew) links bin/ into its own tree,
702    // and the formula owns `qp -> quipu` there (aegis-6f1).
703    let relative =
704        |dir: &Path| fs::read_link(dir.join("qp")).ok().as_deref() == Some(Path::new("quipu"));
705    if !relative(bin) && !relative(resolved_bin) {
706        bail!(
707            "Quipu verification requires relative qp -> quipu in {}",
708            bin.display()
709        );
710    }
711    // The qp a user types (beside the selected quipu) must be the same program.
712    if alias.canonicalize().ok().as_deref() != Some(resolved.as_path()) {
713        bail!("qp and quipu do not resolve to the same executable");
714    }
715    if read_version(alias.to_str().context("qp path is not UTF-8")?)?
716        != read_version(client.to_str().context("Quipu path is not UTF-8")?)?
717    {
718        bail!("qp and quipu version outputs disagree");
719    }
720    Ok(())
721}
722
723fn quipu_install_args(flavor: QuipuFlavor) -> [&'static str; 8] {
724    [
725        "install",
726        "quipu-ai",
727        "--version",
728        QUIPU_VERSION,
729        "--locked",
730        "--features",
731        quipu_features(flavor),
732        "--bins",
733    ]
734}
735
736/// The plan asked for the lancedb flavor. `quipu --version` cannot say which
737/// features were compiled in, so ask the running server's per-feature compile
738/// map — the only read-back that can prove the flavor, as opposed to trusting
739/// that `cargo install --features lancedb` exited zero.
740fn verify_quipu_lancedb_feature() -> Result<()> {
741    let server = env::var("QUIPU_SERVER").unwrap_or_else(|_| "http://localhost:3030".to_owned());
742    let version = curl_get_json(&format!("{server}/version"))
743        .context("read the Quipu server per-feature compile map")?;
744    require_compiled_feature(&version, "lancedb")
745}
746
747fn require_compiled_feature(version: &Value, feature: &str) -> Result<()> {
748    let compiled = version
749        .get("features")
750        .and_then(Value::as_object)
751        .with_context(|| {
752            format!(
753                "Quipu /version returned no per-feature compile map; cannot prove the {feature} flavor"
754            )
755        })?;
756    if compiled.get(feature).and_then(Value::as_bool) != Some(true) {
757        bail!(
758            "the plan requires the {feature} flavor but the running Quipu was compiled without it; \
759             reinstall the reviewed revision with `cargo install quipu-ai --version {QUIPU_VERSION} \
760             --locked --features full,{feature} --bins`"
761        );
762    }
763    Ok(())
764}
765
766struct Bobbin;
767struct Yupana;
768struct DesirePath;
769
770struct Camayoc;
771const BOBBIN_VERSION: &str = "0.30.0";
772
773impl Adapter for Camayoc {
774    fn name(&self) -> ToolName {
775        ToolName::Camayoc
776    }
777
778    fn desired_version(&self) -> String {
779        format!("camayoc {CAMAYOC_REVISION}")
780    }
781
782    fn install(&self) -> Result<()> {
783        install_camayoc_bundle()
784    }
785
786    fn version(&self) -> Result<String> {
787        let revision = fs::read_to_string(camayoc_root()?.join("REVISION"))
788            .context("read installed Camayoc revision")?;
789        let revision = revision.trim();
790        if revision.is_empty() {
791            bail!("installed Camayoc revision is empty");
792        }
793        Ok(format!("camayoc {revision}"))
794    }
795
796    fn verify(&self) -> Result<()> {
797        let root = camayoc_root()?;
798        // Isolated like every other adapter (aegis-ro425e.2): bootstrap is pointed at a
799        // free localhost port inside a tempdir, so it starts its OWN quipu-server from
800        // <tempdir>/.quipu instead of loading ontology, shapes and a marker into whatever
801        // QUIPU_SERVER names. Bootstrapping the user's real server is a separate, explicit
802        // step: run the bundle's scripts/bootstrap.sh yourself.
803        let scratch = tempfile::tempdir().context("create Camayoc verification directory")?;
804        let port = free_local_port()?;
805        let server = format!("http://127.0.0.1:{port}");
806        let _guard = ScratchServer(scratch.path().join(".quipu/server.pid"));
807        let bootstrap = Command::new("bash")
808            .arg(root.join("scripts/bootstrap.sh"))
809            .current_dir(scratch.path())
810            .env("QUIPU_SERVER", &server)
811            .env("CLAUDE_PROJECT_DIR", scratch.path())
812            .env_remove("QUIPU_AUTH_TOKEN")
813            .output()
814            .context("run Camayoc bootstrap against a scratch Quipu")?;
815        if !bootstrap.status.success() {
816            bail!(
817                "Camayoc bootstrap failed against scratch Quipu {server} ({})\nstdout:\n{}\nstderr:\n{}",
818                bootstrap.status,
819                String::from_utf8_lossy(&bootstrap.stdout).trim(),
820                String::from_utf8_lossy(&bootstrap.stderr).trim()
821            );
822        }
823        if !scratch.path().join(".quipu/server.pid").exists() {
824            bail!("Camayoc bootstrap did not start a scratch Quipu at {server}; refusing to verify against a server Tambo does not own");
825        }
826        verify_camayoc_first_ingest(&root, &server)
827    }
828}
829
830/// Stops the scratch quipu-server Camayoc's bootstrap started, on every exit path.
831struct ScratchServer(PathBuf);
832
833impl Drop for ScratchServer {
834    fn drop(&mut self) {
835        if let Ok(pid) = fs::read_to_string(&self.0) {
836            let pid = pid.trim();
837            if !pid.is_empty() && pid.chars().all(|c| c.is_ascii_digit()) {
838                let _ = Command::new("kill").arg(pid).status();
839            }
840        }
841    }
842}
843
844fn free_local_port() -> Result<u16> {
845    let listener =
846        std::net::TcpListener::bind("127.0.0.1:0").context("reserve a free localhost port")?;
847    Ok(listener.local_addr()?.port())
848}
849
850impl Adapter for Bobbin {
851    fn name(&self) -> ToolName {
852        ToolName::Bobbin
853    }
854
855    fn desired_version(&self) -> String {
856        format!("bobbin {BOBBIN_VERSION}")
857    }
858
859    fn is_current(&self, installed: &str) -> bool {
860        installed.strip_prefix("bobbin ").is_some_and(|rest| {
861            rest == BOBBIN_VERSION || rest.starts_with(&format!("{BOBBIN_VERSION} "))
862        })
863    }
864
865    fn install(&self) -> Result<()> {
866        install_bobbin_release()
867    }
868
869    fn version(&self) -> Result<String> {
870        read_version("bobbin")
871    }
872
873    fn verify(&self) -> Result<()> {
874        let root = tempfile::tempdir().context("create bobbin verification repository")?;
875        let nonce = SystemTime::now()
876            .duration_since(UNIX_EPOCH)
877            .context("system clock predates Unix epoch")?
878            .as_nanos();
879        let repo = format!("tambo-verify-{}-{nonce}", std::process::id());
880        let marker = format!("tambo_verify_marker_{}_{nonce}", std::process::id());
881        checked("git", ["init", "--quiet"], Some(root.path()))?;
882        checked("bobbin", ["init"], Some(root.path()))?;
883        fs::write(
884            root.path().join("control.rs"),
885            "/// Proves the negative-control index is live.\npub fn tambo_control() -> usize {\n    1\n}\n",
886        )
887        .context("write bobbin negative-control fixture")?;
888        checked(
889            "bobbin",
890            [
891                "index",
892                ".",
893                "--source",
894                ".",
895                "--repo",
896                &repo,
897                "--skip-calibrate",
898            ],
899            Some(root.path()),
900        )?;
901
902        let before = checked(
903            "bobbin",
904            ["grep", &marker, "--repo", &repo, "--json"],
905            Some(root.path()),
906        )?;
907        if bobbin_result_count(&before.stdout)? != 0 {
908            bail!("bobbin negative control unexpectedly found the fixture marker");
909        }
910
911        fs::write(
912            root.path().join("fixture.rs"),
913            format!(
914                "/// A unique Tambo verification routine.\npub fn {marker}() -> &'static str {{\n    \"indexed\"\n}}\n"
915            ),
916        )
917        .context("write bobbin verification fixture")?;
918        checked(
919            "bobbin",
920            [
921                "index",
922                ".",
923                "--source",
924                ".",
925                "--repo",
926                &repo,
927                "--skip-calibrate",
928            ],
929            Some(root.path()),
930        )?;
931        let after = checked(
932            "bobbin",
933            ["grep", &marker, "--repo", &repo, "--json"],
934            Some(root.path()),
935        )?;
936        if bobbin_result_count(&after.stdout)? == 0 {
937            bail!("bobbin indexed the fixture but search did not return its marker");
938        }
939        Ok(())
940    }
941}
942
943const YUPANA_VERSION: &str = "0.16.2";
944
945impl Adapter for Yupana {
946    fn name(&self) -> ToolName {
947        ToolName::Yupana
948    }
949
950    fn desired_version(&self) -> String {
951        format!("yupana {YUPANA_VERSION}")
952    }
953
954    fn install(&self) -> Result<()> {
955        let (target, checksum) = yupana_release_for(env::consts::ARCH, env::consts::OS)?;
956        let root = tempfile::tempdir().context("create Yupana download directory")?;
957        fetch_yupana_release(target, checksum, root.path())?;
958        let home = env::var_os("HOME").context("HOME is required to install Yupana")?;
959        let bin = env::var_os("CARGO_HOME")
960            .map(PathBuf::from)
961            .unwrap_or_else(|| PathBuf::from(home).join(".cargo"))
962            .join("bin");
963        fs::create_dir_all(&bin).with_context(|| format!("create {}", bin.display()))?;
964        fs::copy(root.path().join("yupana"), bin.join("yupana"))
965            .context("install checksummed Yupana binary")?;
966        Ok(())
967    }
968
969    fn version(&self) -> Result<String> {
970        let version = read_version("yupana")?;
971        require_minimum_version(&version, (0, 6, 4), "yupana")?;
972        Ok(version)
973    }
974
975    fn verify(&self) -> Result<()> {
976        let root = tempfile::tempdir().context("create Yupana verification repository")?;
977        let state = root.path().join("state");
978        fs::write(
979            root.path().join("control.rs"),
980            "pub fn tambo_yupana_control() -> usize { 1 }\n",
981        )?;
982        yupana_checked(root.path(), &state, ["analyze", "."])?;
983        let before = yupana_checked(root.path(), &state, ["callers", "tambo_yupana_target", "."])?;
984        if String::from_utf8_lossy(&before.stdout).contains("tambo_yupana_caller") {
985            bail!("Yupana negative control unexpectedly found the fixture caller");
986        }
987        fs::write(
988            root.path().join("fixture.rs"),
989            "pub fn tambo_yupana_target() -> usize { 1 }\npub fn tambo_yupana_caller() -> usize { tambo_yupana_target() }\n",
990        )?;
991        yupana_checked(root.path(), &state, ["analyze", "."])?;
992        let after = yupana_checked(root.path(), &state, ["callers", "tambo_yupana_target", "."])?;
993        if !String::from_utf8_lossy(&after.stdout).contains("tambo_yupana_caller") {
994            bail!("Yupana analyzed the fixture but callers did not return its caller");
995        }
996        Ok(())
997    }
998}
999
1000fn yupana_release_target() -> Result<&'static str> {
1001    yupana_release_for(env::consts::ARCH, env::consts::OS).map(|(target, _)| target)
1002}
1003
1004// Digests of the published v0.12.7 archives, verified against SHA256SUMS.
1005fn yupana_release_for(arch: &str, os: &str) -> Result<(&'static str, &'static str)> {
1006    match (arch, os) {
1007        ("x86_64", "linux") => Ok((
1008            "x86_64-linux-gnu",
1009            "565507459d3d67b2cc73b6ebd91f784f0522689c5b62257a8fde82793580dc5d",
1010        )),
1011        ("aarch64", "macos") => Ok((
1012            "aarch64-apple-darwin",
1013            "9f3682c6f4dffd7365248ae2d686e9fcdca26ba08ebd915f8ce692e8111179a2",
1014        )),
1015        ("x86_64", "macos") => Ok((
1016            "x86_64-apple-darwin",
1017            "7763d171c7f6e2df395bdf9961a79991b66b4876c3394ce970d1f3e2cddcb4ed",
1018        )),
1019        _ => bail!("Yupana v{YUPANA_VERSION} has no checksummed Tambo release for {arch}-{os}"),
1020    }
1021}
1022
1023fn fetch_yupana_release(target: &str, checksum: &str, root: &Path) -> Result<()> {
1024    let archive_name = format!("yupana-v{YUPANA_VERSION}-{target}.tar.gz");
1025    let archive = root.join(&archive_name);
1026    download_https(
1027        &format!(
1028            "https://github.com/scbrown/yupana/releases/download/v{YUPANA_VERSION}/{archive_name}"
1029        ),
1030        &archive,
1031    )?;
1032    verify_yupana_checksum(&archive, checksum)?;
1033    checked(
1034        "tar",
1035        [
1036            OsStr::new("-xzf"),
1037            archive.as_os_str(),
1038            OsStr::new("-C"),
1039            root.as_os_str(),
1040        ],
1041        None,
1042    )?;
1043    Ok(())
1044}
1045
1046fn verify_yupana_checksum(archive: &Path, expected: &str) -> Result<()> {
1047    if manifest::sha256_file(archive)? != expected {
1048        bail!("Yupana release checksum mismatch");
1049    }
1050    Ok(())
1051}
1052
1053fn yupana_checked<I, S>(cwd: &Path, state: &Path, args: I) -> Result<Output>
1054where
1055    I: IntoIterator<Item = S>,
1056    S: AsRef<OsStr>,
1057{
1058    let home = cwd.join("home");
1059    fs::create_dir_all(&home)?;
1060    let mut command = Command::new("yupana");
1061    command
1062        .args(args)
1063        .current_dir(cwd)
1064        .env("HOME", home)
1065        .env("XDG_STATE_HOME", state);
1066    let result = command
1067        .output()
1068        .context("run isolated Yupana verification")?;
1069    if !result.status.success() {
1070        bail!(
1071            "isolated Yupana verification failed ({}): {}",
1072            result.status,
1073            String::from_utf8_lossy(&result.stderr).trim()
1074        );
1075    }
1076    Ok(result)
1077}
1078
1079// Review and install the executable the user's shell actually selects. CARGO_HOME
1080// must not silently override a different dp on PATH (aegis-fnp1wp).
1081fn desire_path_program() -> Result<PathBuf> {
1082    if let Some(path) = env::var_os("PATH") {
1083        for directory in env::split_paths(&path) {
1084            let candidate = directory.join("dp");
1085            if candidate.is_file() {
1086                #[cfg(unix)]
1087                {
1088                    use std::os::unix::fs::PermissionsExt;
1089                    if candidate.metadata()?.permissions().mode() & 0o111 == 0 {
1090                        continue;
1091                    }
1092                }
1093                return fs::canonicalize(candidate).context("resolve Desire Path executable");
1094            }
1095        }
1096    }
1097    let home = env::var_os("HOME").context("HOME is required to install Desire Path")?;
1098    Ok(PathBuf::from(home).join(".local/bin/dp"))
1099}
1100
1101const DESIRE_PATH_REVISION: &str = "06812336fda6a6fd3fe4cbcae2d50a303e95a024";
1102const DESIRE_PATH_VERSION: &str = "v0.10.0";
1103
1104impl Adapter for DesirePath {
1105    fn name(&self) -> ToolName {
1106        ToolName::DesirePath
1107    }
1108
1109    fn desired_version(&self) -> String {
1110        format!("dp {DESIRE_PATH_VERSION} ({})", &DESIRE_PATH_REVISION[..7])
1111    }
1112
1113    fn is_current(&self, installed: &str) -> bool {
1114        let expected = self.desired_version();
1115        installed.trim_start_matches("dp ").trim_start_matches('v')
1116            == expected.trim_start_matches("dp ").trim_start_matches('v')
1117    }
1118
1119    fn install(&self) -> Result<()> {
1120        let executable = desire_path_program()?;
1121        let bin = executable
1122            .parent()
1123            .context("Desire Path needs an install directory")?;
1124        fs::create_dir_all(bin).with_context(|| format!("create {}", bin.display()))?;
1125        let ldflags = format!(
1126            "-X github.com/scbrown/desire-path/internal/cli.Version={DESIRE_PATH_VERSION} -X github.com/scbrown/desire-path/internal/cli.Commit={DESIRE_PATH_REVISION}"
1127        );
1128        let mut command = Command::new("go");
1129        command
1130            .args([
1131                "install",
1132                "-ldflags",
1133                &ldflags,
1134                &format!("github.com/scbrown/desire-path/cmd/dp@{DESIRE_PATH_REVISION}"),
1135            ])
1136            .env("GOBIN", bin);
1137        let result = command
1138            .output()
1139            .context("build pinned Desire Path revision")?;
1140        if !result.status.success() {
1141            bail!(
1142                "Desire Path install failed ({}): {}",
1143                result.status,
1144                String::from_utf8_lossy(&result.stderr).trim()
1145            );
1146        }
1147        Ok(())
1148    }
1149
1150    fn version(&self) -> Result<String> {
1151        let result = checked(desire_path_program()?, ["version"], None)?;
1152        let version = String::from_utf8_lossy(&result.stdout).trim().to_owned();
1153        // Identity only, like every other adapter: `is_current` and package
1154        // `standing` judge it against the pin. Refusing here made a brew-owned
1155        // dp that is AHEAD of the pin unreadable, so the member failed (aegis-fv4).
1156        if version.is_empty() {
1157            bail!("dp version returned no version");
1158        }
1159        Ok(version)
1160    }
1161
1162    fn verify(&self) -> Result<()> {
1163        let dp = desire_path_program()?;
1164        let root = tempfile::tempdir().context("create Desire Path verification directory")?;
1165        let db = root.path().join("desires.db");
1166        let marker = "tambo_desire_path_marker";
1167        let before = checked(
1168            &dp,
1169            [
1170                "--db",
1171                db.to_str().context("Desire Path DB path is not UTF-8")?,
1172                "--json",
1173                "list",
1174            ],
1175            Some(root.path()),
1176        )?;
1177        if String::from_utf8_lossy(&before.stdout).contains(marker) {
1178            bail!("Desire Path negative control unexpectedly found the marker");
1179        }
1180        let mut child = Command::new(&dp)
1181            .args([
1182                "--db",
1183                db.to_str().unwrap(),
1184                "ingest",
1185                "--source",
1186                "claude-code",
1187            ])
1188            .current_dir(root.path())
1189            .stdin(std::process::Stdio::piped())
1190            .stdout(std::process::Stdio::piped())
1191            .stderr(std::process::Stdio::piped())
1192            .spawn()
1193            .context("start Desire Path ingest verification")?;
1194        use std::io::Write as _;
1195        child
1196            .stdin
1197            .take()
1198            .context("open Desire Path verification stdin")?
1199            .write_all(
1200                format!(r#"{{"tool_name":"{marker}","error":"fixture failure"}}"#).as_bytes(),
1201            )?;
1202        let ingested = child.wait_with_output()?;
1203        if !ingested.status.success() {
1204            bail!(
1205                "Desire Path ingest verification failed ({}): {}",
1206                ingested.status,
1207                String::from_utf8_lossy(&ingested.stderr).trim()
1208            );
1209        }
1210        let after = checked(
1211            &dp,
1212            ["--db", db.to_str().unwrap(), "--json", "list"],
1213            Some(root.path()),
1214        )?;
1215        if !String::from_utf8_lossy(&after.stdout).contains(marker) {
1216            bail!("Desire Path ingested the fixture but its reader path did not return it");
1217        }
1218        Ok(())
1219    }
1220}
1221
1222fn bobbin_result_count(stdout: &[u8]) -> Result<u64> {
1223    let response: serde_json::Value =
1224        serde_json::from_slice(stdout).context("parse bobbin search JSON")?;
1225    response["count"]
1226        .as_u64()
1227        .context("bobbin search JSON omitted numeric count")
1228}
1229
1230fn bobbin_release_target() -> Result<&'static str> {
1231    match (env::consts::ARCH, env::consts::OS) {
1232        ("x86_64", "linux") => Ok("x86_64-unknown-linux-gnu"),
1233        ("aarch64", "linux") => Ok("aarch64-unknown-linux-gnu"),
1234        ("x86_64", "macos") => Ok("x86_64-apple-darwin"),
1235        ("aarch64", "macos") => Ok("aarch64-apple-darwin"),
1236        (arch, os) => bail!("bobbin has no Tambo release target for {arch}-{os}"),
1237    }
1238}
1239
1240fn install_bobbin_release() -> Result<()> {
1241    let target = bobbin_release_target()?;
1242    let archive = format!("bobbin-v{BOBBIN_VERSION}-{target}.tar.gz");
1243    let base = format!("https://github.com/scbrown/bobbin/releases/download/v{BOBBIN_VERSION}");
1244    let download = tempfile::tempdir().context("create bobbin download directory")?;
1245    let archive_path = download.path().join(&archive);
1246    let sums_path = download.path().join("SHA256SUMS.txt");
1247    download_https(&format!("{base}/{archive}"), &archive_path)?;
1248    download_https(&format!("{base}/SHA256SUMS.txt"), &sums_path)?;
1249    verify_checksum(&archive_path, &sums_path)?;
1250
1251    let home = env::var_os("HOME").context("HOME is required to install bobbin")?;
1252    let install_root = PathBuf::from(&home)
1253        .join(".local/share/caboodle/bobbin")
1254        .join(format!("v{BOBBIN_VERSION}"));
1255    fs::create_dir_all(&install_root)
1256        .with_context(|| format!("create bobbin install root {}", install_root.display()))?;
1257    checked(
1258        "tar",
1259        [
1260            OsStr::new("-xzf"),
1261            archive_path.as_os_str(),
1262            OsStr::new("--strip-components=1"),
1263            OsStr::new("-C"),
1264            install_root.as_os_str(),
1265        ],
1266        None,
1267    )?;
1268
1269    let bin_dir = env::var_os("CARGO_HOME")
1270        .map(PathBuf::from)
1271        .unwrap_or_else(|| PathBuf::from(home).join(".cargo"))
1272        .join("bin");
1273    fs::create_dir_all(&bin_dir)
1274        .with_context(|| format!("create binary directory {}", bin_dir.display()))?;
1275    let link = bin_dir.join("bobbin");
1276    let target = install_root.join("bobbin");
1277    ensure_bobbin_link(&link, &target)?;
1278    Ok(())
1279}
1280
1281fn ensure_bobbin_link(link: &Path, target: &Path) -> Result<()> {
1282    if !target.is_file() {
1283        bail!("Bobbin release archive omitted {}", target.display());
1284    }
1285    match link.symlink_metadata() {
1286        Ok(metadata)
1287            if metadata.file_type().is_symlink()
1288                && fs::read_link(link).ok().as_deref() == Some(target) =>
1289        {
1290            return Ok(());
1291        }
1292        // A DANGLING symlink is Tambo's own debris, not a user's install, and
1293        // refusing to repair it deadlocks the tool against itself.
1294        //
1295        // Measured on Tambo CI, red on main 2026-08-31 -> 2026-09-02, one job,
1296        // every run:
1297        //
1298        //     bobbin: not installed (run bobbin --version:
1299        //             No such file or directory (os error 2)); installing
1300        //     Error: bobbin install step
1301        //     Caused by: refusing to replace existing
1302        //                /home/runner/.cargo/bin/bobbin; remove or repair it explicitly
1303        //
1304        // Those two lines are the SAME fact seen from two sides. Executing a
1305        // symlink whose target is gone fails with ENOENT, which is exactly why the
1306        // probe a moment earlier concluded bobbin was not installed — so the
1307        // installer refuses to repair the very condition that summoned it. The
1308        // state is then permanent: never detected as present, never allowed to be
1309        // written. Nothing a re-run can do changes it.
1310        //
1311        // The refusal is right for anything a person could still be using — a real
1312        // binary, a directory, a symlink that resolves. A dangling link is none of
1313        // those: following it is an error for every reader, so there is no working
1314        // installation here to protect.
1315        Ok(metadata) if metadata.file_type().is_symlink() && !link.exists() => {
1316            fs::remove_file(link).with_context(|| format!("remove dangling {}", link.display()))?;
1317        }
1318        Ok(_) => {
1319            bail!(
1320                "refusing to replace existing {}; preserve it at a new backup path such as {}.before-tambo, then rerun apply; see Installing > Replacing a cargo-installed Bobbin for backup and rollback commands",
1321                link.display(),
1322                link.display()
1323            );
1324        }
1325        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1326        Err(error) => return Err(error).with_context(|| format!("inspect {}", link.display())),
1327    }
1328    #[cfg(unix)]
1329    std::os::unix::fs::symlink(target, link)
1330        .with_context(|| format!("link bobbin into {}", link.display()))?;
1331    #[cfg(not(unix))]
1332    bail!("bobbin release installation currently requires a Unix host");
1333    Ok(())
1334}
1335
1336const CAMAYOC_REVISION: &str = "f443bf19974d06ab662c8ae3deeccfbb1e082f48";
1337const CAMAYOC_ARCHIVE_SHA256: &str =
1338    "67b1945615d811ac3c0251412d6b5d619f00d58a7ca87785474c0f1db46ba544";
1339
1340pub(crate) fn camayoc_root() -> Result<PathBuf> {
1341    if let Some(path) = env::var_os("CABOODLE_CAMAYOC_ROOT") {
1342        return Ok(PathBuf::from(path));
1343    }
1344    let home = env::var_os("HOME").context("HOME is required to install Camayoc")?;
1345    Ok(PathBuf::from(home)
1346        .join(".local/share/caboodle/camayoc")
1347        .join(CAMAYOC_REVISION))
1348}
1349
1350fn install_camayoc_bundle() -> Result<()> {
1351    let root = camayoc_root()?;
1352    if root.join("REVISION").exists() {
1353        return Ok(());
1354    }
1355    let download = tempfile::tempdir().context("create Camayoc download directory")?;
1356    let archive = download.path().join("camayoc.tar.gz");
1357    download_https(
1358        &format!("https://github.com/intigraph/camayoc/archive/{CAMAYOC_REVISION}.tar.gz"),
1359        &archive,
1360    )?;
1361    let digest = checked("sha256sum", [archive.as_os_str()], None)?;
1362    let digest = String::from_utf8_lossy(&digest.stdout);
1363    if digest.split_whitespace().next() != Some(CAMAYOC_ARCHIVE_SHA256) {
1364        bail!("Camayoc archive checksum mismatch");
1365    }
1366    fs::create_dir_all(&root)
1367        .with_context(|| format!("create Camayoc install root {}", root.display()))?;
1368    checked(
1369        "tar",
1370        [
1371            OsStr::new("-xzf"),
1372            archive.as_os_str(),
1373            OsStr::new("--strip-components=1"),
1374            OsStr::new("-C"),
1375            root.as_os_str(),
1376        ],
1377        None,
1378    )?;
1379    fs::write(root.join("REVISION"), format!("{CAMAYOC_REVISION}\n"))
1380        .context("write installed Camayoc revision")?;
1381    Ok(())
1382}
1383
1384fn verify_camayoc_first_ingest(root: &Path, server: &str) -> Result<()> {
1385    let namespace = camayoc_aegis_namespace(&root.join("ontology/core.ttl"))?;
1386    let control = "tambo-camayoc-control-must-stay-absent";
1387    let marker = "tambo-camayoc-first-ingest-v1";
1388
1389    if label_count(server, &namespace, control)? != 0 {
1390        bail!("Camayoc negative control unexpectedly exists");
1391    }
1392
1393    let turtle = format!(
1394        "@prefix aegis: <{namespace}> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\
1395         aegis:{marker} a aegis:Verification ; rdfs:label \"{marker}\" ; \
1396         aegis:sourceKind \"observed\" ; aegis:falsifier \"the marker remains absent after ingest\" .\n"
1397    );
1398    let payload = json!({
1399        "turtle": turtle,
1400        "actor": "caboodle",
1401        "source": "Tambo Camayoc first-ingest verification"
1402    });
1403    if label_count(server, &namespace, marker)? == 0 {
1404        let first = curl_json(&format!("{server}/knot"), &payload)?;
1405        if first.get("count").and_then(Value::as_u64).unwrap_or(0) == 0 {
1406            bail!("Camayoc first ingest wrote no triples");
1407        }
1408    }
1409    if label_count(server, &namespace, marker)? == 0 {
1410        bail!("Camayoc first ingest was not retrievable");
1411    }
1412    curl_json(&format!("{server}/knot"), &payload)?;
1413    if label_count(server, &namespace, marker)? != 1 {
1414        bail!("Camayoc idempotent replay wrote duplicate triples");
1415    }
1416    Ok(())
1417}
1418
1419pub(crate) fn camayoc_aegis_namespace(path: &Path) -> Result<String> {
1420    let body = fs::read_to_string(path)
1421        .with_context(|| format!("read Camayoc ontology {}", path.display()))?;
1422    body.lines()
1423        .find_map(|line| {
1424            line.trim()
1425                .strip_prefix("@prefix aegis: <")
1426                .and_then(|rest| rest.strip_suffix("> ."))
1427                .map(str::to_owned)
1428        })
1429        .context("Camayoc ontology does not declare the aegis namespace")
1430}
1431
1432fn label_count(server: &str, namespace: &str, label: &str) -> Result<u64> {
1433    let query = format!(
1434        "SELECT ?s WHERE {{ ?s <http://www.w3.org/2000/01/rdf-schema#label> \"{label}\" . FILTER(STRSTARTS(STR(?s), \"{namespace}\")) }}"
1435    );
1436    let response = curl_json(&format!("{server}/query"), &json!({"query": query}))?;
1437    response["count"]
1438        .as_u64()
1439        .context("Quipu query response omitted numeric count")
1440}
1441
1442pub(crate) fn curl_json(url: &str, payload: &Value) -> Result<Value> {
1443    curl_json_request(url, Some(payload.to_string()))
1444}
1445
1446fn curl_get_json(url: &str) -> Result<Value> {
1447    curl_json_request(url, None)
1448}
1449
1450/// The curl config line carrying `QUIPU_AUTH_TOKEN`, in a temp file so the token
1451/// never reaches argv. curl parses a quoted config value with backslash
1452/// escapes, so `\` and `"` are escaped; a newline would end the line and let
1453/// the token inject a second directive, so it is refused rather than escaped.
1454fn quipu_auth_config() -> Result<Option<tempfile::NamedTempFile>> {
1455    crate::quipu_auth::config()
1456}
1457
1458pub(crate) fn curl_auth_header_line(token: &str) -> Result<String> {
1459    if token.contains(['\n', '\r']) {
1460        bail!("QUIPU_AUTH_TOKEN contains a line break; refusing to pass it to curl");
1461    }
1462    let escaped = token.replace('\\', "\\\\").replace('"', "\\\"");
1463    Ok(format!("header = \"Authorization: Bearer {escaped}\"\n"))
1464}
1465
1466/// POST an empty body to `/episode` with the caller's token and return the HTTP
1467/// status and body. Quipu checks the bearer before it parses the episode, so an
1468/// accepted token yields a validation error (400) and NOTHING is written, while a
1469/// missing or rejected token yields 401. That makes it an authenticated no-op:
1470/// the only way to prove the write path without writing (aegis-0c1qdi). The
1471/// token travels in a curl config file, never on the command line.
1472pub(crate) fn quipu_write_probe(server: &str) -> Result<(u16, String, bool)> {
1473    let body_file = tempfile::NamedTempFile::new().context("create write-probe body file")?;
1474    let auth = quipu_auth_config()?;
1475    let mut args: Vec<OsString> = [
1476        "--silent",
1477        "--max-time",
1478        "5",
1479        "--request",
1480        "POST",
1481        "--header",
1482        "Content-Type: application/json",
1483        "--data",
1484        "{}",
1485        "--write-out",
1486        "%{http_code}",
1487        "--output",
1488    ]
1489    .iter()
1490    .map(OsString::from)
1491    .collect();
1492    args.push(body_file.path().as_os_str().to_owned());
1493    if let Some(file) = &auth {
1494        args.push(OsString::from("--config"));
1495        args.push(file.path().as_os_str().to_owned());
1496    }
1497    args.push(OsString::from(format!(
1498        "{}/episode",
1499        server.trim_end_matches('/')
1500    )));
1501    let result = output("curl", args, None)?;
1502    let code = String::from_utf8_lossy(&result.stdout)
1503        .trim()
1504        .parse::<u16>()
1505        .unwrap_or(0);
1506    let body = fs::read_to_string(body_file.path()).unwrap_or_default();
1507    Ok((code, body, auth.is_some()))
1508}
1509
1510fn curl_json_request(url: &str, body: Option<String>) -> Result<Value> {
1511    let auth = quipu_auth_config()?;
1512    let mut args = vec![
1513        OsString::from("--fail"),
1514        OsString::from("--silent"),
1515        OsString::from("--show-error"),
1516    ];
1517    if let Some(body) = body {
1518        args.extend([
1519            OsString::from("--request"),
1520            OsString::from("POST"),
1521            OsString::from("--header"),
1522            OsString::from("Content-Type: application/json"),
1523            OsString::from("--data"),
1524            OsString::from(body),
1525        ]);
1526    }
1527    if let Some(file) = &auth {
1528        args.push(OsString::from("--config"));
1529        args.push(file.path().as_os_str().to_owned());
1530    }
1531    args.push(OsString::from(url));
1532    let result = checked("curl", args, None)?;
1533    serde_json::from_slice(&result.stdout)
1534        .with_context(|| format!("parse JSON response from {url}"))
1535}
1536
1537pub(crate) fn download_https(url: &str, destination: &Path) -> Result<()> {
1538    // Retry only the GET, never its checksum or installation step. A blanket
1539    // curl --retry-all-errors would also retry a missing asset or bad local path.
1540    const ATTEMPTS: u32 = 3;
1541    for attempt in 1..=ATTEMPTS {
1542        // A failed/partial response must not become the next attempt's input,
1543        // or replace a previously downloaded artifact when retries run out.
1544        let pending = tempfile::NamedTempFile::new_in(
1545            destination
1546                .parent()
1547                .filter(|p| !p.as_os_str().is_empty())
1548                .unwrap_or(Path::new(".")),
1549        )
1550        .context("create pending download")?;
1551        let result = output(
1552            "curl",
1553            [
1554                OsStr::new("--disable"),
1555                OsStr::new("--fail"),
1556                OsStr::new("--location"),
1557                OsStr::new("--silent"),
1558                OsStr::new("--show-error"),
1559                OsStr::new("--proto"),
1560                OsStr::new("=https"),
1561                OsStr::new("--tlsv1.2"),
1562                OsStr::new("--connect-timeout"),
1563                OsStr::new("10"),
1564                OsStr::new("--max-time"),
1565                OsStr::new("120"),
1566                OsStr::new("--write-out"),
1567                OsStr::new("%{http_code}"),
1568                OsStr::new("--output"),
1569                pending.path().as_os_str(),
1570                OsStr::new(url),
1571            ],
1572            None,
1573        )?;
1574        if result.status.success() {
1575            pending
1576                .persist(destination)
1577                .context("publish downloaded artifact")?;
1578            if attempt > 1 {
1579                eprintln!("download {url}: succeeded on attempt {attempt}/{ATTEMPTS}");
1580            }
1581            return Ok(());
1582        }
1583        let http = String::from_utf8_lossy(&result.stdout)
1584            .trim()
1585            .parse::<u16>()
1586            .unwrap_or(0);
1587        let detail = format!(
1588            "download {url}: attempt {attempt}/{ATTEMPTS}, curl {}, HTTP {http:03}: {}",
1589            result.status,
1590            String::from_utf8_lossy(&result.stderr).trim()
1591        );
1592        if !retryable_download(result.status.code(), http) {
1593            bail!("{detail}; terminal failure (not retried)");
1594        }
1595        if attempt == ATTEMPTS {
1596            bail!("{detail}; retry limit exhausted");
1597        }
1598        let delay = 1 << (attempt - 1);
1599        eprintln!("{detail}; retrying in {delay}s");
1600        drop(pending);
1601        std::thread::sleep(std::time::Duration::from_secs(delay));
1602    }
1603    unreachable!("every final attempt returns")
1604}
1605
1606fn retryable_download(code: Option<i32>, http: u16) -> bool {
1607    // An observed client error wins even when reading its body timed out.
1608    if (400..500).contains(&http) {
1609        return false;
1610    }
1611    match code {
1612        Some(22) => (500..600).contains(&http),
1613        // curl transport errors: proxy/DNS resolution, connect, partial body,
1614        // timeout, empty reply, send/receive and HTTP/2 stream failures.
1615        Some(5 | 6 | 7 | 18 | 28 | 52 | 55 | 56 | 92) => true,
1616        // Certificate, local I/O, invocation and unknown errors stay fatal.
1617        _ => false,
1618    }
1619}
1620
1621fn verify_checksum(archive: &Path, sums: &Path) -> Result<()> {
1622    let filename = archive
1623        .file_name()
1624        .and_then(OsStr::to_str)
1625        .context("bobbin archive filename is not UTF-8")?;
1626    let expected = fs::read_to_string(sums)
1627        .context("read Bobbin checksum manifest")?
1628        .lines()
1629        .find_map(|line| {
1630            let mut fields = line.split_whitespace();
1631            let digest = fields.next()?;
1632            let listed = fields.next()?.trim_start_matches('*');
1633            (listed == filename).then(|| digest.to_owned())
1634        })
1635        .with_context(|| format!("checksum manifest does not cover {filename}"))?;
1636    let actual = checked("sha256sum", [archive.as_os_str()], None)?;
1637    let actual = String::from_utf8_lossy(&actual.stdout)
1638        .split_whitespace()
1639        .next()
1640        .context("sha256sum returned no digest")?
1641        .to_owned();
1642    if actual != expected {
1643        bail!("checksum mismatch for {filename}");
1644    }
1645    Ok(())
1646}
1647
1648#[cfg(test)]
1649mod yupana_release_tests {
1650    use super::*;
1651
1652    #[test]
1653    fn published_platforms_resolve_and_missing_platforms_refuse() {
1654        for (arch, os, target) in [
1655            ("x86_64", "linux", "x86_64-linux-gnu"),
1656            ("aarch64", "macos", "aarch64-apple-darwin"),
1657            ("x86_64", "macos", "x86_64-apple-darwin"),
1658        ] {
1659            assert_eq!(yupana_release_for(arch, os).unwrap().0, target);
1660        }
1661        assert!(yupana_release_for("aarch64", "linux").is_err());
1662        assert!(yupana_release_for("x86_64", "windows").is_err());
1663        assert!(!prerequisites(ToolName::Yupana, QuipuFlavor::Release).contains(&"sha256sum"));
1664    }
1665
1666    #[test]
1667    fn checksum_refuses_corruption_without_an_external_hash_command() {
1668        let root = tempfile::tempdir().unwrap();
1669        let file = root.path().join("archive");
1670        fs::write(&file, b"abc").unwrap();
1671        let expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
1672        verify_yupana_checksum(&file, expected).unwrap();
1673        fs::write(&file, b"abd").unwrap();
1674        assert!(verify_yupana_checksum(&file, expected).is_err());
1675    }
1676
1677    #[test]
1678    #[ignore = "downloads all three published archives; explicit release acceptance"]
1679    fn real_yupana_archives_match_pins_and_unpack() {
1680        for (arch, os) in [
1681            ("x86_64", "linux"),
1682            ("aarch64", "macos"),
1683            ("x86_64", "macos"),
1684        ] {
1685            let (target, checksum) = yupana_release_for(arch, os).unwrap();
1686            let root = tempfile::tempdir().unwrap();
1687            fetch_yupana_release(target, checksum, root.path()).unwrap();
1688            assert!(root.path().join("yupana").is_file());
1689            assert_eq!(
1690                fs::read_link(root.path().join("hank")).unwrap(),
1691                Path::new("yupana")
1692            );
1693            eprintln!("verified published {target}: {checksum}");
1694        }
1695    }
1696}
1697
1698#[cfg(test)]
1699mod flavor_tests {
1700    use super::{
1701        fetch_quipu_release, quipu_install_args, quipu_release_target, quipu_release_target_for,
1702        require_compiled_feature,
1703    };
1704    use crate::model::QuipuFlavor;
1705    use serde_json::json;
1706
1707    #[test]
1708    fn install_args_add_only_the_lancedb_feature_to_the_reviewed_pin() {
1709        let release = quipu_install_args(QuipuFlavor::Release);
1710        let lancedb = quipu_install_args(QuipuFlavor::Lancedb);
1711        assert_eq!(release[6], "full");
1712        assert_eq!(lancedb[6], "full,lancedb");
1713        // Everything but the feature list must be identical, so the lancedb
1714        // flavor stays pinned to the same reviewed revision.
1715        assert_eq!(release[..6], lancedb[..6]);
1716        assert_eq!(release[7..], lancedb[7..]);
1717        assert!(release.contains(&"--locked"));
1718    }
1719
1720    #[test]
1721    fn default_quipu_release_has_a_supported_host_artifact() {
1722        if (std::env::consts::ARCH, std::env::consts::OS) == ("x86_64", "linux") {
1723            assert_eq!(quipu_release_target().unwrap(), "x86_64-unknown-linux-gnu");
1724        }
1725    }
1726
1727    #[test]
1728    fn quipu_release_supports_published_linux_and_macos_architectures() {
1729        for (arch, os, target) in [
1730            ("x86_64", "linux", "x86_64-unknown-linux-gnu"),
1731            ("aarch64", "linux", "aarch64-unknown-linux-gnu"),
1732            ("x86_64", "macos", "x86_64-apple-darwin"),
1733            ("aarch64", "macos", "aarch64-apple-darwin"),
1734        ] {
1735            assert_eq!(quipu_release_target_for(arch, os).unwrap(), target);
1736        }
1737        assert!(quipu_release_target_for("x86_64", "windows").is_err());
1738    }
1739
1740    #[test]
1741    #[ignore = "downloads published artifacts; explicit release acceptance only"]
1742    fn real_aarch64_quipu_release_resolves_and_verifies() {
1743        for os in ["macos", "linux"] {
1744            let target = quipu_release_target_for("aarch64", os).unwrap();
1745            let download = tempfile::tempdir().unwrap();
1746            let unpacked = fetch_quipu_release(target, download.path()).unwrap();
1747            assert!(unpacked.join("quipu").is_file());
1748            assert!(unpacked.join("quipu-server").is_file());
1749            eprintln!("verified published Quipu checksums and both binaries for {target}");
1750        }
1751    }
1752
1753    #[test]
1754    fn compile_map_proof_requires_a_true_lancedb_entry() {
1755        require_compiled_feature(&json!({"features": {"lancedb": true}}), "lancedb").unwrap();
1756
1757        let absent = require_compiled_feature(&json!({"features": {"onnx": true}}), "lancedb")
1758            .unwrap_err()
1759            .to_string();
1760        assert!(absent.contains("compiled without it"), "{absent}");
1761
1762        let disabled =
1763            require_compiled_feature(&json!({"features": {"lancedb": false}}), "lancedb")
1764                .unwrap_err()
1765                .to_string();
1766        assert!(disabled.contains("compiled without it"), "{disabled}");
1767
1768        // A server too old to report the map proves nothing; that is a
1769        // refusal, not a pass.
1770        let unmapped = require_compiled_feature(&json!({"version": "0.3.27"}), "lancedb")
1771            .unwrap_err()
1772            .to_string();
1773        assert!(
1774            unmapped.contains("no per-feature compile map"),
1775            "{unmapped}"
1776        );
1777    }
1778}
1779
1780#[cfg(all(test, unix))]
1781mod tests {
1782    use super::ensure_bobbin_link;
1783    use std::{fs, os::unix::fs::symlink};
1784
1785    #[test]
1786    fn failed_commands_preserve_both_diagnostic_streams_and_status() {
1787        for script in [
1788            "printf 'bootstrap rejected'; exit 2",
1789            "printf 'bootstrap rejected' >&2; exit 2",
1790            "printf 'probe started'; printf 'bootstrap rejected' >&2; exit 2",
1791            "exit 2",
1792        ] {
1793            let error = super::checked("sh", ["-c", script], None)
1794                .unwrap_err()
1795                .to_string();
1796            assert!(error.contains("exit status: 2"), "{error}");
1797            assert!(error.contains("stdout:\n"), "{error}");
1798            assert!(error.contains("stderr:\n"), "{error}");
1799            if script.contains("bootstrap rejected") {
1800                assert!(error.contains("bootstrap rejected"), "{error}");
1801            }
1802            if script.contains("probe started") {
1803                assert!(error.contains("probe started"), "{error}");
1804            }
1805        }
1806        let output = super::checked("sh", ["-c", "printf 'successful output'"], None).unwrap();
1807        assert_eq!(output.stdout, b"successful output");
1808    }
1809
1810    #[test]
1811    fn bobbin_link_accepts_its_restored_cache_entry_but_refuses_foreign_paths() {
1812        let root = tempfile::tempdir().unwrap();
1813        let target = root.path().join("release/bobbin");
1814        fs::create_dir_all(target.parent().unwrap()).unwrap();
1815        fs::write(&target, "binary fixture").unwrap();
1816
1817        let link = root.path().join("bin/bobbin");
1818        fs::create_dir_all(link.parent().unwrap()).unwrap();
1819        symlink(&target, &link).unwrap();
1820        ensure_bobbin_link(&link, &target).unwrap();
1821        assert_eq!(fs::read_link(&link).unwrap(), target);
1822
1823        let foreign = root.path().join("foreign");
1824        fs::write(&foreign, "do not replace").unwrap();
1825        fs::remove_file(&link).unwrap();
1826        symlink(&foreign, &link).unwrap();
1827        let error = ensure_bobbin_link(&link, &target).unwrap_err().to_string();
1828        assert!(error.contains("refusing to replace existing"));
1829        assert_eq!(fs::read_link(&link).unwrap(), foreign);
1830    }
1831
1832    #[test]
1833    fn bobbin_link_repairs_its_own_dangling_link_but_still_refuses_a_real_file() {
1834        // The CI deadlock, both arms. A dangling link makes `bobbin --version`
1835        // fail with ENOENT, so the probe reports "not installed" and calls the
1836        // installer -- which then refused to touch it. Never present, never
1837        // writable, and no re-run could break the tie.
1838        let root = tempfile::tempdir().unwrap();
1839        let target = root.path().join("release/bobbin");
1840        fs::create_dir_all(target.parent().unwrap()).unwrap();
1841        fs::write(&target, "binary fixture").unwrap();
1842        let link = root.path().join("bin/bobbin");
1843        fs::create_dir_all(link.parent().unwrap()).unwrap();
1844
1845        symlink(root.path().join("gone/bobbin"), &link).unwrap();
1846        assert!(link.symlink_metadata().is_ok(), "the link itself exists");
1847        assert!(
1848            !link.exists(),
1849            "but it resolves to nothing -- this is the ENOENT"
1850        );
1851        ensure_bobbin_link(&link, &target).unwrap();
1852        assert_eq!(fs::read_link(&link).unwrap(), target);
1853
1854        // and the repair must not have widened into "replace whatever is there":
1855        // a REGULAR FILE is somebody's binary and is still refused.
1856        fs::remove_file(&link).unwrap();
1857        fs::write(&link, "a real bobbin somebody installed").unwrap();
1858        let error = ensure_bobbin_link(&link, &target).unwrap_err().to_string();
1859        assert!(error.contains("refusing to replace existing"));
1860        assert_eq!(
1861            fs::read_to_string(&link).unwrap(),
1862            "a real bobbin somebody installed"
1863        );
1864    }
1865}
1866
1867#[cfg(test)]
1868mod auth_config_tests {
1869    use super::curl_auth_header_line;
1870
1871    #[test]
1872    fn curl_auth_line_escapes_quotes_and_refuses_line_breaks() {
1873        assert_eq!(
1874            curl_auth_header_line("abc").unwrap(),
1875            "header = \"Authorization: Bearer abc\"\n"
1876        );
1877        assert_eq!(
1878            curl_auth_header_line(r#"a"b\c"#).unwrap(),
1879            "header = \"Authorization: Bearer a\\\"b\\\\c\"\n"
1880        );
1881        // A newline would end the config line and let the token add a directive.
1882        assert!(curl_auth_header_line("tok\nurl = \"http://elsewhere\"").is_err());
1883        assert!(curl_auth_header_line("tok\r").is_err());
1884    }
1885}
1886
1887/// Verify one embedded release member without installing it.
1888pub fn verify_member(name: &str) -> Result<()> {
1889    let member = crate::members::get(name).context("unknown reviewed member")?;
1890    manifest::verify_release_member(member)
1891}
1892
1893#[cfg(all(test, unix))]
1894mod quipu_alias_layout_tests {
1895    use super::verify_quipu_alias;
1896    use std::os::unix::fs::symlink;
1897    use std::{fs, path::Path};
1898
1899    fn script(path: &Path, version: &str) {
1900        crate::test_exec::write_executable(path, &format!("#!/bin/sh\necho '{version}'\n"));
1901    }
1902
1903    #[test]
1904    fn package_managed_layout_passes_with_qp_beside_the_resolved_quipu() {
1905        // Homebrew: bin/quipu and bin/qp link into the Cellar, where the
1906        // formula owns the relative qp -> quipu.
1907        let root = tempfile::tempdir().unwrap();
1908        let cellar = root.path().join("Cellar/quipu/1.0/bin");
1909        let bin = root.path().join("bin");
1910        fs::create_dir_all(&cellar).unwrap();
1911        fs::create_dir(&bin).unwrap();
1912        script(&cellar.join("quipu"), "quipu 1.0");
1913        symlink("quipu", cellar.join("qp")).unwrap();
1914        symlink("../Cellar/quipu/1.0/bin/quipu", bin.join("quipu")).unwrap();
1915        symlink("../Cellar/quipu/1.0/bin/qp", bin.join("qp")).unwrap();
1916        verify_quipu_alias(&bin.join("quipu")).unwrap();
1917    }
1918
1919    #[test]
1920    fn a_qp_for_another_program_or_no_qp_still_fails() {
1921        let root = tempfile::tempdir().unwrap();
1922        let bin = root.path().join("bin");
1923        fs::create_dir(&bin).unwrap();
1924        script(&bin.join("quipu"), "quipu 1.0");
1925        let err = verify_quipu_alias(&bin.join("quipu")).unwrap_err();
1926        assert!(err.to_string().contains("requires relative qp -> quipu"));
1927        // A relative link exists beside the resolved file, but the qp on PATH
1928        // is a different program: refuse.
1929        let cellar = root.path().join("Cellar/bin");
1930        fs::create_dir_all(&cellar).unwrap();
1931        script(&cellar.join("quipu"), "quipu 1.0");
1932        symlink("quipu", cellar.join("qp")).unwrap();
1933        script(&root.path().join("other"), "quipu 1.0");
1934        let pkg = root.path().join("pkgbin");
1935        fs::create_dir(&pkg).unwrap();
1936        symlink("../Cellar/bin/quipu", pkg.join("quipu")).unwrap();
1937        symlink("../other", pkg.join("qp")).unwrap();
1938        let err = verify_quipu_alias(&pkg.join("quipu")).unwrap_err();
1939        assert!(err.to_string().contains("same executable"));
1940    }
1941
1942    #[test]
1943    fn owned_layout_with_qp_beside_quipu_still_passes() {
1944        let root = tempfile::tempdir().unwrap();
1945        script(&root.path().join("quipu"), "quipu 1.0");
1946        symlink("quipu", root.path().join("qp")).unwrap();
1947        verify_quipu_alias(&root.path().join("quipu")).unwrap();
1948    }
1949}