Skip to main content

borg/
install.rs

1//! Wiring borg into a harness, and seeing whether it works:
2//! `borg install|uninstall <harness|all> [--apply] [--home DIR]`, `borg status`, `borg doctor`.
3//!
4//! The wiring is exactly what each adapter README describes, written into the engineer's *user* config,
5//! as each harness's module says (harness/): command hooks merged into a JSON file (Claude Code's
6//! `~/.claude/settings.json`, each running `<this borg> hook claude <event>`), or a compiled-in adapter
7//! copied whole (omp's extension, opencode's plugin), plus the `borg` skill wherever the harness loads
8//! skills (`install/skill.rs`). An installed borg needs no checkout.
9//!
10//! Someone else's config is precious, so: the default is a dry run that prints the exact diff;
11//! `--apply` first writes a timestamped backup next to every file it changes; merging keeps every
12//! other key and hook as it was; re-running changes nothing; uninstall removes only what install adds
13//! (borg's own hook commands, and adapter and skill files whose content is this borg's). `--home`
14//! replaces HOME *and ignores every config-dir variable* (the harnesses' and `$BORG_HOME`/`$BORG_CONFIG`,
15//! see [`home_overrides`]), so a test can never reach a real config or store.
16
17pub mod change;
18mod orphans;
19pub mod setup;
20pub mod skill;
21
22use std::collections::{BTreeMap, BTreeSet, HashMap};
23use std::path::{Path, PathBuf};
24use std::time::Duration;
25
26use serde_json::Value;
27
28use crate::collective::{self, Route, Share};
29pub use crate::harness::Level;
30use crate::harness::wiring::Hooks;
31use crate::harness::{self, Harness, Wiring};
32use crate::{learn, outcome};
33use change::read;
34pub use change::{Action, Change, apply, diff};
35
36/// `all` (every visible harness) or one harness by name.
37fn parse(s: &str) -> Option<Vec<&'static dyn Harness>> {
38    match s {
39        "all" => Some(harness::visible().collect()),
40        _ => harness::by_name(s).map(|h| vec![h]),
41    }
42}
43
44/// Where the harnesses read their user config.
45#[derive(Debug, Clone)]
46pub struct Targets {
47    home: PathBuf,
48    /// Whether each harness's own config-dir variables count (not under `--home`).
49    env: bool,
50}
51
52fn var(k: &str) -> Option<PathBuf> {
53    std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from)
54}
55
56impl Targets {
57    /// Everything under `home`, no environment consulted (tests, `--home`).
58    pub fn under(home: &Path) -> Self {
59        Targets { home: home.to_path_buf(), env: false }
60    }
61
62    /// The real locations, honouring each harness's own config-dir variables.
63    pub fn from_env() -> Self {
64        Targets { home: var("HOME").unwrap_or_default(), env: true }
65    }
66
67    pub fn path(&self, h: &dyn Harness) -> PathBuf {
68        h.target(&self.home, &|k| if self.env { var(k) } else { None })
69    }
70
71    /// Where `h` loads the `borg` skill from; None for a harness without skills.
72    pub fn skill_dir(&self, h: &dyn Harness) -> Option<PathBuf> {
73        skill::dir(h, &self.home, &|k| if self.env { var(k) } else { None })
74    }
75}
76
77// ---------------------------------------------------------------- plans
78
79/// What `action` would change for `h`: its hook config or adapter first, then each skill file
80/// (`install/skill.rs`); plus notes: things deliberately left alone, and on install the steps the harness
81/// itself asks of the engineer (`Harness::install_notes`).
82pub fn plan(action: Action, h: &dyn Harness, t: &Targets, bin: &Path) -> Result<(Vec<Change>, Vec<String>), String> {
83    let path = t.path(h);
84    let before = read(&path).map_err(|e| format!("{}: cannot read ({e}); nothing was changed", path.display()))?;
85    let mut notes = Vec::new();
86    let after = match (Hooks::of(h), action) {
87        (Some(k), Action::Install) => k.install(before.as_deref(), bin)?.map(Some),
88        (Some(k), Action::Uninstall) => k.uninstall(before.as_deref())?,
89        (None, Action::Install) => (before.as_deref() != Some(h.wiring().adapter())).then(|| Some(h.wiring().adapter().to_string())),
90        (None, Action::Uninstall) => match before.as_deref() {
91            Some(b) if b == h.wiring().adapter() => Some(None),
92            Some(_) => {
93                notes.push(format!("{}: left alone, its content is not this borg's adapter (yours, or an older borg's)", path.display()));
94                None
95            }
96            None => None,
97        },
98    };
99    let through_links = matches!(h.wiring(), Wiring::CommandHooks { through_links: true, .. });
100    let mut changes: Vec<Change> = after.map(|after| Change { path, before, after, through_links, backup: true }).into_iter().collect();
101    let (skill, left) = skill::plan(action, t.skill_dir(h).as_deref())?;
102    changes.extend(skill);
103    notes.extend(left);
104    if action == Action::Install {
105        notes.extend(h.install_notes());
106    }
107    Ok((changes, notes))
108}
109
110/// UTC `YYYYMMDDTHHMMSS` for an epoch-ms time (no time crate for one format).
111pub fn utc(ms: i64) -> String {
112    let secs = ms.div_euclid(1000);
113    let day_s = crate::clock::DAY_MS / 1000;
114    let (days, rem) = (secs.div_euclid(day_s), secs.rem_euclid(day_s));
115    let (y, m, d) = crate::clock::civil_from_days(days);
116    format!("{y:04}{m:02}{d:02}T{:02}{:02}{:02}", rem / 3600, rem % 3600 / 60, rem % 60)
117}
118
119fn human(ms: i64) -> String {
120    let s = utc(ms);
121    format!("{}-{}-{} {}:{}:{} UTC", &s[0..4], &s[4..6], &s[6..8], &s[9..11], &s[11..13], &s[13..15])
122}
123
124// ---------------------------------------------------------------- status
125
126#[derive(Debug, Default, PartialEq)]
127pub struct Stats {
128    pub lessons: usize,
129    pub episodes: usize,
130    pub outcomes: usize,
131    pub last_capture_ms: Option<i64>,
132    /// When, and which lessons (`id: question`), the conscience last asked.
133    pub last_asked: Option<(i64, Vec<String>)>,
134}
135
136pub fn stats(home: &Path) -> Stats {
137    let lessons = learn::lessons(&home.join("lessons.jsonl"));
138    let episodes: Vec<Value> =
139        read(&home.join("episodes.jsonl")).ok().flatten().unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect();
140    let outcomes = outcome::read(&home.join("outcomes.jsonl"));
141    let last_asked = outcomes.iter().filter(|o| o.kind == outcome::ASKED).max_by_key(|o| o.ms).map(|o| {
142        let named = o.lessons.iter().map(|id| match lessons.iter().find(|l| &l.id == id) {
143            Some(l) => format!("{id}: {}", l.question.chars().take(100).collect::<String>()),
144            None => id.clone(),
145        });
146        (o.ms, named.collect())
147    });
148    Stats {
149        lessons: lessons.len(),
150        episodes: episodes.len(),
151        outcomes: outcomes.len(),
152        last_capture_ms: episodes.iter().filter_map(|e| e.get("ms").and_then(Value::as_i64)).max(),
153        last_asked,
154    }
155}
156
157/// Every collective with its store: those in the config, or the one "default" without a config.
158pub fn collectives(cfg: Option<&collective::Config>, base: &Path) -> Vec<Route> {
159    match cfg {
160        None => vec![Route::Collective { name: "default".into(), home: base.to_path_buf(), share: Share::Team }],
161        Some(c) => c.collectives.iter().map(|e| Route::Collective { name: e.name.clone(), home: collective::store(base, &e.name), share: e.share }).collect(),
162    }
163}
164
165/// How `h` is wired under `t`, in one line: its hooks or adapter, then its skill.
166pub fn wiring(h: &dyn Harness, t: &Targets) -> String {
167    let line = hooks_line(h, t);
168    match skill::status(h.name(), t.skill_dir(h).as_deref()) {
169        Some(skill) => format!("{line}; {skill}"),
170        None => line,
171    }
172}
173
174/// How `h`'s hooks or adapter are wired under `t`.
175fn hooks_line(h: &dyn Harness, t: &Targets) -> String {
176    let path = t.path(h);
177    let text = match read(&path) {
178        Ok(t) => t,
179        Err(e) => return format!("UNREADABLE: {} ({e})", path.display()),
180    };
181    let Some(k) = Hooks::of(h) else {
182        return match text {
183            None => format!("not wired ({})", path.display()),
184            Some(t) if t == h.wiring().adapter() => format!("wired: {}", path.display()),
185            Some(_) => format!("wired, but {} differs from this borg's adapter (older or edited)", path.display()),
186        };
187    };
188    let w = k.wired(text.as_deref());
189    let missing = k.missing(&w);
190    let events: Vec<&str> = k.events.iter().map(|(_, e)| *e).filter(|e| !missing.contains(e)).collect();
191    let mut bins: Vec<String> = w.iter().map(|(_, b)| b.display().to_string()).collect();
192    bins.dedup();
193    match events.len() {
194        0 => format!("not wired ({})", path.display()),
195        n if n == k.events.len() => format!("wired: {} -> {}", path.display(), bins.join(", ")),
196        _ => format!("PARTIAL ({} only): {} -> {}", events.join(","), path.display(), bins.join(", ")),
197    }
198}
199
200fn print_status(t: &Targets) {
201    let base = learn::home();
202    let cfg = collective::load();
203    match &cfg {
204        Err(e) => println!("COLLECTIVES CONFIG INVALID: {e}\n  every repo routes OFF: borg captures and asks nothing until it is fixed (borg doctor)"),
205        Ok(None) => println!("config: {} (absent: every repo is in collective \"default\")", collective::config_path().display()),
206        Ok(Some(c)) => println!("config: {} (default: {}, off: {:?})", collective::config_path().display(), c.default, c.off),
207    }
208    let routes = match &cfg {
209        Ok(c) => collectives(c.as_ref(), &base),
210        Err(_) => Vec::new(), // nothing is routed anywhere; listing stores would suggest otherwise
211    };
212    for r in routes {
213        let Route::Collective { name, home, share } = &r else { continue };
214        let s = stats(home);
215        println!("\ncollective {name} ({share:?}, may sync: {})", collective::may_sync(&r));
216        println!("  store        {}", home.display());
217        let m = crate::live::of(cfg.as_ref().ok().and_then(Option::as_ref), name);
218        let off = (m.mode == crate::live::Mode::Live).then(crate::live::unsupported).flatten();
219        let note = match (&m.warning, off) {
220            (Some(_), _) => "; unknown value, see borg doctor".to_string(),
221            (None, Some(why)) => format!("; off here: {why} replaces the consequence model, so checks run at the turn end only"),
222            (None, None) => String::new(),
223        };
224        println!("  mode         {} ({}){note}", m.mode.name(), m.source);
225        println!("  lessons      {}", s.lessons);
226        println!("  episodes     {}", s.episodes);
227        println!("  outcomes     {}", s.outcomes);
228        println!("  queen open   {}", crate::queen::open(home).len());
229        println!("  trust        {}", crate::trust::summary(home));
230        println!("  last capture {}", s.last_capture_ms.map(human).unwrap_or_else(|| "never".into()));
231        let g = crate::prefilter::tally(&home.join("state"));
232        println!("  stop gate    {} turn ends skipped at 0 tokens, {} asked the model (${:.2} so far)", g.skipped, g.asked, g.cost);
233        if g.live_checks > 0 {
234            println!("  live checks  {} during the turn, {} lessons read (${:.2} so far)", g.live_checks, g.live_lessons, g.live_cost);
235        }
236        println!(
237            "  cost         {} extra rounds (Stop blocks, {} questions, ~{} tokens); {} free deliveries ({} lessons, ~{} tokens, no extra round)",
238            g.rounds,
239            g.questions,
240            g.block_chars / crate::whole::CHARS_PER_TOKEN,
241            g.free,
242            g.free_lessons,
243            g.free_chars / crate::whole::CHARS_PER_TOKEN
244        );
245        println!(
246            "  judge        {} model calls also judged {} asked lessons ({} settled; ~{} prompt tokens added, no extra call)",
247            g.judge_calls,
248            g.judged,
249            g.judge_resolved,
250            g.judge_chars / crate::whole::CHARS_PER_TOKEN
251        );
252        // The store's lesson selection (top.rs `selection`, tested there).
253        let selection = crate::top::selection(&home.join("lessons.jsonl"), crate::select::policy());
254        println!("  selection    {}", crate::top::selection_line(&selection));
255        match s.last_asked {
256            None => println!("  last asked   never"),
257            Some((ms, ids)) => {
258                println!("  last asked   {}", human(ms));
259                for l in ids {
260                    println!("               {l}");
261                }
262            }
263        }
264    }
265    println!("\nharnesses");
266    for &h in harness::ALL {
267        let line = wiring(h, t);
268        // A hidden harness (the simulated one) only once someone wired it.
269        if !h.hidden() || !line.starts_with("not wired") {
270            println!("  {:<9} {line}", h.name());
271        }
272    }
273}
274
275// ---------------------------------------------------------------- doctor
276
277#[cfg(unix)]
278fn executable(p: &Path) -> bool {
279    use std::os::unix::fs::PermissionsExt;
280    std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
281}
282
283#[cfg(not(unix))]
284fn executable(p: &Path) -> bool {
285    p.is_file()
286}
287
288pub fn which(name: &str) -> Option<PathBuf> {
289    std::env::split_paths(&std::env::var_os("PATH")?).map(|d| d.join(name)).find(|p| executable(p))
290}
291
292/// `borg-<part>` beside this borg, else on PATH: main.rs runs it, `borg setup` runs borg-mesh.
293#[must_use]
294pub fn sibling(part: &str) -> Option<PathBuf> {
295    let bin = format!("borg-{part}");
296    let beside = std::env::current_exe().ok().map(|e| e.with_file_name(&bin)).filter(|p| p.exists());
297    beside.or_else(|| which(&bin))
298}
299
300/// First line of `<cli> --version`, if it answers within 5 s.
301fn version(cli: &Path) -> Option<String> {
302    let mut child = std::process::Command::new(cli)
303        .arg("--version")
304        .stdin(std::process::Stdio::null())
305        .stdout(std::process::Stdio::piped())
306        .stderr(std::process::Stdio::null())
307        .spawn()
308        .ok()?;
309    for _ in 0..100 {
310        if child.try_wait().ok()?.is_some() {
311            let out = child.wait_with_output().ok()?;
312            return String::from_utf8_lossy(&out.stdout).lines().next().map(|l| l.trim().to_string());
313        }
314        std::thread::sleep(Duration::from_millis(50));
315    }
316    let _ = child.kill();
317    None
318}
319
320/// Checks on the wiring alone (pure: no PATH, no processes), so they can be tested on fixtures.
321/// `borg_found`: whether the adapters can find a borg (`$BORG_BIN` or PATH).
322pub fn wiring_checks(t: &Targets, borg_found: bool) -> Vec<(Level, String)> {
323    let mut out = Vec::new();
324    // Every harness: an unwired one adds nothing, so a hidden one shows only once someone wired it.
325    for &h in harness::ALL {
326        let found = match Hooks::of(h) {
327            Some(k) => hook_checks(h, &k, t),
328            None => adapter_checks(h, t, borg_found),
329        };
330        let skill = skill::checks(h.name(), t.skill_dir(h).as_deref(), !found.is_empty());
331        out.extend(found.into_iter().chain(skill));
332    }
333    if out.is_empty() {
334        out.push((Level::Warn, "no harness is wired to borg (borg install all)".into()));
335    }
336    out
337}
338
339/// A command-hook harness: its config readable and valid, every event wired, to a binary that runs.
340fn hook_checks(h: &dyn Harness, k: &Hooks, t: &Targets) -> Vec<(Level, String)> {
341    let (name, path) = (h.name(), t.path(h));
342    let mut out = Vec::new();
343    let text = read(&path).unwrap_or_else(|e| {
344        out.push((Level::Fail, format!("{name}: {}: cannot read ({e}); borg install will not touch it", path.display())));
345        None
346    });
347    if text.is_some()
348        && let Err(e) = k.parse(text.as_deref())
349    {
350        out.push((Level::Fail, format!("{name}: {}: {e}", path.display())));
351    }
352    let wired = k.wired(text.as_deref());
353    if wired.is_empty() {
354        return out;
355    }
356    let missing = k.missing(&wired);
357    if !missing.is_empty() {
358        out.push((Level::Warn, format!("{name}: hooks missing for {} (borg install {name})", missing.join(", "))));
359    }
360    let leftover = k.leftover(text.as_deref());
361    if !leftover.is_empty() {
362        out.push((
363            Level::Warn,
364            format!("{name}: an older borg's hooks for {} are still wired (borg install {name} --apply removes them)", leftover.join(", ")),
365        ));
366    }
367    for (ev, bin) in &wired {
368        if !executable(bin) {
369            out.push((
370                Level::Fail,
371                format!("{name}: hook {ev} runs {}, which does not exist or is not executable (borg install {name} --apply)", bin.display()),
372            ));
373        }
374    }
375    if out.iter().all(|(l, _)| *l == Level::Ok) {
376        out.push((Level::Ok, format!("{name}: hooks wired to {}", wired[0].1.display())));
377    }
378    out
379}
380
381/// An adapter harness: the installed file is this borg's adapter, and the adapter can find borg.
382fn adapter_checks(h: &dyn Harness, t: &Targets, borg_found: bool) -> Vec<(Level, String)> {
383    let (name, path) = (h.name(), t.path(h));
384    let text = match read(&path) {
385        Ok(Some(text)) => text,
386        Ok(None) => return Vec::new(),
387        Err(e) => return vec![(Level::Fail, format!("{name}: {}: cannot read ({e})", path.display()))],
388    };
389    let mut out = Vec::new();
390    if text != h.wiring().adapter() {
391        out.push((Level::Warn, format!("{name}: {} differs from this borg's adapter (borg install {name})", path.display())));
392    } else {
393        out.push((Level::Ok, format!("{name}: adapter installed at {}", path.display())));
394    }
395    if !borg_found {
396        out.push((Level::Fail, format!("{name}: the adapter finds borg via $BORG_BIN or PATH, and neither has one: it silently does nothing")));
397    }
398    out
399}
400
401/// Checks on the collectives config and stores.
402pub fn collective_checks(cfg: &Result<Option<collective::Config>, String>, base: &Path) -> Vec<(Level, String)> {
403    let mut out = Vec::new();
404    let cfg = match cfg {
405        Err(e) => {
406            out.push((
407                Level::Fail,
408                format!("COLLECTIVES CONFIG INVALID ({e}): EVERY repo routes OFF, borg captures and asks NOTHING anywhere until it is fixed"),
409            ));
410            return out;
411        }
412        Ok(c) => c.as_ref(),
413    };
414    match cfg {
415        None => out.push((Level::Ok, format!("collectives: no config at {}, every repo is in \"default\"", collective::config_path().display()))),
416        Some(c) => {
417            if c.default != "off" && !c.collectives.iter().any(|e| e.name == c.default) {
418                out.push((Level::Warn, format!("collectives: default \"{}\" names no collective, so unmatched repos route off", c.default)));
419            }
420            let mut names: Vec<&str> = c.collectives.iter().map(|e| e.name.as_str()).collect();
421            names.sort();
422            if names.windows(2).any(|w| w[0] == w[1]) {
423                out.push((Level::Warn, "collectives: a name appears twice; their stores are shared".into()));
424            }
425            out.push((Level::Ok, format!("collectives: {} configured ({})", c.collectives.len(), names.join(", "))));
426        }
427    }
428    for r in collectives(cfg, base) {
429        let Route::Collective { name, home, .. } = &r else { continue };
430        let m = crate::live::of(cfg, name);
431        match m.warning {
432            Some(w) => out.push((Level::Warn, format!("collective {name}: {w}"))),
433            None => out.push((Level::Ok, format!("collective {name}: delivery mode {} ({})", m.mode.name(), m.source))),
434        }
435        // Live mode cannot run without the consequence model; the hook only notes it on stderr, which the
436        // agent's UI does not show.
437        if m.mode == crate::live::Mode::Live
438            && let Some(why) = crate::live::unsupported()
439        {
440            out.push((Level::Warn, format!("collective {name}: live mode is off while {why} is set; its drones check at the turn end only (hook mode)")));
441        }
442        out.extend(orphans::store_checks(name, home));
443        let probe = home.join(".borg-doctor-probe");
444        let ok = std::fs::create_dir_all(home).and_then(|_| std::fs::write(&probe, b"ok")).and_then(|_| std::fs::remove_file(&probe));
445        match ok {
446            Ok(()) => out.push((Level::Ok, format!("store {name}: {} writable", home.display()))),
447            Err(e) => out.push((Level::Fail, format!("store {name}: {} not writable ({e})", home.display()))),
448        }
449    }
450    out
451}
452
453/// Every engineer email a store records (lessons' authors and joiners, episodes), as written.
454pub fn store_emails(home: &Path) -> BTreeSet<String> {
455    let mut out = BTreeSet::new();
456    for l in learn::lessons(&home.join("lessons.jsonl")) {
457        out.extend(l.engineers.into_iter().chain(l.joined.into_keys()));
458    }
459    let episodes = read(&home.join("episodes.jsonl")).ok().flatten().unwrap_or_default();
460    for v in episodes.lines().filter_map(|l| serde_json::from_str::<Value>(l).ok()) {
461        out.extend(v.get("engineer").and_then(Value::as_str).map(str::to_string));
462    }
463    out.retain(|e| !e.trim().is_empty());
464    out
465}
466
467/// Hints for emails in the stores that share a git user.name (`identities`: name, email pairs) but
468/// are not yet one engineer under the config's `engineers` (collective.rs "Engineers").
469pub fn alias_hints(emails: &BTreeSet<String>, identities: &[(String, String)], aliases: &collective::Aliases) -> Vec<String> {
470    let stored: HashMap<String, &String> = emails.iter().map(|e| (e.trim().to_lowercase(), e)).collect();
471    // name (lowercased) -> (name as written, canonical engineer -> an email as the store has it)
472    let mut by_name: BTreeMap<String, (&str, BTreeMap<String, &str>)> = BTreeMap::new();
473    for (name, email) in identities {
474        let Some(raw) = stored.get(&email.trim().to_lowercase()) else { continue };
475        if name.trim().is_empty() {
476            continue;
477        }
478        let entry = by_name.entry(name.trim().to_lowercase()).or_insert((name.trim(), BTreeMap::new()));
479        entry.1.entry(aliases.canon(raw)).or_insert(raw.as_str());
480    }
481    by_name
482        .into_values()
483        .filter(|(_, ids)| ids.len() > 1)
484        .map(|(name, ids)| {
485            let listed: Vec<String> = ids.values().map(|e| format!("{e:?}")).collect();
486            format!(
487                "engineers: git user {name:?} appears in the stores as {}; if that is one engineer, add {{\"engineers\": [{{\"name\": \"...\", \"emails\": [{}]}}]}} to {} so trust and status count them once",
488                listed.join(" and "),
489                listed.join(", "),
490                collective::config_path().display()
491            )
492        })
493        .collect()
494}
495
496/// (user.name, user.email) pairs git knows here: the configured identity (global and the current
497/// repo's) and the authors of the current repo's recent history. Best effort: no git, no pairs.
498fn git_identities() -> Vec<(String, String)> {
499    let git = |args: &[&str]| {
500        std::process::Command::new("git")
501            .args(args)
502            .stdin(std::process::Stdio::null())
503            .stderr(std::process::Stdio::null())
504            .output()
505            .ok()
506            .filter(|o| o.status.success())
507            .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
508            .unwrap_or_default()
509    };
510    let mut out: Vec<(String, String)> =
511        git(&["log", "-n", "2000", "--format=%aN%x09%aE"]).lines().filter_map(|l| l.split_once('\t')).map(|(n, e)| (n.to_string(), e.to_string())).collect();
512    for scope in [&["config", "--global"][..], &["config"][..]] {
513        let get = |k: &str| git(&[scope, &[k]].concat()).trim().to_string();
514        out.push((get("user.name"), get("user.email")));
515    }
516    out.sort();
517    out.dedup();
518    out
519}
520
521/// Each harness's CLI (its version, as its [`harness::Probe`] says) and, once the CLI answered, its own
522/// checks (`Harness::checks`: they may ask the CLI, which a missing or hung one cannot answer).
523fn harness_checks<'a>(hs: impl Iterator<Item = &'a dyn Harness>, t: &Targets) -> Vec<(Level, String)> {
524    let mut checks = Vec::new();
525    for h in hs {
526        let harness::Probe { cli, tested } = h.probe();
527        match which(cli) {
528            None => checks.push((Level::Ok, format!("{cli}: not installed"))),
529            Some(p) => match version(&p) {
530                Some(v) => {
531                    checks.push((Level::Ok, format!("{cli}: {v}{tested}")));
532                    checks.extend(h.checks(&t.path(h)));
533                }
534                None => checks.push((Level::Warn, format!("{cli}: {} did not answer --version", p.display()))),
535            },
536        }
537    }
538    checks
539}
540
541fn doctor(t: &Targets) -> i32 {
542    let mut checks = Vec::new();
543    let env_bin = std::env::var_os("BORG_BIN").filter(|v| !v.is_empty()).map(PathBuf::from);
544    let on_path = which("borg");
545    match (&env_bin, &on_path) {
546        (Some(b), _) if !executable(b) => checks.push((Level::Fail, format!("BORG_BIN={} does not exist or is not executable", b.display()))),
547        (Some(b), _) => checks.push((Level::Ok, format!("borg: BORG_BIN={}", b.display()))),
548        (None, Some(p)) => checks.push((Level::Ok, format!("borg: on PATH at {}", p.display()))),
549        (None, None) => {
550            let adapters: Vec<&str> = harness::visible().filter(|h| matches!(h.wiring(), Wiring::AdapterFile { .. })).map(|h| h.name()).collect();
551            checks.push((Level::Warn, format!("borg: not on PATH and BORG_BIN unset ({} adapters need one)", adapters.join(" and "))));
552        }
553    }
554    let borg_found = env_bin.as_deref().is_some_and(executable) || on_path.is_some();
555    checks.extend(harness_checks(harness::visible(), t));
556    checks.extend(wiring_checks(t, borg_found));
557    let cfg = collective::load();
558    checks.extend(collective_checks(&cfg, &learn::home()));
559    if let Ok(cwd) = std::env::current_dir() {
560        checks.extend(orphans::hive_worktree_checks(&cwd));
561    }
562    if let Ok(c) = &cfg {
563        let routes = collectives(c.as_ref(), &learn::home());
564        checks.extend(crate::vectors::doctor::checks(&routes));
565        checks.extend(crate::presence::mesh_checks(&routes));
566        let emails: BTreeSet<String> = routes
567            .iter()
568            .filter_map(|r| match r {
569                Route::Collective { home, .. } => Some(store_emails(home)),
570                Route::Off => None,
571            })
572            .flatten()
573            .collect();
574        let aliases = c.as_ref().map(collective::Config::aliases).unwrap_or_default();
575        checks.extend(alias_hints(&emails, &git_identities(), &aliases).into_iter().map(|h| (Level::Warn, h)));
576    }
577    let spec = std::env::var("BORG_PREDICT_MODEL").ok();
578    checks.push(match crate::runner::availability(spec.as_deref(), &crate::runner::on_path) {
579        Ok(m) => (Level::Ok, m),
580        Err(m) => (Level::Warn, m),
581    });
582    for (l, msg) in &checks {
583        let tag = match l {
584            Level::Ok => "ok  ",
585            Level::Warn => "WARN",
586            Level::Fail => "FAIL",
587        };
588        println!("{tag} {msg}");
589    }
590    i32::from(checks.iter().any(|(l, _)| *l == Level::Fail))
591}
592
593// ---------------------------------------------------------------- CLI
594
595fn usage_line() -> String {
596    format!("usage: borg install|uninstall <{}|all> [--apply] [--home DIR] | borg status [--home DIR] | borg doctor [--home DIR]", harness::names("|"))
597}
598
599/// `borg install|uninstall|status|doctor`; returns the exit code.
600pub fn main(cmd: &str, args: &[&str]) -> i32 {
601    let mut apply_flag = false;
602    let mut home: Option<PathBuf> = None;
603    let mut which_h: Option<&str> = None;
604    let mut it = args.iter();
605    while let Some(a) = it.next() {
606        match *a {
607            "--apply" => apply_flag = true,
608            "--home" => match it.next() {
609                Some(d) => home = Some(PathBuf::from(d)),
610                None => return usage(),
611            },
612            h if which_h.is_none() && !h.starts_with('-') => which_h = Some(h),
613            _ => return usage(),
614        }
615    }
616    let targets = match &home {
617        Some(h) => {
618            isolate(cmd, h);
619            Targets::under(h)
620        }
621        None => Targets::from_env(),
622    };
623    match cmd {
624        "status" if which_h.is_none() && !apply_flag => {
625            print_status(&targets);
626            0
627        }
628        "doctor" if which_h.is_none() && !apply_flag => doctor(&targets),
629        "install" | "uninstall" => {
630            let Some(hs) = which_h.and_then(parse) else { return usage() };
631            let action = if cmd == "install" { Action::Install } else { Action::Uninstall };
632            run(action, &hs, &targets, &bin(), apply_flag)
633        }
634        _ => usage(),
635    }
636}
637
638/// The borg the hooks run: `$BORG_BIN`, else this binary.
639pub(crate) fn bin() -> PathBuf {
640    match std::env::var_os("BORG_BIN").filter(|v| !v.is_empty()) {
641        Some(b) => PathBuf::from(b),
642        None => std::env::current_exe().and_then(std::fs::canonicalize).unwrap_or_else(|_| PathBuf::from("borg")),
643    }
644}
645
646/// Variables `--home` removes, so every path borg resolves falls under the given HOME: the store
647/// (`$BORG_HOME`, default `HOME/.local/share/borg`), the collectives config (`$BORG_CONFIG`, default
648/// `HOME/.config/borg/collectives.json`) and the vector model (`$BORG_VECTOR_MODEL`, default under
649/// `HOME/.local/share/borg/models`). For status and doctor `$BORG_BIN` goes too (a real binary to
650/// check); install (and `borg setup`, which installs) keeps it, since there it only names the binary to
651/// wire, not a place to write.
652/// Harness config-dir variables need no removing: `Targets::under` never reads them.
653pub fn home_overrides(cmd: &str) -> &'static [&'static str] {
654    match cmd {
655        "install" | "uninstall" | "setup" => &["BORG_HOME", "BORG_CONFIG", "BORG_VECTOR_MODEL"],
656        _ => &["BORG_HOME", "BORG_CONFIG", "BORG_VECTOR_MODEL", "BORG_BIN"],
657    }
658}
659
660pub(crate) fn isolate(cmd: &str, home: &Path) {
661    // SAFETY: single-threaded CLI start, before anything reads the environment.
662    unsafe {
663        std::env::set_var("HOME", home);
664        for k in home_overrides(cmd) {
665            std::env::remove_var(k);
666        }
667    }
668}
669
670fn usage() -> i32 {
671    eprintln!("{}", usage_line());
672    2
673}
674
675fn run(action: Action, hs: &[&dyn Harness], t: &Targets, bin: &Path, apply_flag: bool) -> i32 {
676    let stamp = format!("{}Z", utc(learn::now_ms()));
677    let mut code = 0;
678    for &h in hs {
679        let changes = match plan(action, h, t, bin) {
680            Err(e) => {
681                eprintln!("{}: {e}", h.name());
682                code = 1;
683                continue;
684            }
685            Ok((changes, notes)) => {
686                for n in notes {
687                    println!("{}: {n}", h.name());
688                }
689                changes
690            }
691        };
692        if changes.is_empty() {
693            println!("{}: nothing to change ({})", h.name(), t.path(h).display());
694        } else if apply_flag {
695            code = code.max(write(h, &changes, &stamp));
696            t.skill_dir(h).inspect(|d| skill::tidy(d));
697        } else {
698            for c in &changes {
699                print!("{}", diff(&c.path, c.before.as_deref(), c.after.as_deref()));
700            }
701        }
702    }
703    footer(action, apply_flag, code);
704    code
705}
706
707/// After a clean run: the dry-run note, or after an install what is left that install never does.
708fn footer(action: Action, apply_flag: bool, code: i32) {
709    if code != 0 {
710        return;
711    }
712    if !apply_flag {
713        println!("(dry run: nothing written; add --apply to write, with a backup of every changed file)");
714    } else if action == Action::Install
715        && let Some(hint) = crate::vectors::doctor::hint()
716    {
717        println!("{hint}");
718    }
719}
720
721/// Writes `h`'s changes in order, each reported on its own line; 1 if any failed.
722pub(crate) fn write(h: &dyn Harness, changes: &[Change], stamp: &str) -> i32 {
723    let mut code = 0;
724    for c in changes {
725        match apply(c, stamp) {
726            Ok(backup) => {
727                let b = backup.map(|b| format!(" (backup {})", b.display())).unwrap_or_default();
728                let what = if c.after.is_some() { "wrote" } else { "removed" };
729                println!("{}: {what} {}{b}", h.name(), c.path.display());
730            }
731            Err(e) => {
732                eprintln!("{}: {}: {e}", h.name(), c.path.display());
733                code = 1;
734            }
735        }
736    }
737    code
738}
739
740#[cfg(test)]
741mod tests {
742    use super::*;
743    use crate::harness::{claude, omp, opencode};
744    use serde_json::json;
745
746    const CLAUDE: &dyn Harness = &claude::Claude;
747    const OMP: &dyn Harness = &omp::Omp;
748    const OPENCODE: &dyn Harness = &opencode::Opencode;
749
750    fn claude_hooks() -> Hooks {
751        Hooks::of(CLAUDE).unwrap()
752    }
753
754    fn tmp(name: &str) -> PathBuf {
755        let d = std::env::temp_dir().join(format!("borg-install-{name}-{}", std::process::id()));
756        let _ = std::fs::remove_dir_all(&d);
757        std::fs::create_dir_all(&d).unwrap();
758        d
759    }
760
761    /// A settings.json as Claude Code writes it, with someone else's hooks and settings.
762    const EXISTING: &str = r#"{
763  "model": "opus",
764  "permissions": {
765    "allow": [
766      "Bash(git status)"
767    ]
768  },
769  "hooks": {
770    "Stop": [
771      {
772        "hooks": [
773          {
774            "type": "command",
775            "command": "notify-send done"
776          }
777        ]
778      }
779    ],
780    "PreToolUse": [
781      {
782        "matcher": "Bash",
783        "hooks": [
784          {
785            "type": "command",
786            "command": "/usr/local/bin/guard"
787          }
788        ]
789      }
790    ]
791  },
792  "zz_last": true
793}"#;
794
795    fn all_files(home: &Path) -> Vec<(PathBuf, Vec<u8>)> {
796        fn walk(d: &Path, out: &mut Vec<(PathBuf, Vec<u8>)>) {
797            for e in std::fs::read_dir(d).into_iter().flatten().flatten() {
798                let p = e.path();
799                if p.is_dir() { walk(&p, out) } else { out.push((p.clone(), std::fs::read(&p).unwrap())) }
800            }
801        }
802        let mut out = Vec::new();
803        walk(home, &mut out);
804        out.sort();
805        out
806    }
807
808    /// Applies every visible harness's plan as `run` does; the number of files changed.
809    fn install_all(t: &Targets, bin: &Path, action: Action, stamp: &str) -> usize {
810        let mut n = 0;
811        for h in harness::visible() {
812            for c in plan(action, h, t, bin).unwrap().0 {
813                apply(&c, stamp).unwrap();
814                n += 1;
815            }
816            t.skill_dir(h).inspect(|d| skill::tidy(d));
817        }
818        n
819    }
820
821    /// The files a full install writes: one config or adapter per harness, and the skill's files
822    /// wherever the harness loads skills.
823    fn files_per_install(t: &Targets) -> usize {
824        harness::visible().map(|h| 1 + t.skill_dir(h).map_or(0, |_| skill::FILES.len())).sum()
825    }
826
827    #[test]
828    fn install_preserves_existing_hooks_and_settings() {
829        let home = tmp("preserve");
830        let t = Targets::under(&home);
831        std::fs::create_dir_all(t.path(CLAUDE).parent().unwrap()).unwrap();
832        std::fs::write(t.path(CLAUDE), EXISTING).unwrap();
833        let bin = Path::new("/opt/borg dir/borg");
834        assert_eq!(install_all(&t, bin, Action::Install, "s1"), files_per_install(&t), "one config per harness, and the skill");
835
836        let v: Value = serde_json::from_str(&std::fs::read_to_string(t.path(CLAUDE)).unwrap()).unwrap();
837        assert_eq!(v["model"], "opus");
838        assert_eq!(v["zz_last"], true);
839        assert_eq!(v["permissions"]["allow"][0], "Bash(git status)");
840        assert_eq!(v["hooks"]["PreToolUse"][0]["hooks"][0]["command"], "/usr/local/bin/guard");
841        assert_eq!(v["hooks"]["Stop"][0]["hooks"][0]["command"], "notify-send done", "their Stop hook stays first");
842        assert_eq!(v["hooks"]["Stop"][1]["hooks"][0]["command"], "'/opt/borg dir/borg' hook claude stop");
843        assert_eq!(v["hooks"]["Stop"][1]["hooks"][0]["timeout"], harness::STOP_TIMEOUT_S, "the stop hook's budget is explicit");
844        assert!(v["hooks"]["PostToolUse"][0]["hooks"][0].get("timeout").is_none());
845        // An install from before the timeout is brought up to it.
846        let old = r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"/b/borg hook claude stop"}]}]}}"#;
847        let up: Value = serde_json::from_str(&claude_hooks().install(Some(old), Path::new("/b/borg")).unwrap().unwrap()).unwrap();
848        assert_eq!(up["hooks"]["Stop"].as_array().unwrap().len(), 1);
849        assert_eq!(up["hooks"]["Stop"][0]["hooks"][0]["timeout"], harness::STOP_TIMEOUT_S);
850        let keys: Vec<&String> = v.as_object().unwrap().keys().collect();
851        assert_eq!(keys, ["model", "permissions", "hooks", "zz_last"], "key order kept");
852        let wired = claude_hooks().wired(Some(&std::fs::read_to_string(t.path(CLAUDE)).unwrap()));
853        assert_eq!(wired.len(), claude::EVENTS.len());
854        assert!(wired.iter().all(|(_, b)| b == bin), "quoted path parsed back");
855        assert_eq!(std::fs::read_to_string(t.path(OMP)).unwrap(), omp::ADAPTER);
856        assert_eq!(std::fs::read_to_string(t.path(OPENCODE)).unwrap(), opencode::ADAPTER);
857        let backup = t.path(CLAUDE).with_file_name("settings.json.borg-backup-s1");
858        assert_eq!(std::fs::read_to_string(backup).unwrap(), EXISTING, "backup of the original");
859    }
860
861    #[test]
862    fn install_is_idempotent_and_replaces_a_stale_binary() {
863        let home = tmp("idem");
864        let t = Targets::under(&home);
865        let bin = Path::new("/usr/bin/borg");
866        assert_eq!(install_all(&t, bin, Action::Install, "a"), files_per_install(&t), "one config per harness, and the skill");
867        let snapshot = all_files(&home);
868        assert_eq!(install_all(&t, bin, Action::Install, "b"), 0, "second install changes nothing");
869        assert_eq!(all_files(&home), snapshot, "and writes nothing, not even a backup");
870
871        // A moved binary: each event points at the new one, never twice.
872        let text = claude_hooks().install(read(&t.path(CLAUDE)).unwrap().as_deref(), Path::new("/new/borg")).unwrap().unwrap();
873        let wired = claude_hooks().wired(Some(&text));
874        assert_eq!(wired.len(), claude::EVENTS.len());
875        assert!(wired.iter().all(|(_, b)| b == Path::new("/new/borg")));
876    }
877
878    #[test]
879    fn uninstall_restores_the_original_exactly() {
880        for (name, original) in [("existing", Some(EXISTING)), ("existing-nl", Some(&*format!("{EXISTING}\n"))), ("absent", None)] {
881            let home = tmp(&format!("restore-{name}"));
882            let t = Targets::under(&home);
883            if let Some(o) = original {
884                std::fs::create_dir_all(t.path(CLAUDE).parent().unwrap()).unwrap();
885                std::fs::write(t.path(CLAUDE), o).unwrap();
886            }
887            install_all(&t, Path::new("/usr/bin/borg"), Action::Install, "i");
888            assert_eq!(install_all(&t, Path::new("/elsewhere/borg"), Action::Uninstall, "u"), files_per_install(&t), "everything install wrote");
889            assert_eq!(read(&t.path(CLAUDE)).unwrap().as_deref(), original, "{name}: byte for byte");
890            assert!(!t.path(OMP).exists() && !t.path(OPENCODE).exists() && !t.path(&crate::harness::codex::Codex).exists());
891            for h in harness::visible() {
892                assert!(t.skill_dir(h).is_none_or(|d| !d.exists()), "{name}: {}'s skill directory removed", h.name());
893            }
894            assert_eq!(install_all(&t, Path::new("/usr/bin/borg"), Action::Uninstall, "u2"), 0, "nothing left to remove");
895        }
896    }
897
898    #[test]
899    fn uninstall_leaves_foreign_files_alone() {
900        let home = tmp("foreign");
901        let t = Targets::under(&home);
902        std::fs::create_dir_all(t.path(OMP).parent().unwrap()).unwrap();
903        std::fs::write(t.path(OMP), "// my own borg.ts").unwrap();
904        let (change, notes) = plan(Action::Uninstall, OMP, &t, Path::new("/b/borg")).unwrap();
905        assert!(change.is_empty());
906        assert_eq!(notes.len(), 1);
907        // The engineer's own file in borg's skill directory: left alone, and so is the directory.
908        let skill = t.skill_dir(CLAUDE).unwrap();
909        std::fs::create_dir_all(&skill).unwrap();
910        std::fs::write(skill.join("SKILL.md"), "my own skill").unwrap();
911        std::fs::write(skill.join("notes.md"), "mine").unwrap();
912        install_all(&t, Path::new("/b/borg"), Action::Install, "i");
913        assert_eq!(install_all(&t, Path::new("/b/borg"), Action::Uninstall, "u"), files_per_install(&t));
914        assert_eq!(std::fs::read_to_string(skill.join("notes.md")).unwrap(), "mine");
915        assert_eq!(std::fs::read_to_string(skill.join("SKILL.md.borg-backup-i")).unwrap(), "my own skill", "replaced with a backup");
916        // A hook that merely mentions borg but is not borg's own command stays.
917        let s = r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"/x/notborg hook claude stop"}]}]}}"#;
918        assert_eq!(claude_hooks().uninstall(Some(s)).unwrap(), None);
919    }
920
921    #[test]
922    fn dry_run_writes_nothing() {
923        let home = tmp("dry");
924        let t = Targets::under(&home);
925        std::fs::create_dir_all(t.path(CLAUDE).parent().unwrap()).unwrap();
926        std::fs::write(t.path(CLAUDE), EXISTING).unwrap();
927        let before = all_files(&home);
928        assert_eq!(run(Action::Install, &harness::visible().collect::<Vec<_>>(), &t, Path::new("/usr/bin/borg"), false), 0);
929        assert_eq!(all_files(&home), before);
930        let (c, _) = plan(Action::Install, CLAUDE, &t, Path::new("/usr/bin/borg")).unwrap();
931        let c = &c[0];
932        let d = diff(&c.path, c.before.as_deref(), c.after.as_deref());
933        assert!(d.contains("+            \"command\": \"/usr/bin/borg hook claude stop\""), "{d}");
934        assert!(!d.lines().any(|l| l.starts_with('-') && !l.starts_with("---")), "pure addition:\n{d}");
935    }
936
937    #[test]
938    fn invalid_settings_are_never_overwritten() {
939        assert!(claude_hooks().install(Some("{ not json"), Path::new("/b/borg")).is_err());
940        assert!(claude_hooks().install(Some(r#"{"hooks": []}"#), Path::new("/b/borg")).is_err());
941    }
942
943    #[cfg(unix)]
944    #[test]
945    fn adapter_symlink_is_replaced_not_written_through() {
946        let home = tmp("link");
947        let t = Targets::under(&home);
948        let src = home.join("checkout-borg.ts");
949        std::fs::write(&src, "// older adapter in a checkout").unwrap();
950        std::fs::create_dir_all(t.path(OMP).parent().unwrap()).unwrap();
951        std::os::unix::fs::symlink(&src, t.path(OMP)).unwrap();
952        let (c, _) = plan(Action::Install, OMP, &t, Path::new("/b/borg")).unwrap();
953        apply(&c[0], "x").unwrap();
954        assert_eq!(std::fs::read_to_string(&src).unwrap(), "// older adapter in a checkout");
955        assert_eq!(std::fs::read_to_string(t.path(OMP)).unwrap(), omp::ADAPTER);
956    }
957
958    #[test]
959    fn status_counts_a_store() {
960        let home = tmp("stats");
961        let w = |f: &str, s: &str| std::fs::write(home.join(f), s).unwrap();
962        w("episodes.jsonl", "{\"ms\":5}\n{\"ms\":9}\n");
963        w("lessons.jsonl", "");
964        w(
965            "outcomes.jsonl",
966            "{\"kind\":\"asked\",\"session\":\"s\",\"lessons\":[\"L1\"],\"ms\":3,\"repo\":\"r\"}\n{\"kind\":\"asked\",\"session\":\"s\",\"lessons\":[\"L2\"],\"ms\":7,\"repo\":\"r\"}\n",
967        );
968        let s = stats(&home);
969        assert_eq!((s.lessons, s.episodes, s.outcomes, s.last_capture_ms), (0, 2, 2, Some(9)));
970        assert_eq!(s.last_asked, Some((7, vec!["L2".to_string()])));
971        assert_eq!(stats(&home.join("absent")), Stats::default());
972        let cfg: collective::Config =
973            serde_json::from_str(r#"{"collectives":[{"name":"corp","paths":["/w"]},{"name":"mine","paths":["/p"],"share":"local"}]}"#).unwrap();
974        let rs = collectives(Some(&cfg), Path::new("/b"));
975        assert_eq!(rs.iter().map(collective::may_sync).collect::<Vec<_>>(), [true, false]);
976        assert_eq!(rs[1], Route::Collective { name: "mine".into(), home: "/b/collectives/mine".into(), share: Share::Local });
977        assert_eq!(utc(0), "19700101T000000");
978        assert_eq!(utc(1_791_590_400_000), "20261010T000000");
979    }
980
981    #[test]
982    fn doctor_hints_at_emails_sharing_a_git_name_until_they_are_one_engineer() {
983        let home = tmp("aliases");
984        let line = |v: Value| format!("{v}\n");
985        std::fs::write(
986            home.join("lessons.jsonl"),
987            line(json!({"id": "a", "origin_ms": 1, "repo": "r", "question": "q", "situations": [], "consequence": "", "support": 1,
988                "episodes": [], "history": [], "version": 2, "engineers": ["Dana.Example@corp.example", "ann@x"], "joined": {"ann@x": 5}})),
989        )
990        .unwrap();
991        std::fs::write(home.join("episodes.jsonl"), line(json!({"ms": 1, "engineer": "da@home.example"})) + &line(json!({"ms": 2, "engineer": ""}))).unwrap();
992        let emails = store_emails(&home);
993        assert_eq!(emails.iter().map(String::as_str).collect::<Vec<_>>(), ["Dana.Example@corp.example", "ann@x", "da@home.example"]);
994        let ids = |v: &[(&str, &str)]| v.iter().map(|(n, e)| (n.to_string(), e.to_string())).collect::<Vec<_>>();
995        let known =
996            ids(&[("Dana Example", "dana.example@corp.example"), ("Dana Example", "da@home.example"), ("Ann", "ann@x"), ("Dana Example", "elsewhere@x")]);
997        let hints = alias_hints(&emails, &known, &collective::Aliases::default());
998        assert_eq!(hints.len(), 1, "{hints:?}");
999        assert!(
1000            hints[0].contains("\"Dana Example\"") && hints[0].contains("Dana.Example@corp.example") && hints[0].contains("da@home.example"),
1001            "{}",
1002            hints[0]
1003        );
1004        assert!(!hints[0].contains("elsewhere@x"), "only emails the stores have");
1005        let cfg: collective::Config =
1006            serde_json::from_str(r#"{"engineers": [{"name": "dana", "emails": ["da@home.example", "Dana.Example@corp.example"]}]}"#).unwrap();
1007        assert!(alias_hints(&emails, &known, &cfg.aliases()).is_empty(), "already one engineer");
1008        assert!(alias_hints(&emails, &ids(&[("Ann", "ann@x"), ("Dana Example", "da@home.example")]), &collective::Aliases::default()).is_empty());
1009    }
1010
1011    #[test]
1012    fn doctor_flags_a_missing_binary_and_an_invalid_config() {
1013        let home = tmp("doctor");
1014        let t = Targets::under(&home);
1015        plan(Action::Install, CLAUDE, &t, Path::new("/nonexistent/borg")).unwrap().0.iter().for_each(|c| drop(apply(c, "d").unwrap()));
1016        let checks = wiring_checks(&t, true);
1017        assert!(checks.iter().any(|(l, m)| *l == Level::Fail && m.contains("/nonexistent/borg")), "{checks:?}");
1018        let bad = collective_checks(&Err("x.json: expected value".into()), &home);
1019        assert_eq!(bad.len(), 1);
1020        assert!(bad[0].0 == Level::Fail && bad[0].1.contains("EVERY repo routes OFF"));
1021        assert!(collective_checks(&Ok(None), &home.join("store")).iter().all(|(l, _)| *l == Level::Ok));
1022    }
1023
1024    #[test]
1025    fn doctor_names_a_leftover_hive_and_its_removal_but_leaves_it() {
1026        let base = tmp("hive-orphan");
1027        let store = collectives(None, &base)
1028            .into_iter()
1029            .find_map(|r| match r {
1030                Route::Collective { home, .. } => Some(home),
1031                Route::Off => None,
1032            })
1033            .unwrap();
1034        std::fs::create_dir_all(store.join("hive/g1")).unwrap();
1035        let warn: Vec<String> = collective_checks(&Ok(None), &base).into_iter().filter(|(l, _)| *l == Level::Warn).map(|(_, m)| m).collect();
1036        assert!(
1037            matches!(warn.as_slice(), [m] if m.contains("removed feature") && m.contains(&format!("rm -r '{}'", store.join("hive").display()))),
1038            "{warn:?}"
1039        );
1040        assert!(store.join("hive/g1").is_dir(), "never deleted by doctor");
1041    }
1042
1043    #[cfg(unix)]
1044    fn chmod(p: &Path, mode: u32) {
1045        use std::os::unix::fs::PermissionsExt;
1046        std::fs::set_permissions(p, std::fs::Permissions::from_mode(mode)).unwrap();
1047    }
1048
1049    #[test]
1050    fn full_claude_install_reports_wired_not_partial() {
1051        let home = tmp("wired-status");
1052        let t = Targets::under(&home);
1053        assert_eq!(run(Action::Install, &[CLAUDE], &t, Path::new("/b/borg"), true), 0);
1054        assert!(wiring(CLAUDE, &t).starts_with("wired: "), "{}", wiring(CLAUDE, &t));
1055    }
1056
1057    #[cfg(unix)]
1058    #[test]
1059    fn unreadable_files_are_errors_not_absent() {
1060        let home = tmp("unreadable");
1061        let t = Targets::under(&home);
1062        std::fs::create_dir_all(t.path(CLAUDE).parent().unwrap()).unwrap();
1063        let precious = r#"{"model":"precious"}"#;
1064        std::fs::write(t.path(CLAUDE), precious).unwrap();
1065        chmod(&t.path(CLAUDE), 0o000);
1066        if std::fs::read(t.path(CLAUDE)).is_ok() {
1067            chmod(&t.path(CLAUDE), 0o600);
1068            return; // running as root: permissions do not apply
1069        }
1070        let before = std::fs::read_dir(t.path(CLAUDE).parent().unwrap()).unwrap().count();
1071        for action in [Action::Install, Action::Uninstall] {
1072            assert!(plan(action, CLAUDE, &t, Path::new("/b/borg")).is_err());
1073        }
1074        assert_eq!(run(Action::Install, &[CLAUDE], &t, Path::new("/b/borg"), true), 1);
1075        assert!(wiring(CLAUDE, &t).starts_with("UNREADABLE"));
1076        assert!(wiring_checks(&t, true).iter().any(|(l, m)| *l == Level::Fail && m.contains("cannot read")));
1077        chmod(&t.path(CLAUDE), 0o600);
1078        assert_eq!(std::fs::read_to_string(t.path(CLAUDE)).unwrap(), precious, "untouched");
1079        assert_eq!(std::fs::read_dir(t.path(CLAUDE).parent().unwrap()).unwrap().count(), before, "no new files");
1080
1081        // Not UTF-8: an adapter file someone else wrote, likewise never replaced.
1082        std::fs::create_dir_all(t.path(OMP).parent().unwrap()).unwrap();
1083        std::fs::write(t.path(OMP), [0xff, 0xfe, 0x00]).unwrap();
1084        assert!(plan(Action::Install, OMP, &t, Path::new("/b/borg")).is_err());
1085        assert_eq!(std::fs::read(t.path(OMP)).unwrap(), [0xff, 0xfe, 0x00]);
1086    }
1087
1088    #[test]
1089    fn a_binary_not_named_borg_is_refused() {
1090        let home = tmp("borg-dev");
1091        let t = Targets::under(&home);
1092        for bin in ["/x/borg-dev", "/x/borg-ai", "/x/notborg"] {
1093            let e = plan(Action::Install, CLAUDE, &t, Path::new(bin)).unwrap_err();
1094            assert!(e.contains("BORG_BIN"), "{e}");
1095        }
1096        assert!(!t.path(CLAUDE).exists());
1097        // Named borg: installed once, however often it runs.
1098        for stamp in ["1", "2", "3"] {
1099            install_all(&t, Path::new("/x/dev/borg"), Action::Install, stamp);
1100        }
1101        let text = std::fs::read_to_string(t.path(CLAUDE)).unwrap();
1102        assert_eq!(text.matches("hook claude stop").count(), 1);
1103        assert_eq!(claude_hooks().wired(Some(&text)).len(), claude::EVENTS.len());
1104    }
1105
1106    #[cfg(unix)]
1107    #[test]
1108    fn permissions_are_kept_and_new_files_are_private() {
1109        use std::os::unix::fs::PermissionsExt;
1110        let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
1111        let home = tmp("perms");
1112        let t = Targets::under(&home);
1113        std::fs::create_dir_all(t.path(CLAUDE).parent().unwrap()).unwrap();
1114        std::fs::write(t.path(CLAUDE), r#"{"env":{"SECRET":"x"}}"#).unwrap();
1115        chmod(&t.path(CLAUDE), 0o600);
1116        let (c, _) = plan(Action::Install, CLAUDE, &t, Path::new("/usr/bin/borg")).unwrap();
1117        let backup = apply(&c[0], "p").unwrap().unwrap();
1118        assert_eq!(mode(&t.path(CLAUDE)), 0o600, "settings stay 0600");
1119        assert_eq!(mode(&backup), 0o600, "backup is 0600");
1120
1121        chmod(&t.path(CLAUDE), 0o640);
1122        let (c, _) = plan(Action::Uninstall, CLAUDE, &t, Path::new("/usr/bin/borg")).unwrap();
1123        apply(&c[0], "q").unwrap();
1124        assert_eq!(mode(&t.path(CLAUDE)), 0o640, "whatever the original had");
1125
1126        let fresh = tmp("perms-new");
1127        let t = Targets::under(&fresh);
1128        let (c, _) = plan(Action::Install, CLAUDE, &t, Path::new("/usr/bin/borg")).unwrap();
1129        apply(&c[0], "n").unwrap();
1130        assert_eq!(mode(&t.path(CLAUDE)), 0o600, "a new settings.json is private");
1131    }
1132
1133    #[test]
1134    fn a_backup_is_never_overwritten() {
1135        let home = tmp("backups");
1136        let t = Targets::under(&home);
1137        std::fs::create_dir_all(t.path(CLAUDE).parent().unwrap()).unwrap();
1138        let orig = r#"{"model":"orig"}"#;
1139        std::fs::write(t.path(CLAUDE), orig).unwrap();
1140        // Install then uninstall within one stamp (the same second).
1141        let (c, _) = plan(Action::Install, CLAUDE, &t, Path::new("/usr/bin/borg")).unwrap();
1142        let b1 = apply(&c[0], "same").unwrap().unwrap();
1143        let (c, _) = plan(Action::Uninstall, CLAUDE, &t, Path::new("/usr/bin/borg")).unwrap();
1144        let b2 = apply(&c[0], "same").unwrap().unwrap();
1145        assert_ne!(b1, b2);
1146        assert_eq!(std::fs::read_to_string(&b1).unwrap(), orig, "the original survives");
1147        assert!(std::fs::read_to_string(&b2).unwrap().contains("hook claude stop"));
1148        assert!(b2.to_string_lossy().ends_with("borg-backup-same-1"));
1149    }
1150
1151    #[test]
1152    fn home_overrides_cover_store_and_config() {
1153        for cmd in ["install", "uninstall", "setup", "status", "doctor"] {
1154            let v = home_overrides(cmd);
1155            assert!(v.contains(&"BORG_HOME") && v.contains(&"BORG_CONFIG") && v.contains(&"BORG_VECTOR_MODEL"), "{cmd}");
1156        }
1157        assert!(home_overrides("doctor").contains(&"BORG_BIN"));
1158        assert!(!home_overrides("install").contains(&"BORG_BIN"), "install still wires $BORG_BIN");
1159    }
1160
1161    /// A harness with a step of its own in the harness (as Codex's hook trust will be).
1162    /// A harness with its own install notes and doctor check; its CLI is `.0`.
1163    struct Noted(&'static str);
1164
1165    impl Harness for Noted {
1166        fn name(&self) -> &'static str {
1167            "noted"
1168        }
1169        fn caps(&self) -> harness::Caps {
1170            CLAUDE.caps()
1171        }
1172        fn wiring(&self) -> Wiring {
1173            CLAUDE.wiring()
1174        }
1175        fn target(&self, home: &Path, _var: &dyn Fn(&str) -> Option<PathBuf>) -> PathBuf {
1176            home.join(".noted/hooks.json")
1177        }
1178        fn probe(&self) -> harness::Probe {
1179            harness::Probe { cli: self.0, tested: "" }
1180        }
1181        fn checks(&self, target: &Path) -> Vec<(Level, String)> {
1182            vec![(Level::Warn, format!("noted: {} is not trusted", target.display()))]
1183        }
1184        fn install_notes(&self) -> Vec<String> {
1185            vec!["run /hooks in noted and trust borg".into()]
1186        }
1187    }
1188
1189    #[test]
1190    fn a_harness_adds_its_own_install_notes_and_doctor_checks() {
1191        let home = tmp("noted");
1192        let t = Targets::under(&home);
1193        let (change, notes) = plan(Action::Install, &Noted("git"), &t, Path::new("/b/borg")).unwrap();
1194        assert_eq!(change.len(), 1 + skill::FILES.len(), "the hook config and the skill");
1195        assert_eq!(notes, ["run /hooks in noted and trust borg"]);
1196        assert_eq!(plan(Action::Uninstall, &Noted("git"), &t, Path::new("/b/borg")).unwrap().1, Vec::<String>::new());
1197        let checks = harness_checks([&Noted("git") as &dyn Harness].into_iter(), &t);
1198        assert!(checks[0].0 == Level::Ok && checks[0].1.starts_with("git: git version"), "{checks:?}");
1199        assert_eq!(checks[1], (Level::Warn, format!("noted: {} is not trusted", home.join(".noted/hooks.json").display())));
1200        let missing = harness_checks([&Noted("borg-test-no-such-cli") as &dyn Harness].into_iter(), &t);
1201        assert_eq!(missing, [(Level::Ok, "borg-test-no-such-cli: not installed".into())], "no CLI to ask: its own checks wait");
1202    }
1203}