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