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