Skip to main content

caboodle/
engine.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::{ffi::OsString, path::Path};
4
5use anyhow::{bail, Context, Result};
6use serde::Deserialize;
7
8use crate::{
9    adapter::adapter_for_plan,
10    configuration,
11    crew::{self, CrewEvidence},
12    embedding, emission,
13    model::{ModelArtifactState, Plan, ShareState, State, ToolState},
14};
15
16#[derive(Deserialize)]
17struct ImportPromotion {
18    eligible: bool,
19    blockers: Vec<String>,
20}
21
22#[derive(Deserialize)]
23struct ImportResult {
24    outcome: String,
25    share_id: String,
26    staging_graph: String,
27    promotion: ImportPromotion,
28}
29
30/// The bundle's `REVISION` says nothing about the `camayoc` CLI a shell runs,
31/// so a stale CLI is reported as NOT converged (aegis-mecge2.12).
32fn check_camayoc_cli(path: Option<&std::ffi::OsStr>) -> Result<()> {
33    let home = std::env::var_os("HOME").map(std::path::PathBuf::from);
34    if crate::adapter::camayoc_cli_check(path, home.as_deref())?.is_empty() {
35        println!("camayoc: note: no `camayoc` CLI on PATH or in ~/.local/bin");
36    }
37    Ok(())
38}
39
40/// What `apply` should do about an installed tool whose version is not the one
41/// this Tambo build reviewed (aegis-5ctwu3).
42///
43/// Split out as a pure function ON PURPOSE: the act it decides is a network
44/// download, so a test that drove `apply` end to end would be measuring GitHub
45/// rather than the decision. Every branch below is covered by a unit test; the
46/// branch that could not be, would not have been.
47#[derive(Debug, PartialEq, Eq)]
48pub(crate) enum Convergence {
49    /// Installed IS the reviewed release. Nothing to do.
50    Current,
51    /// Installed is strictly older. Converge upward, then prove by read-back.
52    Converge,
53    /// Installed is at or ahead of the reviewed release, or the two versions
54    /// are not comparable. Do NOT install — that would be a downgrade or a
55    /// replacement on a guess (aegis-48dvl3). Say so instead.
56    Decline,
57    /// Skewed, and the operator asked for no installs. A MISSING tool already
58    /// fails under `--skip-install`; a skewed one reporting "applied" was the
59    /// inconsistency this bead is about.
60    RefuseSkipInstall,
61}
62
63pub(crate) fn decide_convergence(
64    installed: &str,
65    desired: &str,
66    is_current: bool,
67    skip_install: bool,
68) -> Convergence {
69    if is_current {
70        return Convergence::Current;
71    }
72    if skip_install {
73        return Convergence::RefuseSkipInstall;
74    }
75    match crate::release_update::behind_reviewed(installed, desired) {
76        Some(true) => Convergence::Converge,
77        // `None` is "cannot compare", NOT "stale". Treating it as stale is how
78        // an unrecognised build gets replaced on a guess.
79        Some(false) | None => Convergence::Decline,
80    }
81}
82
83pub fn apply(plan: &Plan, state_path: &Path, skip_install: bool) -> Result<State> {
84    plan.validate()?;
85    let mut state = State::read(state_path)?;
86    let mut failures = Vec::new();
87    for &name in &plan.tools {
88        if name == crate::model::ToolName::Quipu && plan.external_quipu {
89            // A failed external path/version probe cannot retain an earlier proof.
90            state.tools.remove(name.as_str());
91            state.write(state_path)?;
92        }
93        let adapter = adapter_for_plan(name, plan)?;
94        let desired = adapter.desired_version();
95        // aegis-5ctwu3: PRESENCE IS NOT CONVERGENCE. Until this match looked at
96        // `is_current`, a binary that merely EXISTED was reported "applied" and
97        // left at whatever version it was — bobbin sat at 0.1.0 while this build
98        // reviewed 0.17.0, and `tambo install` then failed its own verify with
99        // `error: unexpected argument '--source' found`. The installer knew the
100        // newer contract, verified against it, and had never installed it; the
101        // operator got a clap error instead of "your bobbin is 16 minors old".
102        // `st doctor` had it right the whole time ("bobbin 0.1.0 installed —
103        // 0.17.0 available (STALE)"), which is the tell that this was never a
104        // detection problem.
105        let version = (|| -> Result<String> {
106            Ok(match adapter.version() {
107                Ok(installed) if adapter.is_current(&installed) => installed,
108
109                // Keep externally installed newer Bobbin builds without replacing
110                // them. Quickstart still requires the functional round-trip below;
111                // retaining a version never means it has been verified.
112                Ok(installed)
113                    if name == crate::model::ToolName::Bobbin
114                        && skip_install
115                        && crate::release_update::behind_reviewed(&desired, &installed)
116                            == Some(true) =>
117                {
118                    println!(
119                        "bobbin: warning: retaining newer installed {installed}; reviewed {desired}. \
120                         No installation performed; functional verification is still required."
121                    );
122                    installed
123                }
124
125                // Known-wrong under --skip-install. The flag means "do not install",
126                // not "call it applied anyway", and a MISSING tool already fails
127                // here — a SKEWED one reporting success was the inconsistency.
128                Ok(installed) => {
129                    match decide_convergence(&installed, &desired, false, skip_install) {
130                        Convergence::Current => installed,
131                        Convergence::RefuseSkipInstall => bail!(
132                        "{} is installed at {installed} but this Tambo build reviewed {desired}; \
133                         --skip-install refuses to converge it. Install {desired}, or drop \
134                         --skip-install to let apply converge it.",
135                        name.as_str()
136                    ),
137                        Convergence::Decline => {
138                            println!(
139                                "{}: NOT converged — installed {installed}, reviewed {desired}. \
140                             Apply does not downgrade or replace an unrecognised version; \
141                             use `tambo update-release` deliberately if that is what you want.",
142                                name.as_str()
143                            );
144                            installed
145                        }
146                        Convergence::Converge => {
147                            eprintln!(
148                                "{}: stale ({installed}); converging to reviewed {desired}",
149                                name.as_str()
150                            );
151                            adapter.install().with_context(|| {
152                                format!("{} convergence to reviewed {desired}", name.as_str())
153                            })?;
154                            let after = adapter.version().with_context(|| {
155                                format!("{} version read-back after convergence", name.as_str())
156                            })?;
157                            // The read-back is the proof, not the install's exit code.
158                            if !adapter.is_current(&after) {
159                                bail!(
160                                    "{} did not reach reviewed release {desired} (got {after}); \
161                                 refusing to record it as applied",
162                                    name.as_str()
163                                );
164                            }
165                            println!("{}: converged {installed} -> {after}", name.as_str());
166                            after
167                        }
168                    }
169                }
170
171                Err(error)
172                    if !skip_install
173                        && !(name == crate::model::ToolName::Quipu && plan.external_quipu) =>
174                {
175                    eprintln!("{}: not installed ({error:#}); installing", name.as_str());
176                    adapter
177                    .install()
178                    .with_context(|| {
179                        format!(
180                            "{} install step (run `tambo doctor` to list every blocker on this host)",
181                            name.as_str()
182                        )
183                    })?;
184                    adapter.version().with_context(|| {
185                        format!("{} version read-back after install", name.as_str())
186                    })?
187                }
188                Err(error) => {
189                    return Err(error).context(format!("{} version read-back", name.as_str()))
190                }
191            })
192        })();
193        // aegis-z1u9s0: the version above is the MANAGED copy's for a member, so
194        // a stale copy earlier on PATH left apply saying "applied" while the
195        // shell ran the older release. Apply is the step that says done; it
196        // checks what PATH runs, as verify does.
197        let version = version.and_then(|version| {
198            if name == crate::model::ToolName::Quipu && !plan.external_quipu {
199                // A current pair needs only its missing alias, never a downgrade
200                // to the older reviewed release just to add a command name.
201                if skip_install {
202                    crate::adapter::verify_existing_quipu_alias()?;
203                } else {
204                    crate::adapter::ensure_existing_quipu_alias()?;
205                }
206            }
207            if !(name == crate::model::ToolName::Quipu && plan.external_quipu) {
208                check_path_resolution(name)?;
209            }
210            Ok(version)
211        });
212        let version = match version {
213            Ok(version) => version,
214            Err(error) => {
215                // An earlier successful run is no longer evidence for this tool.
216                // Persist the invalidation before continuing with independent tools.
217                state.tools.remove(name.as_str());
218                state.write(state_path)?;
219                eprintln!("{}: FAILED: {error:#}", name.as_str());
220                failures.push(format!("{}: {error:#}", name.as_str()));
221                continue;
222            }
223        };
224        let remains_verified = state
225            .tools
226            .get(name.as_str())
227            .is_some_and(|previous| previous.version == version && previous.verified);
228        state.tools.insert(
229            name.as_str().to_owned(),
230            ToolState {
231                version,
232                applied: true,
233                verified: remains_verified,
234            },
235        );
236        state.write(state_path)?;
237        emission::queue_transition(
238            state_path,
239            name.as_str(),
240            "applied",
241            &state.tools[name.as_str()].version,
242        )?;
243        println!("{}: applied", name.as_str());
244    }
245    if !failures.is_empty() {
246        bail!(
247            "{} tool(s) failed to apply:\n{}\nSuccessful tools were saved. Fix the failures and rerun the same command. \
248             Stack configuration, model provisioning, crew setup, share imports and verification \
249             have not run; run `tambo doctor` for preflight guidance.",
250            failures.len(),
251            failures.join("\n")
252        );
253    }
254    if let Some(config) = &plan.stack_config {
255        configuration::apply(config)?;
256        println!("stack configuration: applied");
257    }
258    if let Some(model) = &plan.embedding_model {
259        let provisioned = embedding::provision(model, crate::adapter::download_https)
260            .context("embedding-model provisioning step")?;
261        for artifact in provisioned {
262            // Like tools, a re-fetch of identical pinned bytes keeps its
263            // verified mark; anything else must earn it again.
264            let remains_verified = state
265                .models
266                .get(&artifact.name)
267                .is_some_and(|previous| previous.sha256 == artifact.sha256 && previous.verified);
268            state.models.insert(
269                artifact.name.clone(),
270                ModelArtifactState {
271                    path: artifact.path.clone(),
272                    sha256: artifact.sha256.clone(),
273                    provisioned: true,
274                    verified: remains_verified,
275                },
276            );
277            state.write(state_path)?;
278            emission::queue_transition(
279                state_path,
280                &format!("embedding-model/{}", artifact.name),
281                "applied",
282                &artifact.sha256,
283            )?;
284            let outcome = match artifact.outcome {
285                embedding::ArtifactOutcome::Fetched => "provisioned",
286                embedding::ArtifactOutcome::Current => "current",
287            };
288            println!("embedding-model {}: {outcome}", artifact.name);
289        }
290    }
291    #[cfg(unix)]
292    if let Some(mcp) = &plan.quipu_mcp {
293        let outcome = crate::quipu_mcp::provision(&mcp.url, mcp.token_file.as_deref())
294            .context("quipu MCP registration step (headersHelper)")?;
295        println!("quipu mcp: {outcome}");
296    }
297    if let Some(selection) = &plan.crew {
298        crew::apply(selection, &mut state, skip_install)?;
299        state.write(state_path)?;
300        for (name, runtime) in &state.crew {
301            emission::queue_transition(state_path, name, "applied", &runtime.version)?;
302        }
303    }
304    // After the tools and crew (which may have just installed st): register the
305    // stack's hook bundles for the tools this plan installs (aegis-u1ybxo).
306    // Each tool's OWN bundle when the installed tool prints one (aegis-5s32or.5).
307    let resolved = crate::tool_bundles::resolve(&crate::hook_bundles::selected(
308        plan.tools.iter().map(|t| t.as_str()),
309    ));
310    for (name, _, source) in &resolved {
311        println!("hook bundle {name}: source {}", source.label());
312    }
313    for line in crate::hook_bundles::register(&crate::tool_bundles::as_pairs(&resolved), "st")? {
314        println!("hook bundle {line}");
315    }
316    // seeds + Desire Path: redirect habitual `bd` to `sd`, never overwriting a
317    // host's existing `bd` rule (aegis-fbaso4).
318    if crate::dp_alias::wanted(plan.tools.iter().map(|t| t.as_str())) {
319        let outcome = crate::dp_alias::apply(crate::dp_alias::locate().as_deref(), None)
320            .context("Desire Path bd -> sd alias step")?;
321        println!("dp alias {}", outcome.line());
322    }
323    load_vocabulary(plan)?;
324    consume_shares(plan, &mut state, state_path)?;
325    Ok(state)
326}
327
328/// Load the pinned Quechua vocabulary (aegis-1i5h1j.3) into the plan's Quipu
329/// store. It is part of Quipu: a plan without Quipu, or without a store to load
330/// into, loads nothing, and verify still proves the release round trip in a
331/// throwaway store.
332fn load_vocabulary(plan: &Plan) -> Result<()> {
333    if !plan.tools.contains(&crate::model::ToolName::Quipu) {
334        return Ok(());
335    }
336    let cached = crate::vocabulary::ensure_cached()?;
337    match plan.quipu_db.as_deref() {
338        Some(db) => {
339            crate::vocabulary::load(db)?;
340            println!(
341                "vocabulary: quechua v{} loaded into {}",
342                crate::vocabulary::QUECHUA_VERSION,
343                db.display()
344            );
345        }
346        None => println!(
347            "vocabulary: quechua v{} cached at {} (no plan quipu_db to load into)",
348            crate::vocabulary::QUECHUA_VERSION,
349            cached.display()
350        ),
351    }
352    Ok(())
353}
354
355fn consume_shares(plan: &Plan, state: &mut State, state_path: &Path) -> Result<()> {
356    let Some(db) = plan.quipu_db.as_deref() else {
357        return Ok(());
358    };
359    for share in &plan.shares {
360        let result = crate::adapter::checked(
361            "quipu",
362            [
363                OsString::from("import"),
364                share.as_os_str().to_owned(),
365                OsString::from("--db"),
366                db.as_os_str().to_owned(),
367            ],
368            None,
369        )
370        .with_context(|| format!("import canonical Quipu share {}", share.display()))?;
371        let imported: ImportResult = serde_json::from_slice(&result.stdout)
372            .with_context(|| format!("parse Quipu import result for {}", share.display()))?;
373        if !matches!(
374            imported.outcome.as_str(),
375            "staged" | "quarantined" | "unchanged"
376        ) {
377            bail!(
378                "Quipu returned unknown share import outcome {:?} for {}",
379                imported.outcome,
380                share.display()
381            );
382        }
383        state.shares.insert(
384            imported.share_id.clone(),
385            ShareState {
386                path: share.clone(),
387                staging_graph: imported.staging_graph,
388                outcome: imported.outcome.clone(),
389                promotion_eligible: imported.promotion.eligible,
390                blockers: imported.promotion.blockers,
391            },
392        );
393        state.write(state_path)?;
394        println!(
395            "share {}: {} (promotion eligible: {})",
396            imported.share_id, imported.outcome, imported.promotion.eligible
397        );
398    }
399    Ok(())
400}
401
402/// Refuse to call a tool verified when the copy PATH runs is not the copy that
403/// was verified (aegis-70qlhs). A different file with the same version is a
404/// note, not a failure: it runs the same build.
405fn check_path_resolution(name: crate::model::ToolName) -> Result<()> {
406    let path = std::env::var_os("PATH");
407    if name == crate::model::ToolName::Camayoc {
408        check_camayoc_cli(path.as_deref())?;
409    }
410    for &program in crate::adapter::programs(name) {
411        match crate::adapter::path_resolution(program, path.as_deref()) {
412            crate::adapter::PathResolution::Managed => {}
413            crate::adapter::PathResolution::NotOnPath => println!(
414                "{}: note: `{program}` is not on PATH; add the install directory to PATH to run it",
415                name.as_str()
416            ),
417            crate::adapter::PathResolution::SameBuild { runs, managed } => println!(
418                "{}: note: PATH runs {} rather than {}, but both report the same version",
419                name.as_str(),
420                runs.display(),
421                managed.display()
422            ),
423            crate::adapter::PathResolution::Shadowed {
424                runs,
425                runs_version,
426                managed,
427                managed_version,
428            } => anyhow::bail!(
429                "{program} is SHADOWED: PATH runs {} ({}), not the verified {} ({}). \
430                 Remove the stale copy or put {} earlier on PATH",
431                runs.display(),
432                runs_version.trim(),
433                managed.display(),
434                managed_version.trim(),
435                managed
436                    .parent()
437                    .map(|d| d.display().to_string())
438                    .unwrap_or_default()
439            ),
440        }
441    }
442    Ok(())
443}
444
445pub fn verify(plan: &Plan, state_path: &Path, evidence: &CrewEvidence) -> Result<State> {
446    plan.validate()?;
447    let mut state = State::read(state_path)?;
448    // The hook bundles apply registers for the plan's tools (aegis-u1ybxo).
449    // Asserted for every plan, as apply registers for every plan, and FIRST:
450    // it is independent of the tools' functional checks, and a skewed tool
451    // failing below must not hide whether the hooks are registered (measured
452    // on a fresh Mac, where a bobbin skew left the bundles never asserted).
453    for line in hook_bundles_verify(plan)? {
454        println!("hook bundle {line}");
455    }
456    if plan.tools.contains(&crate::model::ToolName::Quipu) && plan.requires_remote_quipu() {
457        if let Some(record) = state.tools.get_mut("quipu") {
458            record.verified = false;
459            state.write(state_path)?;
460        }
461        let server = std::env::var("QUIPU_SERVER")
462            .ok()
463            .filter(|url| !url.trim().is_empty())
464            .unwrap_or_else(|| {
465                plan.quipu_mcp
466                    .as_ref()
467                    .map(|mcp| mcp.url.clone())
468                    .unwrap_or_else(|| "http://localhost:3030".to_owned())
469            });
470        let source = crate::quipu_credential::verify(&server)
471            .context("live Quipu client credential verification")?;
472        println!("quipu credential: canonical file 0400/0700 and authenticated read verified; source: {source}");
473    }
474    for &name in &plan.tools {
475        if name == crate::model::ToolName::Quipu && plan.external_quipu {
476            // A failed external path/version probe cannot retain an earlier proof.
477            state.tools.remove(name.as_str());
478            state.write(state_path)?;
479        }
480        let adapter = adapter_for_plan(name, plan)?;
481        let version = adapter
482            .version()
483            .with_context(|| format!("{} version read-back", name.as_str()))?;
484        // aegis-5ctwu3 item 3. A verification failure on a SKEWED tool used to
485        // surface the tool's own complaint — `error: unexpected argument
486        // '--source' found` — which points at an argument, not at the cause. We
487        // verify against the contract of the release we reviewed, so when the
488        // installed version is not that release, the skew IS the finding and
489        // must be said first.
490        adapter.verify().with_context(|| {
491            let desired = adapter.desired_version();
492            if adapter.is_current(&version) {
493                format!("{} functional verification", name.as_str())
494            } else {
495                format!(
496                    "{} functional verification — VERSION SKEW: {version} is installed, \
497                     this Tambo build reviewed and verifies against {desired}. The error \
498                     below is most likely that skew, not a broken tool. Converge with \
499                     `tambo apply` (or `tambo update`), then re-verify.",
500                    name.as_str()
501                )
502            }
503        })?;
504        if !(name == crate::model::ToolName::Quipu && plan.external_quipu) {
505            check_path_resolution(name)?;
506        }
507        state.tools.insert(
508            name.as_str().to_owned(),
509            ToolState {
510                version,
511                applied: true,
512                verified: true,
513            },
514        );
515        state.write(state_path)?;
516        emission::queue_transition(
517            state_path,
518            name.as_str(),
519            "verified",
520            &state.tools[name.as_str()].version,
521        )?;
522        println!("{}: verified", name.as_str());
523    }
524    // After the tools: Desire Path itself was verified above (aegis-fbaso4).
525    if crate::dp_alias::wanted(plan.tools.iter().map(|t| t.as_str())) {
526        let outcome = crate::dp_alias::verify(crate::dp_alias::locate().as_deref(), None)
527            .context("Desire Path bd -> sd alias")?;
528        println!("dp alias {}", outcome.line());
529    }
530    if let Some(model) = &plan.embedding_model {
531        // This is deliberately a re-hash, not an embed round-trip; see
532        // embedding::verify for why claiming more would be a banner.
533        embedding::verify(model).context("embedding-model artifact re-hash step")?;
534        for artifact in &model.artifacts {
535            state.models.insert(
536                artifact.name.clone(),
537                ModelArtifactState {
538                    path: model.destination.join(&artifact.name),
539                    sha256: artifact.sha256.clone(),
540                    provisioned: true,
541                    verified: true,
542                },
543            );
544            state.write(state_path)?;
545            emission::queue_transition(
546                state_path,
547                &format!("embedding-model/{}", artifact.name),
548                "verified",
549                &artifact.sha256,
550            )?;
551            println!("embedding-model {}: digest re-checked", artifact.name);
552        }
553    }
554    #[cfg(unix)]
555    if let Some(mcp) = &plan.quipu_mcp {
556        let notes = crate::quipu_mcp::verify(&mcp.url)
557            .context("quipu MCP authenticated-write probe (headersHelper)")?;
558        for note in notes {
559            println!("quipu mcp: {note}");
560        }
561        println!("quipu mcp: authenticated MCP write reached Quipu's parser; unauthenticated control was refused");
562    }
563    if let Some(selection) = &plan.crew {
564        crew::verify(selection, evidence, &mut state)?;
565        state.write(state_path)?;
566        for (name, runtime) in &state.crew {
567            emission::queue_transition(state_path, name, "verified", &runtime.version)?;
568        }
569    }
570    Ok(state)
571}
572
573/// Compare the running toolchain to the releases reviewed by this Tambo
574/// build. Returns true only when every selected tool is current.
575pub(crate) fn reviewed_drift_status(installed: &str, desired: &str) -> &'static str {
576    match crate::release_update::behind_reviewed(installed, desired) {
577        Some(true) => "update available",
578        Some(false) if crate::release_update::behind_reviewed(desired, installed) == Some(true) => {
579            "ahead of reviewed pin; downgrade refused"
580        }
581        Some(false) | None => "version drift; review required",
582    }
583}
584
585/// A tool whose binary a package manager owns is judged by its package receipt
586/// and never installed by Tambo (aegis-6f1, option A): the package lane is
587/// its only writer. Returns the line to print and whether it is current.
588fn package_owned_status(name: crate::model::ToolName, desired: &str) -> Option<(String, bool)> {
589    use crate::package::{apt_receipt, primary_program, standing, Standing};
590    let receipt = primary_program(name)
591        .and_then(|program| apt_receipt(&program))
592        .or_else(|| crate::package::brew_receipt(name))?;
593    let status = standing(&receipt.version, desired);
594    let verdict = match status {
595        Standing::Current => "current",
596        Standing::Ahead => "ahead of reviewed pin; downgrade refused",
597        Standing::Behind => {
598            "behind reviewed pin; delivered by the package lane, not installed by Tambo"
599        }
600        Standing::Unknown => "version drift; review required",
601    };
602    Some((
603        format!(
604            "{}: {verdict} (package-owned: {} {} {}; reviewed: {desired})",
605            name.as_str(),
606            receipt.manager,
607            receipt.package,
608            receipt.version
609        ),
610        status == Standing::Current,
611    ))
612}
613
614/// Member delivery through the stack's Homebrew tap (aegis-6f1). Applies only
615/// where Tambo may drive brew and the tool has a stack formula. Returns the
616/// verified version when brew delivered (or already holds) the tool, `None` to
617/// fall back to the other lanes (the release download when the tap is older
618/// than the pin). Never downgrades.
619/// Link an unlinked keg, or fail the member with why it is still unlinked:
620/// verify would otherwise fail opaquely on the missing command.
621fn relink_or_fail(
622    name: crate::model::ToolName,
623    relink: fn(crate::model::ToolName) -> std::result::Result<String, String>,
624) -> Result<()> {
625    match relink(name) {
626        Ok(done) => {
627            println!("{}: keg was not linked; {done}", name.as_str());
628            Ok(())
629        }
630        Err(why) => anyhow::bail!("{} brew keg is not linked: {why}", name.as_str()),
631    }
632}
633
634fn brew_update(
635    name: crate::model::ToolName,
636    adapter: &dyn crate::adapter::Adapter,
637) -> Result<Option<String>> {
638    use crate::package::{
639        brew_channel, brew_converge, brew_formula, brew_program, brew_relink, standing, Standing,
640    };
641    if brew_formula(name).is_none() || brew_program().is_none() {
642        return Ok(None);
643    }
644    let Some(channel) = brew_channel(name)? else {
645        return Ok(None);
646    };
647    let desired = adapter.desired_version();
648    let stable = format!("pkg {}", channel.stable);
649    if channel.pinned {
650        let installed = channel
651            .installed
652            .context("pinned brew formula has no installed receipt")?;
653        println!(
654            "{}: pinned Homebrew formula; update skipped ({} {}; stable: {})",
655            name.as_str(),
656            crate::package::STACK_TAP,
657            installed,
658            channel.stable
659        );
660        return brew_version(adapter, &installed).map(Some);
661    }
662    match channel.installed {
663        Some(installed) => match standing(&installed, &stable) {
664            Standing::Behind => {
665                // A tap older than the minimum reviewed release cannot deliver
666                // it; keep the existing package ownership/fallback decision.
667                if standing(&channel.stable, &desired) == Standing::Behind {
668                    return Ok(None);
669                }
670                brew_converge(name, true)?;
671            }
672            Standing::Current | Standing::Ahead => {
673                let word = if standing(&installed, &stable) == Standing::Ahead {
674                    "ahead of stable channel; downgrade refused"
675                } else {
676                    "current stable channel"
677                };
678                println!(
679                    "{}: {word} (package-owned: brew {} {}; stable: {})",
680                    name.as_str(),
681                    crate::package::STACK_TAP,
682                    installed,
683                    channel.stable
684                );
685                if channel.unlinked {
686                    // aegis-f0ne: an interrupted brew step left the keg off PATH.
687                    relink_or_fail(name, brew_relink)?;
688                }
689                return brew_version(adapter, &installed).map(Some);
690            }
691            Standing::Unknown => {
692                anyhow::bail!("{} brew versions cannot be compared", name.as_str())
693            }
694        },
695        None => {
696            if standing(&channel.stable, &desired) == Standing::Behind {
697                return Ok(None);
698            }
699            if let Ok(installed) = adapter.version() {
700                if crate::release_update::behind_reviewed(&stable, &installed) == Some(true) {
701                    println!(
702                        "{}: installed {installed} is newer than {} {}; not installed by brew",
703                        name.as_str(),
704                        crate::package::STACK_TAP,
705                        channel.stable
706                    );
707                    return Ok(Some(installed));
708                }
709            }
710            brew_converge(name, false)?;
711        }
712    }
713    let after = brew_channel(name)?.context("brew channel after delivery")?;
714    if after.unlinked {
715        // aegis-f0ne: `brew upgrade` keeps an unlinked keg unlinked, so a
716        // successful delivery can still leave the tool off PATH.
717        relink_or_fail(name, brew_relink)?;
718    }
719    let receipt = after.installed.context("brew receipt after delivery")?;
720    if !matches!(
721        standing(&receipt, &stable),
722        Standing::Current | Standing::Ahead
723    ) {
724        anyhow::bail!(
725            "{} brew update did not reach stable {} (receipt: {receipt})",
726            name.as_str(),
727            channel.stable
728        );
729    }
730    // Resolve after delivery: a fresh package install creates the PATH pair.
731    let package_adapter = adapter.package_adapter()?;
732    let adapter = package_adapter.as_deref().unwrap_or(adapter);
733    adapter
734        .verify()
735        .with_context(|| format!("{} verification after brew delivery", name.as_str()))?;
736    let version = brew_version(adapter, &receipt)?;
737    println!(
738        "{}: delivered by brew ({} {}) and verified",
739        name.as_str(),
740        crate::package::STACK_TAP,
741        receipt
742    );
743    Ok(Some(version))
744}
745
746fn brew_version(adapter: &dyn crate::adapter::Adapter, receipt: &str) -> Result<String> {
747    // Current/pinned reads also use the package pair, never an unrelated
748    // Cargo copy. This is deliberately lazy until a read-back is needed.
749    let package_adapter = adapter.package_adapter()?;
750    let adapter = package_adapter.as_deref().unwrap_or(adapter);
751    let version = adapter
752        .version()
753        .context("version read-back after brew delivery")?;
754    // Quipu reports its client and server as two semicolon-separated
755    // identities. Check both; a plain version line must not absorb the
756    // separator, and a current client must not hide a stale server.
757    let identities: Vec<_> = if adapter.name() == crate::model::ToolName::Quipu {
758        version.split(';').take(2).collect()
759    } else {
760        vec![version.as_str()]
761    };
762    if identities.iter().any(|identity| {
763        crate::package::standing(receipt, identity.trim()) != crate::package::Standing::Current
764    }) {
765        anyhow::bail!("brew receipt and executable version disagree");
766    }
767    Ok(version)
768}
769
770pub fn check_updates(plan: &Plan) -> Result<bool> {
771    plan.validate()?;
772    let mut current = true;
773    for &name in &plan.tools {
774        let adapter = adapter_for_plan(name, plan)?;
775        let desired = adapter.desired_version();
776        if name == crate::model::ToolName::Quipu && plan.external_quipu {
777            println!(
778                "quipu: externally owned; release convergence not assessed ({})",
779                adapter.version()?
780            );
781            continue;
782        }
783        if let Some((line, is_current)) = package_owned_status(name, &desired) {
784            current &= is_current;
785            println!("{line}");
786            continue;
787        }
788        match adapter.version() {
789            Ok(installed) if adapter.is_current(&installed) => {
790                println!("{}: current ({installed})", name.as_str());
791            }
792            Ok(installed) => {
793                current = false;
794                println!(
795                    "{}: {} (installed: {installed}; reviewed: {desired})",
796                    name.as_str(),
797                    reviewed_drift_status(&installed, &desired)
798                );
799            }
800            Err(error) => {
801                current = false;
802                println!(
803                    "{}: missing or unreadable ({error:#}); reviewed: {desired}",
804                    name.as_str()
805                );
806            }
807        }
808    }
809    if let Some(selection) = &plan.crew {
810        current &= crew::check_updates(selection);
811    }
812    Ok(current)
813}
814
815/// Converge drifted tools to the reviewed releases and functionally verify
816/// each changed tool before recording it as current.
817pub fn update(plan: &Plan, state_path: &Path, evidence: &CrewEvidence) -> Result<State> {
818    plan.validate()?;
819    let mut state = State::read(state_path)?;
820    if crate::package::brew_program().is_some()
821        && plan.tools.iter().any(|name| {
822            crate::package::brew_formula(*name).is_some()
823                && !(*name == crate::model::ToolName::Quipu && plan.external_quipu)
824        })
825    {
826        crate::package::brew_refresh()?;
827    }
828    // A stale `camayoc` CLI must fail update, but not skip later members or
829    // drop the state of a bundle that did install; it fails at the end.
830    let mut camayoc_cli: Option<anyhow::Error> = None;
831    for &name in &plan.tools {
832        let adapter = adapter_for_plan(name, plan)?;
833        if name == crate::model::ToolName::Quipu && plan.external_quipu {
834            println!(
835                "quipu: externally owned; update skipped ({})",
836                adapter.version()?
837            );
838            continue;
839        }
840        if let Some(version) = brew_update(name, adapter.as_ref())? {
841            state.tools.insert(
842                name.as_str().to_owned(),
843                ToolState {
844                    version: version.clone(),
845                    applied: true,
846                    verified: true,
847                },
848            );
849            state.write(state_path)?;
850            emission::queue_transition(state_path, name.as_str(), "updated", &version)?;
851            continue;
852        }
853        if let Some((line, _)) = package_owned_status(name, &adapter.desired_version()) {
854            println!("{line}");
855            continue;
856        }
857        let before = adapter.version().ok();
858        if before
859            .as_deref()
860            .is_some_and(|installed| adapter.is_current(installed))
861        {
862            if name == crate::model::ToolName::Quipu {
863                crate::adapter::ensure_existing_quipu_alias()?;
864            }
865            if name == crate::model::ToolName::Camayoc {
866                camayoc_cli = check_camayoc_cli(std::env::var_os("PATH").as_deref()).err();
867            }
868            println!("{}: current", name.as_str());
869            continue;
870        }
871        #[cfg(unix)]
872        crate::release_update::guard_reviewed_update(name, &adapter.desired_version())?;
873        eprintln!(
874            "{}: converging {:?} -> {}",
875            name.as_str(),
876            before,
877            adapter.desired_version()
878        );
879        adapter
880            .install()
881            .with_context(|| format!("{} reviewed update install", name.as_str()))?;
882        let version = adapter
883            .version()
884            .with_context(|| format!("{} version read-back after update", name.as_str()))?;
885        if !adapter.is_current(&version) {
886            bail!(
887                "{} update did not reach reviewed release {} (got {})",
888                name.as_str(),
889                adapter.desired_version(),
890                version
891            );
892        }
893        adapter
894            .verify()
895            .with_context(|| format!("{} verification after update", name.as_str()))?;
896        if name == crate::model::ToolName::Camayoc {
897            camayoc_cli = check_camayoc_cli(std::env::var_os("PATH").as_deref()).err();
898        }
899        state.tools.insert(
900            name.as_str().to_owned(),
901            ToolState {
902                version: version.clone(),
903                applied: true,
904                verified: true,
905            },
906        );
907        state.write(state_path)?;
908        emission::queue_transition(state_path, name.as_str(), "updated", &version)?;
909        println!("{}: updated and verified", name.as_str());
910    }
911    if let Some(selection) = &plan.crew {
912        if !crew::check_updates(selection) {
913            crew::apply(selection, &mut state, false)?;
914            crew::verify(selection, evidence, &mut state)?;
915            for line in hook_bundles_verify(plan)? {
916                println!("hook bundle {line}");
917            }
918            state.write(state_path)?;
919            for (name, runtime) in &state.crew {
920                emission::queue_transition(state_path, name, "updated", &runtime.version)?;
921            }
922        }
923    }
924    if let Some(error) = camayoc_cli {
925        return Err(error);
926    }
927    Ok(state)
928}
929
930fn hook_bundles_verify(plan: &Plan) -> Result<Vec<String>> {
931    let resolved = crate::tool_bundles::resolve(&crate::hook_bundles::selected(
932        plan.tools.iter().map(|t| t.as_str()),
933    ));
934    crate::hook_bundles::verify(&crate::tool_bundles::as_pairs(&resolved))
935}
936
937pub fn verify_questions(plan: &Plan, db: Option<&Path>) -> Result<()> {
938    plan.validate()?;
939    let intent = plan.intent.as_ref().context(
940        "plan has no intended-use/question contract; regenerate it through the Phase 2 interview",
941    )?;
942    for (index, contract) in intent.anticipated_questions.iter().enumerate() {
943        // The self-test question is about the stack, not the user's graph, so it
944        // always runs against a scratch store seeded with its own fact.
945        let scratch = if contract.is_self_test() {
946            Some(seed_self_test_store()?)
947        } else {
948            None
949        };
950        let db = scratch.as_ref().map(|(_, db)| db.as_path()).or(db);
951        let mut args = vec![OsString::from("read"), OsString::from(&contract.sparql)];
952        if let Some(db) = db {
953            args.push(OsString::from("--db"));
954            args.push(db.as_os_str().to_owned());
955        }
956        let result = crate::adapter::checked("quipu", args, None)
957            .with_context(|| format!("anticipated question {} query", index + 1))?;
958        let answer = String::from_utf8_lossy(&result.stdout);
959        if !answer.contains(&contract.expected) {
960            anyhow::bail!(
961                "anticipated question {} was executable but its answer did not contain {:?}: {}",
962                index + 1,
963                contract.expected,
964                contract.question
965            );
966        }
967        println!("question {}: verified — {}", index + 1, contract.question);
968    }
969    Ok(())
970}
971
972/// A throwaway Quipu store holding exactly the self-test fact. The tempdir is
973/// returned so it lives as long as the query that reads it.
974fn seed_self_test_store() -> Result<(tempfile::TempDir, std::path::PathBuf)> {
975    use crate::model::SELF_TEST_MARKER;
976    let dir = tempfile::tempdir().context("create self-test question store")?;
977    let db = dir.path().join("self-test.db");
978    let episode = dir.path().join("episode.json");
979    std::fs::write(
980        &episode,
981        format!(
982            r#"{{"name":"Tambo self-test question","episode_body":"self-test seed","source":"caboodle","group_id":"caboodle-verification","nodes":[{{"name":"{SELF_TEST_MARKER}","type":"Verification","description":"Tambo self-test question seed"}}],"edges":[]}}"#
983        ),
984    )
985    .context("write self-test episode")?;
986    crate::adapter::checked(
987        "quipu",
988        [
989            OsString::from("episode"),
990            episode.into_os_string(),
991            OsString::from("--db"),
992            db.clone().into_os_string(),
993        ],
994        None,
995    )
996    .context("seed the self-test question store")?;
997    Ok((dir, db))
998}
999
1000/// Provision a pre-issued client credential; never mint or rotate an identity.
1001pub fn provision_quipu_credential(source: &Path, server: &str) -> Result<()> {
1002    let home = std::env::var_os("HOME").context("HOME required for canonical Quipu credential")?;
1003    crate::quipu_credential::provision(source, server, Path::new(&home))?;
1004    println!(
1005        "quipu credential: issued file accepted and canonical installation verified (0400/0700)"
1006    );
1007    Ok(())
1008}
1009
1010#[cfg(test)]
1011mod convergence_tests {
1012    use super::{decide_convergence, reviewed_drift_status, Convergence};
1013
1014    const REVIEWED: &str = "bobbin 0.16.2";
1015
1016    #[test]
1017    fn reviewed_drift_never_proposes_a_downgrade_or_unknown_replacement() {
1018        assert_eq!(
1019            reviewed_drift_status("sd 0.1.4 (seeds)", "seeds 0.0.4"),
1020            "ahead of reviewed pin; downgrade refused"
1021        );
1022        assert_eq!(
1023            reviewed_drift_status("sd 0.0.3", "seeds 0.0.4"),
1024            "update available"
1025        );
1026        for installed in ["sd dev", "sd 0.0.4", "sd 0.0.4-rc1"] {
1027            assert_eq!(
1028                reviewed_drift_status(installed, "seeds 0.0.4"),
1029                "version drift; review required"
1030            );
1031        }
1032    }
1033
1034    #[test]
1035    fn current_is_left_alone_even_under_skip_install() {
1036        // Unreachable from apply today (is_current is matched first), which is why
1037        // this branch is covered here rather than deleted as apparently dead.
1038        assert_eq!(
1039            decide_convergence(REVIEWED, REVIEWED, true, true),
1040            Convergence::Current
1041        );
1042        assert_eq!(
1043            decide_convergence(REVIEWED, REVIEWED, true, false),
1044            Convergence::Current
1045        );
1046    }
1047
1048    #[test]
1049    fn stale_converges_and_skip_install_refuses_instead_of_claiming_applied() {
1050        assert_eq!(
1051            decide_convergence("bobbin 0.1.0", REVIEWED, false, false),
1052            Convergence::Converge
1053        );
1054        assert_eq!(
1055            decide_convergence("bobbin 0.1.0", REVIEWED, false, true),
1056            Convergence::RefuseSkipInstall
1057        );
1058    }
1059
1060    #[test]
1061    fn ahead_or_incomparable_is_declined_not_replaced() {
1062        assert_eq!(
1063            decide_convergence("bobbin 0.99.0", REVIEWED, false, false),
1064            Convergence::Decline
1065        );
1066        assert_eq!(
1067            decide_convergence("bobbin dev", REVIEWED, false, false),
1068            Convergence::Decline
1069        );
1070    }
1071}