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