1use 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, hermetic_via, identify_member, prove_release, release_target, single_program,
21 stage, verify_at,
22};
23
24pub trait Adapter {
25 fn name(&self) -> ToolName;
26 fn desired_version(&self) -> String;
28 fn install(&self) -> Result<()>;
29 fn version(&self) -> Result<String>;
30 fn verify(&self) -> Result<()>;
31
32 fn package_adapter(&self) -> Result<Option<Box<dyn Adapter>>> {
36 Ok(None)
37 }
38
39 fn is_current(&self, installed: &str) -> bool {
40 installed == self.desired_version()
41 }
42}
43
44pub fn release_blocker(name: ToolName, quipu_flavor: QuipuFlavor) -> Option<String> {
48 let result = match name {
49 ToolName::Quipu if quipu_flavor == QuipuFlavor::Release => quipu_release_target(),
50 ToolName::Bobbin => bobbin_release_target(),
51 ToolName::Yupana => yupana_release_target(),
52 ToolName::Member(name) => match crate::members::get(name) {
53 Some(m) => manifest::release_target(m),
54 None => return Some(format!("unknown stack member {name}")),
55 },
56 ToolName::Quipu | ToolName::Camayoc | ToolName::DesirePath => return None,
60 };
61 result.err().map(|error| format!("{error:#}"))
62}
63
64pub fn prerequisites(name: ToolName, quipu_flavor: QuipuFlavor) -> &'static [&'static str] {
66 match name {
67 ToolName::Quipu if quipu_flavor == QuipuFlavor::Lancedb => &["cargo"],
68 ToolName::Quipu => &["curl", "tar"],
69 ToolName::Camayoc => &["curl", "tar", "bash", "python3"],
73 ToolName::Bobbin => &["curl", "tar", "git"],
74 ToolName::Yupana => &["curl", "tar"],
75 ToolName::DesirePath => &["go"],
76 ToolName::Member(name) => crate::members::prerequisites(name),
77 }
78}
79
80pub fn source_install_command(name: ToolName) -> Option<String> {
82 match name {
83 ToolName::Quipu => Some(format!("cargo {}", quipu_install_args(QuipuFlavor::Release).join(" "))),
84 ToolName::Yupana => Some(format!(
85 "cargo install --git https://github.com/scbrown/yupana --tag v{YUPANA_VERSION} --locked --features mcp"
86 )),
87 ToolName::Camayoc | ToolName::Bobbin | ToolName::DesirePath | ToolName::Member(_) => None,
89 }
90}
91
92pub fn programs(name: ToolName) -> &'static [&'static str] {
94 match name {
95 ToolName::Quipu => &["qp", "quipu", "quipu-server"],
96 ToolName::Camayoc => &[],
97 ToolName::Bobbin => &["bobbin"],
98 ToolName::Yupana => &["yupana"],
99 ToolName::DesirePath => &["dp"],
100 ToolName::Member(name) => crate::members::programs(name),
101 }
102}
103
104pub fn which_all(program: &str, path: Option<&std::ffi::OsStr>) -> Vec<PathBuf> {
106 let Some(path) = path else {
107 return Vec::new();
108 };
109 let mut found: Vec<PathBuf> = Vec::new();
110 let mut targets: Vec<PathBuf> = Vec::new();
111 for candidate in env::split_paths(path).map(|directory| directory.join(program)) {
112 if !is_executable(&candidate) {
113 continue;
114 }
115 let target = candidate
118 .canonicalize()
119 .unwrap_or_else(|_| candidate.clone());
120 if !targets.contains(&target) {
121 targets.push(target);
122 found.push(candidate);
123 }
124 }
125 found
126}
127
128pub(crate) fn is_executable(path: &Path) -> bool {
129 let Ok(metadata) = path.metadata() else {
130 return false;
131 };
132 if !metadata.is_file() {
133 return false;
134 }
135 #[cfg(unix)]
136 {
137 use std::os::unix::fs::PermissionsExt;
138 metadata.permissions().mode() & 0o111 != 0
139 }
140 #[cfg(not(unix))]
141 true
142}
143
144#[derive(Debug, PartialEq, Eq)]
152pub enum PathResolution {
153 Managed,
155 NotOnPath,
157 SameBuild { runs: PathBuf, managed: PathBuf },
159 Shadowed {
161 runs: PathBuf,
162 runs_version: String,
163 managed: PathBuf,
164 managed_version: String,
165 },
166}
167
168pub fn path_resolution(program: &str, path: Option<&OsStr>) -> PathResolution {
170 let Some(managed) = managed_bin_dir().map(|dir| dir.join(program)) else {
171 return PathResolution::Managed;
172 };
173 if !is_executable(&managed) {
174 return PathResolution::Managed;
175 }
176 let Some(runs) = which_all(program, path).into_iter().next() else {
177 return PathResolution::NotOnPath;
178 };
179 let canonical = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
180 if canonical(&runs) == canonical(&managed) {
181 return PathResolution::Managed;
182 }
183 let version = |p: &Path| {
184 p.to_str()
185 .and_then(|s| read_version(s).ok())
186 .unwrap_or_else(|| "unreadable".to_owned())
187 };
188 let (runs_version, managed_version) = (version(&runs), version(&managed));
189 if runs_version == managed_version {
190 PathResolution::SameBuild { runs, managed }
191 } else {
192 PathResolution::Shadowed {
193 runs,
194 runs_version,
195 managed,
196 managed_version,
197 }
198 }
199}
200
201pub fn managed_bin_dir() -> Option<PathBuf> {
203 env::var_os("CARGO_HOME")
204 .map(PathBuf::from)
205 .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".cargo")))
206 .map(|home| home.join("bin"))
207}
208
209pub fn adapter(name: ToolName, quipu_flavor: QuipuFlavor) -> Box<dyn Adapter> {
210 match name {
211 ToolName::Quipu => Box::new(Quipu {
212 flavor: quipu_flavor,
213 external: None,
214 }),
215 ToolName::Camayoc => Box::new(Camayoc),
216 ToolName::Bobbin => Box::new(Bobbin),
217 ToolName::Yupana => Box::new(Yupana),
218 ToolName::DesirePath => Box::new(DesirePath),
219 ToolName::Member(name) => Box::new(manifest::ManifestAdapter(
220 crate::members::get(name)
221 .expect("a Member name is only minted for an embedded manifest"),
222 )),
223 }
224}
225
226pub fn adapter_for_plan(name: ToolName, plan: &crate::model::Plan) -> Result<Box<dyn Adapter>> {
228 if name != ToolName::Quipu || !plan.external_quipu {
229 return Ok(adapter(name, plan.quipu_flavor));
230 }
231 let path = env::var_os("PATH");
232 let resolve = |name| -> Result<PathBuf> {
233 which_all(name, path.as_deref())
234 .into_iter()
235 .next()
236 .with_context(|| format!("external Quipu requires {name} on PATH"))?
237 .canonicalize()
238 .with_context(|| format!("resolve external {name}"))
239 };
240 Ok(Box::new(Quipu {
241 flavor: plan.quipu_flavor,
242 external: Some((resolve("quipu")?, resolve("quipu-server")?)),
243 }))
244}
245
246fn output<P, I, S>(program: P, args: I, cwd: Option<&Path>) -> Result<Output>
247where
248 P: AsRef<OsStr>,
249 I: IntoIterator<Item = S>,
250 S: AsRef<OsStr>,
251{
252 let args: Vec<OsString> = args
253 .into_iter()
254 .map(|arg| arg.as_ref().to_os_string())
255 .collect();
256 let program = program.as_ref();
257 let mut command = Command::new(program);
258 command.args(&args);
259 if let Some(cwd) = cwd {
260 command.current_dir(cwd);
261 }
262 command.output().with_context(|| {
263 format!(
264 "run {} {}",
265 program.to_string_lossy(),
266 args.iter()
267 .map(|arg| arg.to_string_lossy())
268 .collect::<Vec<_>>()
269 .join(" ")
270 )
271 })
272}
273
274pub(crate) fn checked<P, I, S>(program: P, args: I, cwd: Option<&Path>) -> Result<Output>
275where
276 P: AsRef<OsStr>,
277 I: IntoIterator<Item = S>,
278 S: AsRef<OsStr>,
279{
280 let program = program.as_ref();
281 let result = output(program, args, cwd)?;
282 if !result.status.success() {
283 bail!(
284 "{} failed ({})\nstdout:\n{}\nstderr:\n{}",
285 program.to_string_lossy(),
286 result.status,
287 String::from_utf8_lossy(&result.stdout).trim(),
288 String::from_utf8_lossy(&result.stderr).trim()
289 );
290 }
291 Ok(result)
292}
293
294fn read_version(program: &str) -> Result<String> {
295 let result = checked(program, ["--version"], None)?;
296 let version = String::from_utf8_lossy(&result.stdout).trim().to_owned();
297 if version.is_empty() {
298 bail!("{} --version returned no version", program);
299 }
300 Ok(version)
301}
302
303fn read_cargo_version(program: &str) -> Result<String> {
304 let program_path = cargo_program(program);
305 read_version(
306 program_path
307 .to_str()
308 .with_context(|| format!("{} path is not valid UTF-8", program_path.display()))?,
309 )
310}
311
312fn cargo_program(program: &str) -> PathBuf {
313 let cargo_home = env::var_os("CARGO_HOME")
314 .map(PathBuf::from)
315 .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".cargo")));
316 if let Some(path) = cargo_home.map(|home| home.join("bin").join(program)) {
317 if path.is_file() {
318 return path;
319 }
320 }
321 PathBuf::from(program)
322}
323
324fn require_minimum_version(output: &str, minimum: (u64, u64, u64), program: &str) -> Result<()> {
325 let raw = output
326 .split_whitespace()
327 .nth(1)
328 .with_context(|| format!("{program} --version omitted a semantic version"))?;
329 let mut parts = raw.trim_start_matches('v').split('.');
330 let found = (
331 parts.next().and_then(|value| value.parse().ok()),
332 parts.next().and_then(|value| value.parse().ok()),
333 parts.next().and_then(|value| value.parse().ok()),
334 );
335 let found = match found {
336 (Some(major), Some(minor), Some(patch)) => (major, minor, patch),
337 _ => bail!("{program} returned an invalid semantic version: {raw}"),
338 };
339 if found < minimum {
340 bail!(
341 "{program} {}.{}.{} is too old; Tambo requires at least {}.{}.{}",
342 found.0,
343 found.1,
344 found.2,
345 minimum.0,
346 minimum.1,
347 minimum.2
348 );
349 }
350 Ok(())
351}
352
353struct Quipu {
354 flavor: QuipuFlavor,
355 external: Option<(PathBuf, PathBuf)>,
356}
357
358const QUIPU_VERSION: crate::builtin_pins::Pin =
359 crate::builtin_pins::Pin(|| &crate::builtin_pins::pin("quipu").version);
360
361fn quipu_features(flavor: QuipuFlavor) -> &'static str {
365 match flavor {
366 QuipuFlavor::Release => "full",
367 QuipuFlavor::Lancedb => "full,lancedb",
368 }
369}
370
371impl Adapter for Quipu {
372 fn package_adapter(&self) -> Result<Option<Box<dyn Adapter>>> {
373 let path = env::var_os("PATH");
374 let resolve = |name| {
375 which_all(name, path.as_deref())
376 .into_iter()
377 .next()
378 .with_context(|| format!("package Quipu requires {name} on PATH"))
379 };
380 Ok(Some(Box::new(Self {
383 flavor: self.flavor,
384 external: Some((resolve("quipu")?, resolve("quipu-server")?)),
385 })))
386 }
387
388 fn name(&self) -> ToolName {
389 ToolName::Quipu
390 }
391
392 fn desired_version(&self) -> String {
393 match self.flavor {
394 QuipuFlavor::Release => format!("quipu {QUIPU_VERSION}; quipu-server {QUIPU_VERSION}"),
395 QuipuFlavor::Lancedb => {
396 format!("quipu {QUIPU_VERSION}; quipu-server {QUIPU_VERSION} (+lancedb)")
397 }
398 }
399 }
400
401 fn is_current(&self, _installed: &str) -> bool {
402 true
407 }
408
409 fn install(&self) -> Result<()> {
410 if self.external.is_some() {
411 bail!("external Quipu is not owned by Tambo; installation refused");
412 }
413 preflight_owned_quipu_alias()?;
414 match self.flavor {
415 QuipuFlavor::Release => install_quipu_release(),
416 QuipuFlavor::Lancedb => {
420 let mut args: Vec<OsString> = quipu_install_args(self.flavor)
421 .iter()
422 .map(OsString::from)
423 .collect();
424 args.push("--root".into());
425 args.push(
426 owned_quipu_bin()?
427 .parent()
428 .context("cargo bin has no root")?
429 .as_os_str()
430 .into(),
431 );
432 checked("cargo", args, None)?;
433 ensure_owned_quipu_alias()
434 }
435 }
436 }
437
438 fn version(&self) -> Result<String> {
439 let client = if let Some((client, _)) = &self.external {
443 read_version(
444 client
445 .to_str()
446 .context("external Quipu path is not UTF-8")?,
447 )?
448 } else {
449 read_cargo_version("quipu")?
450 };
451 require_minimum_version(&client, (0, 3, 27), "quipu")?;
452 let server = if let Some((_, server)) = &self.external {
453 read_version(
454 server
455 .to_str()
456 .context("external server path is not UTF-8")?,
457 )?
458 } else {
459 read_cargo_version("quipu-server")?
460 };
461 require_minimum_version(&server, (0, 3, 27), "quipu-server")?;
462 Ok(match &self.external {
463 Some((c, s)) => format!(
464 "{client}; {server}; external executables: {} | {}",
465 c.display(),
466 s.display()
467 ),
468 None => format!("{client}; {server}"),
469 })
470 }
471
472 fn verify(&self) -> Result<()> {
473 let client = self
474 .external
475 .as_ref()
476 .map(|(c, _)| c.clone())
477 .map(Ok)
478 .unwrap_or_else(selected_quipu_client)?;
479 verify_quipu_alias(&client)?;
480 self.verify_core()
481 }
482}
483
484impl Quipu {
485 fn verify_core(&self) -> Result<()> {
486 if self.flavor == QuipuFlavor::Lancedb {
487 verify_quipu_lancedb_feature()?;
488 }
489 let client = self
490 .external
491 .as_ref()
492 .map(|(client, _)| client.as_path())
493 .unwrap_or_else(|| Path::new("quipu"));
494 let root = tempfile::tempdir().context("create quipu verification directory")?;
495 let db = root.path().join("verify.db");
496 let episode = root.path().join("episode.json");
497 let marker = "tambo-verify-roundtrip";
498 fs::write(
499 &episode,
500 format!(
501 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":[]}}"#
502 ),
503 )
504 .context("write quipu verification episode")?;
505
506 let query = format!(
507 "SELECT ?s ?label WHERE {{ ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label . FILTER(?label = \"{marker}\") }}"
508 );
509 let before = checked(
510 client,
511 [
512 OsStr::new("read"),
513 OsStr::new(&query),
514 OsStr::new("--db"),
515 db.as_os_str(),
516 ],
517 None,
518 )?;
519 if String::from_utf8_lossy(&before.stdout).contains(marker) {
520 bail!("quipu negative control unexpectedly found the verification node");
521 }
522
523 checked(
524 client,
525 [
526 OsStr::new("episode"),
527 episode.as_os_str(),
528 OsStr::new("--base-ns"),
529 OsStr::new("https://example.org/tambo/verification/"),
530 OsStr::new("--db"),
531 db.as_os_str(),
532 ],
533 None,
534 )?;
535 let after = checked(
536 client,
537 [
538 OsStr::new("read"),
539 OsStr::new(&query),
540 OsStr::new("--db"),
541 db.as_os_str(),
542 ],
543 None,
544 )?;
545 if !String::from_utf8_lossy(&after.stdout).contains(marker) {
546 bail!("quipu episode landed but read-back did not find the verification node");
547 }
548 crate::vocabulary::verify_at(client).context("Quechua vocabulary verification")?;
551 Ok(())
552 }
553}
554
555pub(crate) fn verify_quipu_pair(client: &Path, server: &Path) -> Result<()> {
557 Quipu {
558 flavor: QuipuFlavor::Release,
559 external: Some((client.to_path_buf(), server.to_path_buf())),
560 }
561 .verify_core()?;
562 let help = checked(server, ["--help"], None)?;
563 let help = String::from_utf8_lossy(&help.stdout);
564 if !help.contains("--db") || !help.contains("--bind") {
565 bail!("Quipu server omitted isolated database/bind command contract");
566 }
567 Ok(())
568}
569
570pub(crate) fn quipu_release_target() -> Result<&'static str> {
571 quipu_release_target_for(env::consts::ARCH, env::consts::OS)
572}
573
574fn quipu_release_target_for(arch: &str, os: &str) -> Result<&'static str> {
575 match (arch, os) {
576 ("x86_64", "linux") => Ok("x86_64-unknown-linux-gnu"),
577 ("aarch64", "linux") => Ok("aarch64-unknown-linux-gnu"),
578 ("x86_64", "macos") => Ok("x86_64-apple-darwin"),
579 ("aarch64", "macos") => Ok("aarch64-apple-darwin"),
580 (arch, os) => bail!("Quipu has no checksummed Tambo release for {arch}-{os}"),
581 }
582}
583
584fn fetch_quipu_release(target: &str, download: &Path) -> Result<PathBuf> {
585 let tag = format!("quipu-ai-v{QUIPU_VERSION}");
588 let directory = format!("quipu-{tag}-{target}");
589 let archive_name = format!("{directory}.tar.gz");
590 let base = format!("https://github.com/scbrown/quipu/releases/download/{tag}");
591 let archive = download.join(&archive_name);
592 let checksum = download.join(format!("{archive_name}.sha256"));
593 download_https(&format!("{base}/{archive_name}"), &archive)?;
594 download_https(&format!("{base}/{archive_name}.sha256"), &checksum)?;
595 verify_checksum(&archive, &checksum)?;
596
597 let unpacked = download.join(directory);
598 checked(
599 "tar",
600 [
601 OsStr::new("-xzf"),
602 archive.as_os_str(),
603 OsStr::new("-C"),
604 download.as_os_str(),
605 ],
606 None,
607 )?;
608 for program in ["quipu", "quipu-server"] {
609 if !unpacked.join(program).is_file() {
610 bail!("Quipu release archive omitted {program}");
611 }
612 }
613 if !fs::symlink_metadata(unpacked.join("quipu"))?
614 .file_type()
615 .is_file()
616 {
617 bail!("Quipu primary archive executable must be regular");
618 }
619 crate::quipu_layout::alias(&unpacked.join("quipu-server"))?;
620 Ok(unpacked)
621}
622
623fn install_quipu_release() -> Result<()> {
624 let target = quipu_release_target()?;
625 let download = tempfile::tempdir().context("create Quipu download directory")?;
626 let unpacked = fetch_quipu_release(target, download.path())?;
627 let home = env::var_os("HOME").context("HOME is required to install Quipu")?;
628 let bin = env::var_os("CARGO_HOME")
629 .map(PathBuf::from)
630 .unwrap_or_else(|| PathBuf::from(home).join(".cargo"))
631 .join("bin");
632 fs::create_dir_all(&bin).with_context(|| format!("create {}", bin.display()))?;
633 let unified = crate::quipu_layout::alias(&unpacked.join("quipu-server"))?.is_some();
636 for program in if unified {
637 &["quipu"][..]
638 } else {
639 &["quipu", "quipu-server"][..]
640 } {
641 crate::quipu_layout::replace_regular(&unpacked.join(program), &bin.join(program))?;
642 }
643 if unified {
644 crate::quipu_layout::replace_alias(&bin.join("quipu-server"))?;
645 }
646 ensure_owned_quipu_alias()
647}
648
649fn owned_quipu_bin() -> Result<PathBuf> {
650 env::var_os("CARGO_HOME")
651 .map(PathBuf::from)
652 .or_else(|| env::var_os("HOME").map(|h| PathBuf::from(h).join(".cargo")))
653 .map(|root| root.join("bin"))
654 .context("HOME or CARGO_HOME is required for owned Quipu installation")
655}
656
657pub(crate) fn preflight_owned_quipu_alias() -> Result<()> {
658 quipu_alias::preflight(&owned_quipu_bin()?).map_err(anyhow::Error::msg)
659}
660
661pub(crate) fn ensure_owned_quipu_alias() -> Result<()> {
662 quipu_alias::ensure(&owned_quipu_bin()?).map_err(anyhow::Error::msg)
663}
664
665#[cfg(unix)]
668pub fn repair_owned_quipu_alias() -> Result<String> {
669 use quipu_alias::Repair;
670 let bin = owned_quipu_bin()?;
671 let qp = bin.join("qp");
672 Ok(
673 match quipu_alias::repair(&bin).map_err(anyhow::Error::msg)? {
674 Repair::NoQuipu => format!("no owned quipu in {}; nothing to repair", bin.display()),
675 Repair::Current => format!("{} -> quipu already current", qp.display()),
676 Repair::Created => format!("created {} -> quipu", qp.display()),
677 Repair::Retargeted => format!("retargeted {} -> quipu", qp.display()),
678 Repair::ForeignPreserved => format!(
679 "{} is not a symlink; preserved it, qp NOT repaired",
680 qp.display()
681 ),
682 Repair::PackageManaged(package) => format!(
683 "quipu in {} is managed by apt (package {package}); qp left to the package",
684 bin.display()
685 ),
686 },
687 )
688}
689
690fn selected_quipu_client() -> Result<PathBuf> {
691 let owned = cargo_program("quipu");
692 if owned.is_file() {
693 return Ok(owned);
694 }
695 which_all("quipu", env::var_os("PATH").as_deref())
696 .into_iter()
697 .next()
698 .context("Quipu CLI is not on PATH")
699}
700
701pub(crate) fn ensure_existing_quipu_alias() -> Result<()> {
702 let client = selected_quipu_client()?;
703 let bin = client
704 .parent()
705 .context("selected Quipu CLI has no directory")?;
706 quipu_alias::ensure(bin).map_err(anyhow::Error::msg)
707}
708
709pub(crate) fn verify_existing_quipu_alias() -> Result<()> {
710 verify_quipu_alias(&selected_quipu_client()?)
711}
712
713fn verify_quipu_alias(client: &Path) -> Result<()> {
714 let bin = client.parent().context("Quipu CLI has no directory")?;
715 let alias = bin.join("qp");
716 let resolved = client.canonicalize()?;
717 let resolved_bin = resolved.parent().context("Quipu CLI has no directory")?;
718 let relative =
722 |dir: &Path| fs::read_link(dir.join("qp")).ok().as_deref() == Some(Path::new("quipu"));
723 if !relative(bin) && !relative(resolved_bin) {
724 bail!(
725 "Quipu verification requires relative qp -> quipu in {}",
726 bin.display()
727 );
728 }
729 if alias.canonicalize().ok().as_deref() != Some(resolved.as_path()) {
731 bail!("qp and quipu do not resolve to the same executable");
732 }
733 if read_version(alias.to_str().context("qp path is not UTF-8")?)?
734 != read_version(client.to_str().context("Quipu path is not UTF-8")?)?
735 {
736 bail!("qp and quipu version outputs disagree");
737 }
738 Ok(())
739}
740
741fn quipu_install_args(flavor: QuipuFlavor) -> [&'static str; 8] {
742 [
743 "install",
744 "quipu-ai",
745 "--version",
746 &QUIPU_VERSION,
747 "--locked",
748 "--features",
749 quipu_features(flavor),
750 "--bins",
751 ]
752}
753
754fn verify_quipu_lancedb_feature() -> Result<()> {
759 let server = env::var("QUIPU_SERVER").unwrap_or_else(|_| "http://localhost:3030".to_owned());
760 let version = curl_get_json(&format!("{server}/version"))
761 .context("read the Quipu server per-feature compile map")?;
762 require_compiled_feature(&version, "lancedb")
763}
764
765fn require_compiled_feature(version: &Value, feature: &str) -> Result<()> {
766 let compiled = version
767 .get("features")
768 .and_then(Value::as_object)
769 .with_context(|| {
770 format!(
771 "Quipu /version returned no per-feature compile map; cannot prove the {feature} flavor"
772 )
773 })?;
774 if compiled.get(feature).and_then(Value::as_bool) != Some(true) {
775 bail!(
776 "the plan requires the {feature} flavor but the running Quipu was compiled without it; \
777 reinstall the reviewed revision with `cargo install quipu-ai --version {QUIPU_VERSION} \
778 --locked --features full,{feature} --bins`"
779 );
780 }
781 Ok(())
782}
783
784struct Bobbin;
785struct Yupana;
786struct DesirePath;
787
788struct Camayoc;
789const BOBBIN_VERSION: crate::builtin_pins::Pin =
790 crate::builtin_pins::Pin(|| &crate::builtin_pins::pin("bobbin").version);
791
792impl Adapter for Camayoc {
793 fn name(&self) -> ToolName {
794 ToolName::Camayoc
795 }
796
797 fn desired_version(&self) -> String {
798 format!("camayoc {CAMAYOC_REVISION}")
799 }
800
801 fn install(&self) -> Result<()> {
802 install_camayoc_bundle()
803 }
804
805 fn version(&self) -> Result<String> {
806 let revision = fs::read_to_string(camayoc_root()?.join("REVISION"))
807 .context("read installed Camayoc revision")?;
808 let revision = revision.trim();
809 if revision.is_empty() {
810 bail!("installed Camayoc revision is empty");
811 }
812 Ok(format!("camayoc {revision}"))
813 }
814
815 fn verify(&self) -> Result<()> {
816 let root = camayoc_root()?;
817 let scratch = tempfile::tempdir().context("create Camayoc verification directory")?;
823 let port = free_local_port()?;
824 let server = format!("http://127.0.0.1:{port}");
825 let _guard = ScratchServer(scratch.path().join(".quipu/server.pid"));
826 let home = scratch.path().join("home");
827 fs::create_dir(&home).context("create Camayoc verification HOME")?;
828 let bootstrap = Command::new("bash")
829 .arg(root.join("scripts/bootstrap.sh"))
830 .current_dir(scratch.path())
831 .env("QUIPU_SERVER", &server)
832 .env("CLAUDE_PROJECT_DIR", scratch.path())
833 .env("HOME", &home)
834 .env_remove("XDG_CONFIG_HOME")
835 .env_remove("CLAUDE_CONFIG_DIR")
836 .env_remove("QUIPU_AUTH_TOKEN_FILE")
837 .env_remove("QUIPU_AUTH_TOKEN")
838 .output()
839 .context("run Camayoc bootstrap against a scratch Quipu")?;
840 if !bootstrap.status.success() {
841 bail!(
842 "Camayoc bootstrap failed against scratch Quipu {server} ({})\nstdout:\n{}\nstderr:\n{}",
843 bootstrap.status,
844 String::from_utf8_lossy(&bootstrap.stdout).trim(),
845 String::from_utf8_lossy(&bootstrap.stderr).trim()
846 );
847 }
848 if !scratch.path().join(".quipu/server.pid").exists() {
849 bail!("Camayoc bootstrap did not start a scratch Quipu at {server}; refusing to verify against a server Tambo does not own");
850 }
851 let token = fs::read_to_string(home.join(".config/quipu/token"))
852 .context("read scratch Camayoc credential")?;
853 if token.trim().is_empty() {
854 bail!("scratch Camayoc credential is empty");
855 }
856 let auth = tempfile::NamedTempFile::new_in(scratch.path())
857 .context("create scratch Camayoc curl config")?;
858 fs::write(auth.path(), curl_auth_header_line(token.trim())?)
859 .context("write scratch Camayoc curl config")?;
860 verify_camayoc_first_ingest(&root, &server, auth.path())
861 }
862}
863
864struct ScratchServer(PathBuf);
866
867impl Drop for ScratchServer {
868 fn drop(&mut self) {
869 if let Ok(pid) = fs::read_to_string(&self.0) {
870 let pid = pid.trim();
871 if !pid.is_empty() && pid.chars().all(|c| c.is_ascii_digit()) {
872 let _ = Command::new("kill").arg(pid).status();
873 }
874 }
875 }
876}
877
878fn free_local_port() -> Result<u16> {
879 let listener =
880 std::net::TcpListener::bind("127.0.0.1:0").context("reserve a free localhost port")?;
881 Ok(listener.local_addr()?.port())
882}
883
884impl Adapter for Bobbin {
885 fn name(&self) -> ToolName {
886 ToolName::Bobbin
887 }
888
889 fn desired_version(&self) -> String {
890 format!("bobbin {BOBBIN_VERSION}")
891 }
892
893 fn is_current(&self, installed: &str) -> bool {
894 installed.strip_prefix("bobbin ").is_some_and(|rest| {
895 rest == BOBBIN_VERSION || rest.starts_with(&format!("{BOBBIN_VERSION} "))
896 })
897 }
898
899 fn install(&self) -> Result<()> {
900 install_bobbin_release()
901 }
902
903 fn version(&self) -> Result<String> {
904 read_version("bobbin")
905 }
906
907 fn verify(&self) -> Result<()> {
908 let root = tempfile::tempdir().context("create bobbin verification repository")?;
909 let nonce = SystemTime::now()
910 .duration_since(UNIX_EPOCH)
911 .context("system clock predates Unix epoch")?
912 .as_nanos();
913 let repo = format!("tambo-verify-{}-{nonce}", std::process::id());
914 let marker = format!("tambo_verify_marker_{}_{nonce}", std::process::id());
915 checked("git", ["init", "--quiet"], Some(root.path()))?;
916 checked("bobbin", ["init"], Some(root.path()))?;
917 fs::write(
918 root.path().join("control.rs"),
919 "/// Proves the negative-control index is live.\npub fn tambo_control() -> usize {\n 1\n}\n",
920 )
921 .context("write bobbin negative-control fixture")?;
922 checked(
923 "bobbin",
924 [
925 "index",
926 ".",
927 "--source",
928 ".",
929 "--repo",
930 &repo,
931 "--skip-calibrate",
932 ],
933 Some(root.path()),
934 )?;
935
936 let before = checked(
937 "bobbin",
938 ["grep", &marker, "--repo", &repo, "--json"],
939 Some(root.path()),
940 )?;
941 if bobbin_result_count(&before.stdout)? != 0 {
942 bail!("bobbin negative control unexpectedly found the fixture marker");
943 }
944
945 fs::write(
946 root.path().join("fixture.rs"),
947 format!(
948 "/// A unique Tambo verification routine.\npub fn {marker}() -> &'static str {{\n \"indexed\"\n}}\n"
949 ),
950 )
951 .context("write bobbin verification fixture")?;
952 checked(
953 "bobbin",
954 [
955 "index",
956 ".",
957 "--source",
958 ".",
959 "--repo",
960 &repo,
961 "--skip-calibrate",
962 ],
963 Some(root.path()),
964 )?;
965 let after = checked(
966 "bobbin",
967 ["grep", &marker, "--repo", &repo, "--json"],
968 Some(root.path()),
969 )?;
970 if bobbin_result_count(&after.stdout)? == 0 {
971 bail!("bobbin indexed the fixture but search did not return its marker");
972 }
973 Ok(())
974 }
975}
976
977const YUPANA_VERSION: crate::builtin_pins::Pin =
978 crate::builtin_pins::Pin(|| &crate::builtin_pins::pin("yupana").version);
979
980impl Adapter for Yupana {
981 fn name(&self) -> ToolName {
982 ToolName::Yupana
983 }
984
985 fn desired_version(&self) -> String {
986 format!("yupana {YUPANA_VERSION}")
987 }
988
989 fn install(&self) -> Result<()> {
990 let (target, checksum) = yupana_release_for(env::consts::ARCH, env::consts::OS)?;
991 let root = tempfile::tempdir().context("create Yupana download directory")?;
992 fetch_yupana_release(target, checksum, root.path())?;
993 let home = env::var_os("HOME").context("HOME is required to install Yupana")?;
994 let bin = env::var_os("CARGO_HOME")
995 .map(PathBuf::from)
996 .unwrap_or_else(|| PathBuf::from(home).join(".cargo"))
997 .join("bin");
998 fs::create_dir_all(&bin).with_context(|| format!("create {}", bin.display()))?;
999 fs::copy(root.path().join("yupana"), bin.join("yupana"))
1000 .context("install checksummed Yupana binary")?;
1001 Ok(())
1002 }
1003
1004 fn version(&self) -> Result<String> {
1005 let version = read_version("yupana")?;
1006 require_minimum_version(&version, (0, 6, 4), "yupana")?;
1007 Ok(version)
1008 }
1009
1010 fn verify(&self) -> Result<()> {
1011 let root = tempfile::tempdir().context("create Yupana verification repository")?;
1012 let state = root.path().join("state");
1013 fs::write(
1014 root.path().join("control.rs"),
1015 "pub fn tambo_yupana_control() -> usize { 1 }\n",
1016 )?;
1017 yupana_checked(root.path(), &state, ["analyze", "."])?;
1018 let before = yupana_checked(root.path(), &state, ["callers", "tambo_yupana_target", "."])?;
1019 if String::from_utf8_lossy(&before.stdout).contains("tambo_yupana_caller") {
1020 bail!("Yupana negative control unexpectedly found the fixture caller");
1021 }
1022 fs::write(
1023 root.path().join("fixture.rs"),
1024 "pub fn tambo_yupana_target() -> usize { 1 }\npub fn tambo_yupana_caller() -> usize { tambo_yupana_target() }\n",
1025 )?;
1026 yupana_checked(root.path(), &state, ["analyze", "."])?;
1027 let after = yupana_checked(root.path(), &state, ["callers", "tambo_yupana_target", "."])?;
1028 if !String::from_utf8_lossy(&after.stdout).contains("tambo_yupana_caller") {
1029 bail!("Yupana analyzed the fixture but callers did not return its caller");
1030 }
1031 Ok(())
1032 }
1033}
1034
1035fn yupana_release_target() -> Result<&'static str> {
1036 yupana_release_for(env::consts::ARCH, env::consts::OS).map(|(target, _)| target)
1037}
1038
1039pub(crate) fn yupana_release_for(arch: &str, os: &str) -> Result<(&'static str, &'static str)> {
1042 let target = match (arch, os) {
1043 ("x86_64", "linux") => "x86_64-linux-gnu",
1044 ("aarch64", "macos") => "aarch64-apple-darwin",
1045 ("x86_64", "macos") => "x86_64-apple-darwin",
1046 _ => bail!("Yupana v{YUPANA_VERSION} has no checksummed Tambo release for {arch}-{os}"),
1047 };
1048 let checksum = crate::builtin_pins::pin("yupana")
1049 .sha256
1050 .get(target)
1051 .with_context(|| format!("Yupana v{YUPANA_VERSION} pins no digest for {target}"))?;
1052 Ok((target, checksum))
1053}
1054
1055fn fetch_yupana_release(target: &str, checksum: &str, root: &Path) -> Result<()> {
1056 let archive_name = format!("yupana-v{YUPANA_VERSION}-{target}.tar.gz");
1057 let archive = root.join(&archive_name);
1058 download_https(
1059 &format!(
1060 "https://github.com/scbrown/yupana/releases/download/v{YUPANA_VERSION}/{archive_name}"
1061 ),
1062 &archive,
1063 )?;
1064 verify_yupana_checksum(&archive, checksum)?;
1065 checked(
1066 "tar",
1067 [
1068 OsStr::new("-xzf"),
1069 archive.as_os_str(),
1070 OsStr::new("-C"),
1071 root.as_os_str(),
1072 ],
1073 None,
1074 )?;
1075 Ok(())
1076}
1077
1078fn verify_yupana_checksum(archive: &Path, expected: &str) -> Result<()> {
1079 if manifest::sha256_file(archive)? != expected {
1080 bail!("Yupana release checksum mismatch");
1081 }
1082 Ok(())
1083}
1084
1085fn yupana_checked<I, S>(cwd: &Path, state: &Path, args: I) -> Result<Output>
1086where
1087 I: IntoIterator<Item = S>,
1088 S: AsRef<OsStr>,
1089{
1090 let home = cwd.join("home");
1091 fs::create_dir_all(&home)?;
1092 let mut command = Command::new("yupana");
1093 command
1094 .args(args)
1095 .current_dir(cwd)
1096 .env("HOME", home)
1097 .env("XDG_STATE_HOME", state);
1098 let result = command
1099 .output()
1100 .context("run isolated Yupana verification")?;
1101 if !result.status.success() {
1102 bail!(
1103 "isolated Yupana verification failed ({}): {}",
1104 result.status,
1105 String::from_utf8_lossy(&result.stderr).trim()
1106 );
1107 }
1108 Ok(result)
1109}
1110
1111fn desire_path_program() -> Result<PathBuf> {
1114 if let Some(path) = env::var_os("PATH") {
1115 for directory in env::split_paths(&path) {
1116 let candidate = directory.join("dp");
1117 if candidate.is_file() {
1118 #[cfg(unix)]
1119 {
1120 use std::os::unix::fs::PermissionsExt;
1121 if candidate.metadata()?.permissions().mode() & 0o111 == 0 {
1122 continue;
1123 }
1124 }
1125 return fs::canonicalize(candidate).context("resolve Desire Path executable");
1126 }
1127 }
1128 }
1129 let home = env::var_os("HOME").context("HOME is required to install Desire Path")?;
1130 Ok(PathBuf::from(home).join(".local/bin/dp"))
1131}
1132
1133const DESIRE_PATH_REVISION: crate::builtin_pins::Pin =
1134 crate::builtin_pins::Pin(|| revision("desire-path"));
1135const DESIRE_PATH_VERSION: crate::builtin_pins::Pin = crate::builtin_pins::Pin(|| {
1137 static TAG: std::sync::OnceLock<String> = std::sync::OnceLock::new();
1138 TAG.get_or_init(|| crate::builtin_pins::pin("desire-path").tag_name())
1139});
1140
1141fn revision(tool: &str) -> &'static str {
1142 crate::builtin_pins::pin(tool)
1143 .revision
1144 .as_deref()
1145 .unwrap_or_else(|| panic!("{tool} pins no revision"))
1146}
1147
1148impl Adapter for DesirePath {
1149 fn name(&self) -> ToolName {
1150 ToolName::DesirePath
1151 }
1152
1153 fn desired_version(&self) -> String {
1154 format!("dp {DESIRE_PATH_VERSION} ({})", &DESIRE_PATH_REVISION[..7])
1155 }
1156
1157 fn is_current(&self, installed: &str) -> bool {
1158 let expected = self.desired_version();
1159 installed.trim_start_matches("dp ").trim_start_matches('v')
1160 == expected.trim_start_matches("dp ").trim_start_matches('v')
1161 }
1162
1163 fn install(&self) -> Result<()> {
1164 let executable = desire_path_program()?;
1165 let bin = executable
1166 .parent()
1167 .context("Desire Path needs an install directory")?;
1168 fs::create_dir_all(bin).with_context(|| format!("create {}", bin.display()))?;
1169 let ldflags = format!(
1170 "-X github.com/scbrown/desire-path/internal/cli.Version={DESIRE_PATH_VERSION} -X github.com/scbrown/desire-path/internal/cli.Commit={DESIRE_PATH_REVISION}"
1171 );
1172 let mut command = Command::new("go");
1173 command
1174 .args([
1175 "install",
1176 "-ldflags",
1177 &ldflags,
1178 &format!("github.com/scbrown/desire-path/cmd/dp@{DESIRE_PATH_REVISION}"),
1179 ])
1180 .env("GOBIN", bin);
1181 let result = command
1182 .output()
1183 .context("build pinned Desire Path revision")?;
1184 if !result.status.success() {
1185 bail!(
1186 "Desire Path install failed ({}): {}",
1187 result.status,
1188 String::from_utf8_lossy(&result.stderr).trim()
1189 );
1190 }
1191 Ok(())
1192 }
1193
1194 fn version(&self) -> Result<String> {
1195 let result = checked(desire_path_program()?, ["version"], None)?;
1196 let version = String::from_utf8_lossy(&result.stdout).trim().to_owned();
1197 if version.is_empty() {
1201 bail!("dp version returned no version");
1202 }
1203 Ok(version)
1204 }
1205
1206 fn verify(&self) -> Result<()> {
1207 let dp = desire_path_program()?;
1208 let root = tempfile::tempdir().context("create Desire Path verification directory")?;
1209 let db = root.path().join("desires.db");
1210 let marker = "tambo_desire_path_marker";
1211 let before = checked(
1212 &dp,
1213 [
1214 "--db",
1215 db.to_str().context("Desire Path DB path is not UTF-8")?,
1216 "--json",
1217 "list",
1218 ],
1219 Some(root.path()),
1220 )?;
1221 if String::from_utf8_lossy(&before.stdout).contains(marker) {
1222 bail!("Desire Path negative control unexpectedly found the marker");
1223 }
1224 let mut child = Command::new(&dp)
1225 .args([
1226 "--db",
1227 db.to_str().unwrap(),
1228 "ingest",
1229 "--source",
1230 "claude-code",
1231 ])
1232 .current_dir(root.path())
1233 .stdin(std::process::Stdio::piped())
1234 .stdout(std::process::Stdio::piped())
1235 .stderr(std::process::Stdio::piped())
1236 .spawn()
1237 .context("start Desire Path ingest verification")?;
1238 use std::io::Write as _;
1239 child
1240 .stdin
1241 .take()
1242 .context("open Desire Path verification stdin")?
1243 .write_all(
1244 format!(r#"{{"tool_name":"{marker}","error":"fixture failure"}}"#).as_bytes(),
1245 )?;
1246 let ingested = child.wait_with_output()?;
1247 if !ingested.status.success() {
1248 bail!(
1249 "Desire Path ingest verification failed ({}): {}",
1250 ingested.status,
1251 String::from_utf8_lossy(&ingested.stderr).trim()
1252 );
1253 }
1254 let after = checked(
1255 &dp,
1256 ["--db", db.to_str().unwrap(), "--json", "list"],
1257 Some(root.path()),
1258 )?;
1259 if !String::from_utf8_lossy(&after.stdout).contains(marker) {
1260 bail!("Desire Path ingested the fixture but its reader path did not return it");
1261 }
1262 Ok(())
1263 }
1264}
1265
1266fn bobbin_result_count(stdout: &[u8]) -> Result<u64> {
1267 let response: serde_json::Value =
1268 serde_json::from_slice(stdout).context("parse bobbin search JSON")?;
1269 response["count"]
1270 .as_u64()
1271 .context("bobbin search JSON omitted numeric count")
1272}
1273
1274pub(crate) fn bobbin_release_target() -> Result<&'static str> {
1275 match (env::consts::ARCH, env::consts::OS) {
1276 ("x86_64", "linux") => Ok("x86_64-unknown-linux-gnu"),
1277 ("aarch64", "linux") => Ok("aarch64-unknown-linux-gnu"),
1278 ("x86_64", "macos") => Ok("x86_64-apple-darwin"),
1279 ("aarch64", "macos") => Ok("aarch64-apple-darwin"),
1280 (arch, os) => bail!("bobbin has no Tambo release target for {arch}-{os}"),
1281 }
1282}
1283
1284fn install_bobbin_release() -> Result<()> {
1285 let target = bobbin_release_target()?;
1286 let archive = format!("bobbin-v{BOBBIN_VERSION}-{target}.tar.gz");
1287 let base = format!("https://github.com/scbrown/bobbin/releases/download/v{BOBBIN_VERSION}");
1288 let download = tempfile::tempdir().context("create bobbin download directory")?;
1289 let archive_path = download.path().join(&archive);
1290 let sums_path = download.path().join("SHA256SUMS.txt");
1291 download_https(&format!("{base}/{archive}"), &archive_path)?;
1292 download_https(&format!("{base}/SHA256SUMS.txt"), &sums_path)?;
1293 verify_checksum(&archive_path, &sums_path)?;
1294
1295 let home = env::var_os("HOME").context("HOME is required to install bobbin")?;
1296 let install_root = PathBuf::from(&home)
1297 .join(".local/share/caboodle/bobbin")
1298 .join(format!("v{BOBBIN_VERSION}"));
1299 fs::create_dir_all(&install_root)
1300 .with_context(|| format!("create bobbin install root {}", install_root.display()))?;
1301 checked(
1302 "tar",
1303 [
1304 OsStr::new("-xzf"),
1305 archive_path.as_os_str(),
1306 OsStr::new("--strip-components=1"),
1307 OsStr::new("-C"),
1308 install_root.as_os_str(),
1309 ],
1310 None,
1311 )?;
1312
1313 let bin_dir = env::var_os("CARGO_HOME")
1314 .map(PathBuf::from)
1315 .unwrap_or_else(|| PathBuf::from(home).join(".cargo"))
1316 .join("bin");
1317 fs::create_dir_all(&bin_dir)
1318 .with_context(|| format!("create binary directory {}", bin_dir.display()))?;
1319 let link = bin_dir.join("bobbin");
1320 let target = install_root.join("bobbin");
1321 ensure_bobbin_link(&link, &target)?;
1322 Ok(())
1323}
1324
1325fn ensure_bobbin_link(link: &Path, target: &Path) -> Result<()> {
1326 if !target.is_file() {
1327 bail!("Bobbin release archive omitted {}", target.display());
1328 }
1329 match link.symlink_metadata() {
1330 Ok(metadata)
1331 if metadata.file_type().is_symlink()
1332 && fs::read_link(link).ok().as_deref() == Some(target) =>
1333 {
1334 return Ok(());
1335 }
1336 Ok(metadata) if metadata.file_type().is_symlink() && !link.exists() => {
1360 fs::remove_file(link).with_context(|| format!("remove dangling {}", link.display()))?;
1361 }
1362 Ok(_) => {
1363 bail!(
1364 "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",
1365 link.display(),
1366 link.display()
1367 );
1368 }
1369 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1370 Err(error) => return Err(error).with_context(|| format!("inspect {}", link.display())),
1371 }
1372 #[cfg(unix)]
1373 std::os::unix::fs::symlink(target, link)
1374 .with_context(|| format!("link bobbin into {}", link.display()))?;
1375 #[cfg(not(unix))]
1376 bail!("bobbin release installation currently requires a Unix host");
1377 Ok(())
1378}
1379
1380pub(crate) const CAMAYOC_VERSION: crate::builtin_pins::Pin =
1385 crate::builtin_pins::Pin(|| &crate::builtin_pins::pin("camayoc").version);
1386const CAMAYOC_REVISION: crate::builtin_pins::Pin = crate::builtin_pins::Pin(|| revision("camayoc"));
1387const CAMAYOC_ARCHIVE_SHA256: crate::builtin_pins::Pin =
1388 crate::builtin_pins::Pin(|| &crate::builtin_pins::pin("camayoc").sha256["any"]);
1389
1390pub(crate) fn camayoc_root() -> Result<PathBuf> {
1391 if let Some(path) = env::var_os("CABOODLE_CAMAYOC_ROOT") {
1392 return Ok(PathBuf::from(path));
1393 }
1394 let home = env::var_os("HOME").context("HOME is required to install Camayoc")?;
1395 Ok(PathBuf::from(home)
1396 .join(".local/share/caboodle/camayoc")
1397 .join(&*CAMAYOC_REVISION))
1398}
1399
1400fn install_camayoc_bundle() -> Result<()> {
1401 let root = camayoc_root()?;
1402 if root.join("REVISION").exists() {
1403 return Ok(());
1404 }
1405 let download = tempfile::tempdir().context("create Camayoc download directory")?;
1406 let archive = download.path().join("camayoc.tar.gz");
1407 download_https(
1408 &format!(
1409 "https://github.com/intigraph/camayoc/releases/download/v{CAMAYOC_VERSION}/camayoc-v{CAMAYOC_VERSION}.tar.gz"
1410 ),
1411 &archive,
1412 )?;
1413 if crate::embedding::sha256_file(&archive)? != CAMAYOC_ARCHIVE_SHA256 {
1414 bail!("Camayoc archive checksum mismatch");
1415 }
1416 fs::create_dir_all(&root)
1417 .with_context(|| format!("create Camayoc install root {}", root.display()))?;
1418 checked(
1419 "tar",
1420 [
1421 OsStr::new("-xzf"),
1422 archive.as_os_str(),
1423 OsStr::new("--strip-components=1"),
1424 OsStr::new("-C"),
1425 root.as_os_str(),
1426 ],
1427 None,
1428 )?;
1429 fs::write(root.join("REVISION"), format!("{CAMAYOC_REVISION}\n"))
1430 .context("write installed Camayoc revision")?;
1431 Ok(())
1432}
1433
1434pub fn camayoc_cli_check(path: Option<&OsStr>, home: Option<&Path>) -> Result<Vec<PathBuf>> {
1450 let mut probes: Vec<PathBuf> = which_all("camayoc", path).into_iter().take(1).collect();
1451 if let Some(uv_bin) = home.map(|home| home.join(".local/bin/camayoc")) {
1452 let same = |seen: &PathBuf| {
1453 seen.canonicalize()
1454 .ok()
1455 .is_some_and(|seen| uv_bin.canonicalize().ok() == Some(seen))
1456 };
1457 if is_executable(&uv_bin) && !probes.iter().any(same) {
1458 probes.push(uv_bin);
1459 }
1460 }
1461 for runs in &probes {
1462 let reported = runs
1463 .to_str()
1464 .context("camayoc CLI path is not UTF-8")
1465 .and_then(read_version);
1466 let reported = match reported {
1467 Ok(reported) => reported,
1468 Err(error) => bail!(
1469 "camayoc NOT converged: {} has an unreadable version ({error:#}); \
1470 the reviewed Camayoc release is v{CAMAYOC_VERSION}",
1471 runs.display()
1472 ),
1473 };
1474 if camayoc_cli_version(&reported) != Some(&*CAMAYOC_VERSION) {
1475 bail!(
1476 "camayoc NOT converged: {} reports `{}`, but the reviewed Camayoc \
1477 release is v{CAMAYOC_VERSION}. Tambo installs the Camayoc bundle, not this CLI; \
1478 upgrade it (`uv tool install --force git+https://github.com/intigraph/camayoc@v{CAMAYOC_VERSION}`) \
1479 or remove the stale copy",
1480 runs.display(),
1481 reported.trim()
1482 );
1483 }
1484 }
1485 Ok(probes)
1486}
1487
1488fn camayoc_cli_version(reported: &str) -> Option<&str> {
1490 reported
1491 .lines()
1492 .next()?
1493 .trim()
1494 .strip_prefix("camayoc ")
1495 .map(|v| v.trim().trim_start_matches('v'))
1496}
1497
1498fn verify_camayoc_first_ingest(root: &Path, server: &str, auth: &Path) -> Result<()> {
1499 let namespace = camayoc_aegis_namespace(&root.join("ontology/core.ttl"))?;
1500 let control = "tambo-camayoc-control-must-stay-absent";
1501 let marker = "tambo-camayoc-first-ingest-v1";
1502
1503 if label_count(server, &namespace, control, auth)? != 0 {
1504 bail!("Camayoc negative control unexpectedly exists");
1505 }
1506
1507 let turtle = format!(
1508 "@prefix aegis: <{namespace}> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\
1509 aegis:{marker} a aegis:Verification ; rdfs:label \"{marker}\" ; \
1510 aegis:sourceKind \"observed\" ; aegis:falsifier \"the marker remains absent after ingest\" .\n"
1511 );
1512 let payload = json!({
1513 "turtle": turtle,
1514 "actor": "caboodle",
1515 "source": "Tambo Camayoc first-ingest verification"
1516 });
1517 if label_count(server, &namespace, marker, auth)? == 0 {
1518 let first = curl_json_request_with_config(
1519 &format!("{server}/knot"),
1520 Some(payload.to_string()),
1521 Some(auth),
1522 )?;
1523 if first.get("count").and_then(Value::as_u64).unwrap_or(0) == 0 {
1524 bail!("Camayoc first ingest wrote no triples");
1525 }
1526 }
1527 if label_count(server, &namespace, marker, auth)? == 0 {
1528 bail!("Camayoc first ingest was not retrievable");
1529 }
1530 curl_json_request_with_config(
1531 &format!("{server}/knot"),
1532 Some(payload.to_string()),
1533 Some(auth),
1534 )?;
1535 if label_count(server, &namespace, marker, auth)? != 1 {
1536 bail!("Camayoc idempotent replay wrote duplicate triples");
1537 }
1538 Ok(())
1539}
1540
1541pub(crate) fn camayoc_aegis_namespace(path: &Path) -> Result<String> {
1542 let body = fs::read_to_string(path)
1543 .with_context(|| format!("read Camayoc ontology {}", path.display()))?;
1544 body.lines()
1545 .find_map(|line| {
1546 line.trim()
1547 .strip_prefix("@prefix aegis: <")
1548 .and_then(|rest| rest.strip_suffix("> ."))
1549 .map(str::to_owned)
1550 })
1551 .context("Camayoc ontology does not declare the aegis namespace")
1552}
1553
1554fn label_count(server: &str, namespace: &str, label: &str, auth: &Path) -> Result<u64> {
1555 let query = format!(
1556 "SELECT ?s WHERE {{ ?s <http://www.w3.org/2000/01/rdf-schema#label> \"{label}\" . FILTER(STRSTARTS(STR(?s), \"{namespace}\")) }}"
1557 );
1558 let response = curl_json_request_with_config(
1559 &format!("{server}/query"),
1560 Some(json!({"query": query}).to_string()),
1561 Some(auth),
1562 )?;
1563 response["count"]
1564 .as_u64()
1565 .context("Quipu query response omitted numeric count")
1566}
1567
1568pub(crate) fn curl_json(url: &str, payload: &Value) -> Result<Value> {
1569 curl_json_request(url, Some(payload.to_string()))
1570}
1571
1572fn curl_get_json(url: &str) -> Result<Value> {
1573 curl_json_request(url, None)
1574}
1575
1576fn quipu_auth_config() -> Result<Option<tempfile::NamedTempFile>> {
1581 crate::quipu_auth::config()
1582}
1583
1584pub(crate) fn curl_auth_header_line(token: &str) -> Result<String> {
1585 if token.contains(['\n', '\r']) {
1586 bail!("QUIPU_AUTH_TOKEN contains a line break; refusing to pass it to curl");
1587 }
1588 let escaped = token.replace('\\', "\\\\").replace('"', "\\\"");
1589 Ok(format!("header = \"Authorization: Bearer {escaped}\"\n"))
1590}
1591
1592pub(crate) fn quipu_write_probe(server: &str) -> Result<(u16, String, bool)> {
1599 let body_file = tempfile::NamedTempFile::new().context("create write-probe body file")?;
1600 let auth = quipu_auth_config()?;
1601 let mut args: Vec<OsString> = [
1602 "--silent",
1603 "--max-time",
1604 "5",
1605 "--request",
1606 "POST",
1607 "--header",
1608 "Content-Type: application/json",
1609 "--data",
1610 "{}",
1611 "--write-out",
1612 "%{http_code}",
1613 "--output",
1614 ]
1615 .iter()
1616 .map(OsString::from)
1617 .collect();
1618 args.push(body_file.path().as_os_str().to_owned());
1619 if let Some(file) = &auth {
1620 args.push(OsString::from("--config"));
1621 args.push(file.path().as_os_str().to_owned());
1622 }
1623 args.push(OsString::from(format!(
1624 "{}/episode",
1625 server.trim_end_matches('/')
1626 )));
1627 let result = output("curl", args, None)?;
1628 let code = String::from_utf8_lossy(&result.stdout)
1629 .trim()
1630 .parse::<u16>()
1631 .unwrap_or(0);
1632 let body = fs::read_to_string(body_file.path()).unwrap_or_default();
1633 Ok((code, body, auth.is_some()))
1634}
1635
1636fn curl_json_request(url: &str, body: Option<String>) -> Result<Value> {
1637 let auth = quipu_auth_config()?;
1638 curl_json_request_with_config(url, body, auth.as_ref().map(|file| file.path()))
1639}
1640
1641fn curl_json_request_with_config(
1642 url: &str,
1643 body: Option<String>,
1644 auth: Option<&Path>,
1645) -> Result<Value> {
1646 let mut args = vec![
1647 OsString::from("--fail"),
1648 OsString::from("--silent"),
1649 OsString::from("--show-error"),
1650 ];
1651 if let Some(body) = body {
1652 args.extend([
1653 OsString::from("--request"),
1654 OsString::from("POST"),
1655 OsString::from("--header"),
1656 OsString::from("Content-Type: application/json"),
1657 OsString::from("--data"),
1658 OsString::from(body),
1659 ]);
1660 }
1661 if let Some(file) = &auth {
1662 args.push(OsString::from("--config"));
1663 args.push(file.as_os_str().to_owned());
1664 }
1665 args.push(OsString::from(url));
1666 let result = checked("curl", args, None)?;
1667 serde_json::from_slice(&result.stdout)
1668 .with_context(|| format!("parse JSON response from {url}"))
1669}
1670
1671pub(crate) fn download_https(url: &str, destination: &Path) -> Result<()> {
1672 const ATTEMPTS: u32 = 3;
1675 for attempt in 1..=ATTEMPTS {
1676 let pending = tempfile::NamedTempFile::new_in(
1679 destination
1680 .parent()
1681 .filter(|p| !p.as_os_str().is_empty())
1682 .unwrap_or(Path::new(".")),
1683 )
1684 .context("create pending download")?;
1685 let result = output(
1686 "curl",
1687 [
1688 OsStr::new("--disable"),
1689 OsStr::new("--fail"),
1690 OsStr::new("--location"),
1691 OsStr::new("--silent"),
1692 OsStr::new("--show-error"),
1693 OsStr::new("--proto"),
1694 OsStr::new("=https"),
1695 OsStr::new("--tlsv1.2"),
1696 OsStr::new("--connect-timeout"),
1697 OsStr::new("10"),
1698 OsStr::new("--max-time"),
1699 OsStr::new("120"),
1700 OsStr::new("--write-out"),
1701 OsStr::new("%{http_code}"),
1702 OsStr::new("--output"),
1703 pending.path().as_os_str(),
1704 OsStr::new(url),
1705 ],
1706 None,
1707 )?;
1708 if result.status.success() {
1709 pending
1710 .persist(destination)
1711 .context("publish downloaded artifact")?;
1712 if attempt > 1 {
1713 eprintln!("download {url}: succeeded on attempt {attempt}/{ATTEMPTS}");
1714 }
1715 return Ok(());
1716 }
1717 let http = String::from_utf8_lossy(&result.stdout)
1718 .trim()
1719 .parse::<u16>()
1720 .unwrap_or(0);
1721 let detail = format!(
1722 "download {url}: attempt {attempt}/{ATTEMPTS}, curl {}, HTTP {http:03}: {}",
1723 result.status,
1724 String::from_utf8_lossy(&result.stderr).trim()
1725 );
1726 if !retryable_download(result.status.code(), http) {
1727 bail!("{detail}; terminal failure (not retried)");
1728 }
1729 if attempt == ATTEMPTS {
1730 bail!("{detail}; retry limit exhausted");
1731 }
1732 let delay = 1 << (attempt - 1);
1733 eprintln!("{detail}; retrying in {delay}s");
1734 drop(pending);
1735 std::thread::sleep(std::time::Duration::from_secs(delay));
1736 }
1737 unreachable!("every final attempt returns")
1738}
1739
1740fn retryable_download(code: Option<i32>, http: u16) -> bool {
1741 if (400..500).contains(&http) {
1743 return false;
1744 }
1745 match code {
1746 Some(22) => (500..600).contains(&http),
1747 Some(5 | 6 | 7 | 18 | 28 | 52 | 55 | 56 | 92) => true,
1750 _ => false,
1752 }
1753}
1754
1755fn verify_checksum(archive: &Path, sums: &Path) -> Result<()> {
1756 let filename = archive
1757 .file_name()
1758 .and_then(OsStr::to_str)
1759 .context("bobbin archive filename is not UTF-8")?;
1760 let expected = fs::read_to_string(sums)
1761 .context("read Bobbin checksum manifest")?
1762 .lines()
1763 .find_map(|line| {
1764 let mut fields = line.split_whitespace();
1765 let digest = fields.next()?;
1766 let listed = fields.next()?.trim_start_matches('*');
1767 (listed == filename).then(|| digest.to_owned())
1768 })
1769 .with_context(|| format!("checksum manifest does not cover {filename}"))?;
1770 if crate::embedding::sha256_file(archive)? != expected {
1771 bail!("checksum mismatch for {filename}");
1772 }
1773 Ok(())
1774}
1775
1776#[cfg(test)]
1777mod yupana_release_tests {
1778 use super::*;
1779
1780 #[test]
1781 fn published_platforms_resolve_and_missing_platforms_refuse() {
1782 for (arch, os, target) in [
1783 ("x86_64", "linux", "x86_64-linux-gnu"),
1784 ("aarch64", "macos", "aarch64-apple-darwin"),
1785 ("x86_64", "macos", "x86_64-apple-darwin"),
1786 ] {
1787 assert_eq!(yupana_release_for(arch, os).unwrap().0, target);
1788 }
1789 assert!(yupana_release_for("aarch64", "linux").is_err());
1790 assert!(yupana_release_for("x86_64", "windows").is_err());
1791 assert!(!prerequisites(ToolName::Yupana, QuipuFlavor::Release).contains(&"sha256sum"));
1792 }
1793
1794 #[test]
1795 fn checksum_refuses_corruption_without_an_external_hash_command() {
1796 let root = tempfile::tempdir().unwrap();
1797 let file = root.path().join("archive");
1798 fs::write(&file, b"abc").unwrap();
1799 let expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
1800 verify_yupana_checksum(&file, expected).unwrap();
1801 fs::write(&file, b"abd").unwrap();
1802 assert!(verify_yupana_checksum(&file, expected).is_err());
1803 }
1804
1805 #[test]
1808 fn camayoc_needs_no_external_hash_command() {
1809 for flavor in [QuipuFlavor::Release, QuipuFlavor::Lancedb] {
1810 assert!(!prerequisites(ToolName::Camayoc, flavor).contains(&"sha256sum"));
1811 }
1812 }
1813
1814 #[test]
1818 fn checksums_verify_and_refuse_with_an_empty_path() {
1819 const CHILD: &str = "TAMBO_EMPTY_PATH_CHECKSUM_CHILD";
1820 if env::var_os(CHILD).is_some() {
1821 assert_eq!(env::var_os("PATH").as_deref(), Some(OsStr::new("")));
1822 let root = tempfile::tempdir().unwrap();
1823 let archive = root.path().join("bobbin.tar.gz");
1824 let sums = root.path().join("SHA256SUMS");
1825 let abc = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
1826 fs::write(&archive, b"abc").unwrap();
1827 fs::write(&sums, format!("{abc} bobbin.tar.gz\n")).unwrap();
1828 verify_checksum(&archive, &sums).unwrap();
1829 verify_yupana_checksum(&archive, abc).unwrap();
1830 fs::write(&archive, b"abd").unwrap();
1831 let mismatch = verify_checksum(&archive, &sums).unwrap_err();
1832 assert!(
1833 format!("{mismatch:#}").contains("checksum mismatch"),
1834 "{mismatch:#}"
1835 );
1836 assert!(verify_yupana_checksum(&archive, abc).is_err());
1837 return;
1838 }
1839 let output = Command::new(env::current_exe().unwrap())
1840 .args([
1841 "--exact",
1842 "adapter::yupana_release_tests::checksums_verify_and_refuse_with_an_empty_path",
1843 "--nocapture",
1844 "--test-threads=1",
1845 ])
1846 .env("PATH", "")
1847 .env(CHILD, "1")
1848 .output()
1849 .unwrap();
1850 let stdout = String::from_utf8_lossy(&output.stdout);
1851 assert!(
1852 output.status.success() && stdout.contains("1 passed"),
1853 "empty-PATH child failed:\n{stdout}\n{}",
1854 String::from_utf8_lossy(&output.stderr)
1855 );
1856 }
1857
1858 #[test]
1859 fn manifest_checksum_is_computed_in_process() {
1860 let root = tempfile::tempdir().unwrap();
1861 let archive = root.path().join("bobbin.tar.gz");
1862 let sums = root.path().join("SHA256SUMS");
1863 fs::write(&archive, b"abc").unwrap();
1864 fs::write(
1865 &sums,
1866 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad bobbin.tar.gz\n",
1867 )
1868 .unwrap();
1869 verify_checksum(&archive, &sums).unwrap();
1870 fs::write(&archive, b"abd").unwrap();
1871 assert!(verify_checksum(&archive, &sums).is_err());
1872 }
1873
1874 #[test]
1875 #[ignore = "downloads all three published archives; explicit release acceptance"]
1876 fn real_yupana_archives_match_pins_and_unpack() {
1877 for (arch, os) in [
1878 ("x86_64", "linux"),
1879 ("aarch64", "macos"),
1880 ("x86_64", "macos"),
1881 ] {
1882 let (target, checksum) = yupana_release_for(arch, os).unwrap();
1883 let root = tempfile::tempdir().unwrap();
1884 fetch_yupana_release(target, checksum, root.path()).unwrap();
1885 assert!(root.path().join("yupana").is_file());
1886 assert_eq!(
1887 fs::read_link(root.path().join("hank")).unwrap(),
1888 Path::new("yupana")
1889 );
1890 eprintln!("verified published {target}: {checksum}");
1891 }
1892 }
1893}
1894
1895#[cfg(test)]
1896mod flavor_tests {
1897 use super::{
1898 fetch_quipu_release, quipu_install_args, quipu_release_target, quipu_release_target_for,
1899 require_compiled_feature,
1900 };
1901 use crate::model::QuipuFlavor;
1902 use serde_json::json;
1903
1904 #[test]
1905 fn install_args_add_only_the_lancedb_feature_to_the_reviewed_pin() {
1906 let release = quipu_install_args(QuipuFlavor::Release);
1907 let lancedb = quipu_install_args(QuipuFlavor::Lancedb);
1908 assert_eq!(release[6], "full");
1909 assert_eq!(lancedb[6], "full,lancedb");
1910 assert_eq!(release[..6], lancedb[..6]);
1913 assert_eq!(release[7..], lancedb[7..]);
1914 assert!(release.contains(&"--locked"));
1915 }
1916
1917 #[test]
1918 fn default_quipu_release_has_a_supported_host_artifact() {
1919 if (std::env::consts::ARCH, std::env::consts::OS) == ("x86_64", "linux") {
1920 assert_eq!(quipu_release_target().unwrap(), "x86_64-unknown-linux-gnu");
1921 }
1922 }
1923
1924 #[test]
1925 fn quipu_release_supports_published_linux_and_macos_architectures() {
1926 for (arch, os, target) in [
1927 ("x86_64", "linux", "x86_64-unknown-linux-gnu"),
1928 ("aarch64", "linux", "aarch64-unknown-linux-gnu"),
1929 ("x86_64", "macos", "x86_64-apple-darwin"),
1930 ("aarch64", "macos", "aarch64-apple-darwin"),
1931 ] {
1932 assert_eq!(quipu_release_target_for(arch, os).unwrap(), target);
1933 }
1934 assert!(quipu_release_target_for("x86_64", "windows").is_err());
1935 }
1936
1937 #[test]
1938 #[ignore = "downloads published artifacts; explicit release acceptance only"]
1939 fn real_aarch64_quipu_release_resolves_and_verifies() {
1940 for os in ["macos", "linux"] {
1941 let target = quipu_release_target_for("aarch64", os).unwrap();
1942 let download = tempfile::tempdir().unwrap();
1943 let unpacked = fetch_quipu_release(target, download.path()).unwrap();
1944 assert!(unpacked.join("quipu").is_file());
1945 assert!(unpacked.join("quipu-server").is_file());
1946 eprintln!("verified published Quipu checksums and both binaries for {target}");
1947 }
1948 }
1949
1950 #[test]
1951 fn compile_map_proof_requires_a_true_lancedb_entry() {
1952 require_compiled_feature(&json!({"features": {"lancedb": true}}), "lancedb").unwrap();
1953
1954 let absent = require_compiled_feature(&json!({"features": {"onnx": true}}), "lancedb")
1955 .unwrap_err()
1956 .to_string();
1957 assert!(absent.contains("compiled without it"), "{absent}");
1958
1959 let disabled =
1960 require_compiled_feature(&json!({"features": {"lancedb": false}}), "lancedb")
1961 .unwrap_err()
1962 .to_string();
1963 assert!(disabled.contains("compiled without it"), "{disabled}");
1964
1965 let unmapped = require_compiled_feature(&json!({"version": "0.3.27"}), "lancedb")
1968 .unwrap_err()
1969 .to_string();
1970 assert!(
1971 unmapped.contains("no per-feature compile map"),
1972 "{unmapped}"
1973 );
1974 }
1975}
1976
1977#[cfg(all(test, unix))]
1978mod tests {
1979 use super::ensure_bobbin_link;
1980 use std::{fs, os::unix::fs::symlink};
1981
1982 fn fake_camayoc(dir: &std::path::Path, script: &str) {
1983 use std::os::unix::fs::PermissionsExt;
1984 let program = dir.join("camayoc");
1985 fs::write(&program, script).unwrap();
1986 fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap();
1987 }
1988
1989 #[test]
1992 fn stale_camayoc_cli_on_path_is_not_converged() {
1993 let dir = tempfile::tempdir().unwrap();
1994 fake_camayoc(dir.path(), "#!/bin/sh\necho 'camayoc 0.1.4'\n");
1995 let error = super::camayoc_cli_check(Some(dir.path().as_os_str()), None)
1996 .unwrap_err()
1997 .to_string();
1998 assert!(error.contains("camayoc NOT converged"), "{error}");
1999 assert!(error.contains("camayoc 0.1.4"), "{error}");
2000 assert!(
2001 error.contains(&format!("v{}", super::CAMAYOC_VERSION)),
2002 "{error}"
2003 );
2004 }
2005
2006 #[test]
2009 fn stale_uv_camayoc_off_path_is_not_converged() {
2010 let home = tempfile::tempdir().unwrap();
2011 let uv_bin = home.path().join(".local/bin");
2012 fs::create_dir_all(&uv_bin).unwrap();
2013 fake_camayoc(&uv_bin, "#!/bin/sh\necho 'camayoc 0.1.4'\n");
2014 let empty = tempfile::tempdir().unwrap();
2015 let error = super::camayoc_cli_check(Some(empty.path().as_os_str()), Some(home.path()))
2016 .unwrap_err()
2017 .to_string();
2018 assert!(error.contains("camayoc NOT converged"), "{error}");
2019 assert!(error.contains(".local/bin/camayoc"), "{error}");
2020 }
2021
2022 #[test]
2024 fn current_path_camayoc_does_not_hide_stale_uv_copy() {
2025 let home = tempfile::tempdir().unwrap();
2026 let uv_bin = home.path().join(".local/bin");
2027 fs::create_dir_all(&uv_bin).unwrap();
2028 fake_camayoc(&uv_bin, "#!/bin/sh\necho 'camayoc 0.1.4'\n");
2029 let path_dir = tempfile::tempdir().unwrap();
2030 fake_camayoc(
2031 path_dir.path(),
2032 &format!("#!/bin/sh\necho 'camayoc {}'\n", super::CAMAYOC_VERSION),
2033 );
2034 assert!(
2035 super::camayoc_cli_check(Some(path_dir.path().as_os_str()), Some(home.path())).is_err()
2036 );
2037 }
2038
2039 #[test]
2040 fn reviewed_camayoc_cli_is_converged_once_when_path_and_uv_agree() {
2041 let home = tempfile::tempdir().unwrap();
2042 let uv_bin = home.path().join(".local/bin");
2043 fs::create_dir_all(&uv_bin).unwrap();
2044 fake_camayoc(
2046 &uv_bin,
2047 &format!("#!/bin/sh\necho 'camayoc {}'\n", super::CAMAYOC_VERSION),
2048 );
2049 let runs = super::camayoc_cli_check(Some(uv_bin.as_os_str()), Some(home.path())).unwrap();
2050 assert_eq!(runs, vec![uv_bin.join("camayoc")]);
2051 }
2052
2053 #[test]
2054 fn unreadable_camayoc_cli_version_is_not_converged() {
2055 let dir = tempfile::tempdir().unwrap();
2056 fake_camayoc(dir.path(), "#!/bin/sh\nexit 3\n");
2057 let error = super::camayoc_cli_check(Some(dir.path().as_os_str()), None)
2058 .unwrap_err()
2059 .to_string();
2060 assert!(error.contains("unreadable version"), "{error}");
2061 }
2062
2063 #[test]
2064 fn absent_camayoc_cli_is_only_a_note() {
2065 let dir = tempfile::tempdir().unwrap();
2066 let home = tempfile::tempdir().unwrap();
2067 assert!(
2068 super::camayoc_cli_check(Some(dir.path().as_os_str()), Some(home.path()))
2069 .unwrap()
2070 .is_empty()
2071 );
2072 }
2073
2074 #[test]
2075 fn failed_commands_preserve_both_diagnostic_streams_and_status() {
2076 for script in [
2077 "printf 'bootstrap rejected'; exit 2",
2078 "printf 'bootstrap rejected' >&2; exit 2",
2079 "printf 'probe started'; printf 'bootstrap rejected' >&2; exit 2",
2080 "exit 2",
2081 ] {
2082 let error = super::checked("sh", ["-c", script], None)
2083 .unwrap_err()
2084 .to_string();
2085 assert!(error.contains("exit status: 2"), "{error}");
2086 assert!(error.contains("stdout:\n"), "{error}");
2087 assert!(error.contains("stderr:\n"), "{error}");
2088 if script.contains("bootstrap rejected") {
2089 assert!(error.contains("bootstrap rejected"), "{error}");
2090 }
2091 if script.contains("probe started") {
2092 assert!(error.contains("probe started"), "{error}");
2093 }
2094 }
2095 let output = super::checked("sh", ["-c", "printf 'successful output'"], None).unwrap();
2096 assert_eq!(output.stdout, b"successful output");
2097 }
2098
2099 #[test]
2100 fn bobbin_link_accepts_its_restored_cache_entry_but_refuses_foreign_paths() {
2101 let root = tempfile::tempdir().unwrap();
2102 let target = root.path().join("release/bobbin");
2103 fs::create_dir_all(target.parent().unwrap()).unwrap();
2104 fs::write(&target, "binary fixture").unwrap();
2105
2106 let link = root.path().join("bin/bobbin");
2107 fs::create_dir_all(link.parent().unwrap()).unwrap();
2108 symlink(&target, &link).unwrap();
2109 ensure_bobbin_link(&link, &target).unwrap();
2110 assert_eq!(fs::read_link(&link).unwrap(), target);
2111
2112 let foreign = root.path().join("foreign");
2113 fs::write(&foreign, "do not replace").unwrap();
2114 fs::remove_file(&link).unwrap();
2115 symlink(&foreign, &link).unwrap();
2116 let error = ensure_bobbin_link(&link, &target).unwrap_err().to_string();
2117 assert!(error.contains("refusing to replace existing"));
2118 assert_eq!(fs::read_link(&link).unwrap(), foreign);
2119 }
2120
2121 #[test]
2122 fn bobbin_link_repairs_its_own_dangling_link_but_still_refuses_a_real_file() {
2123 let root = tempfile::tempdir().unwrap();
2128 let target = root.path().join("release/bobbin");
2129 fs::create_dir_all(target.parent().unwrap()).unwrap();
2130 fs::write(&target, "binary fixture").unwrap();
2131 let link = root.path().join("bin/bobbin");
2132 fs::create_dir_all(link.parent().unwrap()).unwrap();
2133
2134 symlink(root.path().join("gone/bobbin"), &link).unwrap();
2135 assert!(link.symlink_metadata().is_ok(), "the link itself exists");
2136 assert!(
2137 !link.exists(),
2138 "but it resolves to nothing -- this is the ENOENT"
2139 );
2140 ensure_bobbin_link(&link, &target).unwrap();
2141 assert_eq!(fs::read_link(&link).unwrap(), target);
2142
2143 fs::remove_file(&link).unwrap();
2146 fs::write(&link, "a real bobbin somebody installed").unwrap();
2147 let error = ensure_bobbin_link(&link, &target).unwrap_err().to_string();
2148 assert!(error.contains("refusing to replace existing"));
2149 assert_eq!(
2150 fs::read_to_string(&link).unwrap(),
2151 "a real bobbin somebody installed"
2152 );
2153 }
2154}
2155
2156#[cfg(test)]
2157mod auth_config_tests {
2158 use super::curl_auth_header_line;
2159
2160 #[test]
2161 fn curl_auth_line_escapes_quotes_and_refuses_line_breaks() {
2162 assert_eq!(
2163 curl_auth_header_line("abc").unwrap(),
2164 "header = \"Authorization: Bearer abc\"\n"
2165 );
2166 assert_eq!(
2167 curl_auth_header_line(r#"a"b\c"#).unwrap(),
2168 "header = \"Authorization: Bearer a\\\"b\\\\c\"\n"
2169 );
2170 assert!(curl_auth_header_line("tok\nurl = \"http://elsewhere\"").is_err());
2172 assert!(curl_auth_header_line("tok\r").is_err());
2173 }
2174}
2175
2176pub fn verify_member(name: &str) -> Result<()> {
2178 let member = crate::members::get(name).context("unknown reviewed member")?;
2179 manifest::verify_release_member(member)
2180}
2181
2182#[cfg(all(test, unix))]
2183mod quipu_alias_layout_tests {
2184 use super::verify_quipu_alias;
2185 use std::os::unix::fs::symlink;
2186 use std::{fs, path::Path};
2187
2188 fn script(path: &Path, version: &str) {
2189 crate::test_exec::write_executable(path, &format!("#!/bin/sh\necho '{version}'\n"));
2190 }
2191
2192 #[test]
2193 fn package_managed_layout_passes_with_qp_beside_the_resolved_quipu() {
2194 let root = tempfile::tempdir().unwrap();
2197 let cellar = root.path().join("Cellar/quipu/1.0/bin");
2198 let bin = root.path().join("bin");
2199 fs::create_dir_all(&cellar).unwrap();
2200 fs::create_dir(&bin).unwrap();
2201 script(&cellar.join("quipu"), "quipu 1.0");
2202 symlink("quipu", cellar.join("qp")).unwrap();
2203 symlink("../Cellar/quipu/1.0/bin/quipu", bin.join("quipu")).unwrap();
2204 symlink("../Cellar/quipu/1.0/bin/qp", bin.join("qp")).unwrap();
2205 verify_quipu_alias(&bin.join("quipu")).unwrap();
2206 }
2207
2208 #[test]
2209 fn a_qp_for_another_program_or_no_qp_still_fails() {
2210 let root = tempfile::tempdir().unwrap();
2211 let bin = root.path().join("bin");
2212 fs::create_dir(&bin).unwrap();
2213 script(&bin.join("quipu"), "quipu 1.0");
2214 let err = verify_quipu_alias(&bin.join("quipu")).unwrap_err();
2215 assert!(err.to_string().contains("requires relative qp -> quipu"));
2216 let cellar = root.path().join("Cellar/bin");
2219 fs::create_dir_all(&cellar).unwrap();
2220 script(&cellar.join("quipu"), "quipu 1.0");
2221 symlink("quipu", cellar.join("qp")).unwrap();
2222 script(&root.path().join("other"), "quipu 1.0");
2223 let pkg = root.path().join("pkgbin");
2224 fs::create_dir(&pkg).unwrap();
2225 symlink("../Cellar/bin/quipu", pkg.join("quipu")).unwrap();
2226 symlink("../other", pkg.join("qp")).unwrap();
2227 let err = verify_quipu_alias(&pkg.join("quipu")).unwrap_err();
2228 assert!(err.to_string().contains("same executable"));
2229 }
2230
2231 #[test]
2232 fn owned_layout_with_qp_beside_quipu_still_passes() {
2233 let root = tempfile::tempdir().unwrap();
2234 script(&root.path().join("quipu"), "quipu 1.0");
2235 symlink("quipu", root.path().join("qp")).unwrap();
2236 verify_quipu_alias(&root.path().join("quipu")).unwrap();
2237 }
2238}