Skip to main content

borg/
completions.rs

1//! The command table of the borg CLI, and `borg completions <bash|zsh|fish>`: a shell completion script
2//! for borg, printed to stdout.
3//!
4//! One table (`GROUPS`, plus `DEBUG` for `borg debug`) feeds `borg help`, the dispatch gate in main.rs
5//! (`known`) and all three shells, so a new command needs one entry here; `HARNESSES` stands for the
6//! harnesses' names (harness/mod.rs `ALL`). Paths complete as files where a command takes one (`why`).
7
8/// In a subcommand list: every visible harness's name.
9pub const HARNESSES: &str = "<harnesses>";
10
11/// One command: its name, its help rows (the arguments after the name, what it does), and for the
12/// shells its subcommands, its flags and whether it takes a path.
13pub struct Command {
14    pub name: &'static str,
15    pub help: &'static [(&'static str, &'static str)],
16    pub subs: &'static [&'static str],
17    pub flags: &'static [&'static str],
18    pub path: bool,
19}
20
21const fn cmd(name: &'static str, help: &'static [(&'static str, &'static str)], subs: &'static [&'static str], flags: &'static [&'static str]) -> Command {
22    Command { name, help, subs, flags, path: false }
23}
24
25/// `borg help`: the commands grouped by what they are for.
26pub const GROUPS: &[(&str, &[Command])] = &[
27    (
28        "Setup",
29        &[
30            cmd("setup", &[("[--yes] [--no-vectors]", "guided setup: collectives, team, vectors, wiring")], &[], crate::install::setup::FLAGS),
31            cmd("install", &[("<HARNESS|all> [--apply]", "wire the hooks (a dry run without --apply)")], &[HARNESSES, "all"], &["--apply", "--home"]),
32            cmd("uninstall", &[("<HARNESS|all> [--apply]", "unwire them")], &[HARNESSES, "all"], &["--apply", "--home"]),
33            cmd("status", &[("", "each collective's lessons, outcomes and wiring")], &[], &["--home"]),
34            cmd("doctor", &[("", "what is broken: config, hooks, adapters, the model CLI")], &[], &["--home"]),
35            Command { path: true, ..cmd("collective", &[("[DIR]", "which collective a directory belongs to")], &[], &[]) },
36            cmd("vectors", &[("[--fetch|--rebuild] [--store LESSONS]", "the vector model and index")], &[], &["--fetch", "--rebuild", "--store"]),
37            cmd("completions", &[("<bash|zsh|fish>", "a shell completion script")], &["bash", "zsh", "fish"], &[]),
38            cmd("version", &[("", "borg's version (also --version, -V)")], &[], &[]),
39            cmd(
40                "update",
41                &[("[--check] [--quiet] [--json]", "install the latest release and refresh the wiring; --check: is there one (exit 10), who runs what")],
42                &[],
43                &["--check", "--quiet", "--json"],
44            ),
45        ],
46    ),
47    (
48        "Learning",
49        &[
50            cmd("learn", &[("", "turn waiting corrections into lessons now")], &[], &[]),
51            cmd(
52                "no",
53                &[("[--session ID] <reason>", "say no to a drone's work: shown lessons lose credit, the reason becomes a lesson")],
54                &[],
55                crate::veto::FLAGS,
56            ),
57            cmd(
58                "assimilate",
59                &[
60                    ("[--apply] [--since DATE] [--limit N]", "import corrections from past sessions"),
61                    ("--from-dir DIR [--plan FILE] [--apply]", "import lessons from team documents"),
62                ],
63                &[],
64                crate::assimilate::FLAGS,
65            ),
66            cmd("reach", &[("[--plan FILE] [--apply] [--jobs N]", "sort lessons into team, repo-only and personal")], &[], &["--plan", "--apply", "--jobs"]),
67            Command {
68                path: true,
69                ..cmd(
70                    "move",
71                    &[(
72                        "<lesson-id|repo-path> --to <collective> [--from <collective>] [--personal] [--apply]",
73                        "move a misplaced lesson, or a repo's waiting evidence, to another collective (a dry run without --apply)",
74                    )],
75                    &[],
76                    crate::moves::MOVE_FLAGS,
77                )
78            },
79            cmd(
80                "correct",
81                &[("--collective <name> [--session ID] [--repo NAME] <words>", "record this session's correction in another collective, learned there")],
82                &[],
83                crate::moves::CORRECT_FLAGS,
84            ),
85            cmd("facets", &[("[--apply] [--store FILE] [--jobs N]", "search facets for lessons")], &[], &["--apply", "--store", "--jobs"]),
86            cmd(
87                "memory",
88                &[
89                    ("export [--json] [--absorbed] [--since DATE] [--dir DIR]", "each lesson's evidence, for a store outside borg to take over"),
90                    ("absorb <id>... [--note TEXT]", "a lesson is held outside borg now: borg stops delivering it"),
91                    ("release <id>...", "an absorbed lesson: borg delivers it again"),
92                ],
93                crate::memory_export::SUBS,
94                crate::memory_export::FLAGS,
95            ),
96        ],
97    ),
98    (
99        "Decisions",
100        &[
101            cmd(
102                "queen",
103                &[("[show|ask|answer|skip|dismiss|dedupe]", "open decisions waiting for you")],
104                &["show", "ask", "answer", "skip", "dismiss", "dedupe"],
105                &["--json", "--repo", "--dir", "--collective", "--apply"],
106            ),
107            Command {
108                path: true,
109                ..cmd("why", &[("<path>[:<line>[-<line>]] | <commit>", "the reasoning behind code  [--full] [--json]")], &[], &["--full", "--json", "--dir"])
110            },
111            cmd("notes", &[("fetch [<commit>...]", "fetch the team's reasoning notes behind commits")], &["fetch"], &["--dir"]),
112            cmd(
113                "regress",
114                &[("[--replay A..B] [--explain] [--json]", "which earlier decisions later commits fixed (dry run)")],
115                &[],
116                crate::notes::regress_cli::FLAGS,
117            ),
118            cmd(
119                "review-fix",
120                &[("[--since DATE] [--json]", "bugs workflow reviews found and fix steps fixed, before any commit")],
121                &[],
122                crate::review_fix::FLAGS,
123            ),
124            cmd("trust", &[("[--dir DIR]", "trust per engineer and area")], &[], &["--dir"]),
125        ],
126    ),
127    (
128        "Watching",
129        &[
130            cmd("top", &[("[--once] [--json] [--dir DIR]", "the drones running across the team, live (q quits)")], &[], &["--once", "--json", "--dir"]),
131            cmd("web", &[("[--port PORT] [--dir DIR]", "a live page of knowledge and stats on 127.0.0.1")], &[], &["--port", "--dir"]),
132        ],
133    ),
134    (
135        "Team",
136        &[
137            cmd(
138                "mesh",
139                &[("<command>", "sync with team members (borg mesh --help)")],
140                &["id", "init", "invite", "invites", "join", "revoke", "members", "peer", "serve", "sync", "fetch"],
141                &["--collective", "--apply", "--paths", "--role", "--expires", "--uses", "--png", "--revoke"],
142            ),
143            cmd(
144                "tell",
145                &[(
146                    "<session|drone|local|collective|engineer> <text> [--re ID]",
147                    "a message to other sessions: local is this machine's, collective (or all) every member's",
148                )],
149                &["local", "collective", "all"],
150                crate::msg::FLAGS,
151            ),
152            cmd(
153                "ask",
154                &[("<session|drone|local|collective|engineer> <question> [--re ID]", "a message that asks for a reply")],
155                &["local", "collective", "all"],
156                crate::msg::FLAGS,
157            ),
158            cmd(
159                "inbox",
160                &[("[--all] [--json] [--show ID]", "this session's messages; from a terminal, every recent one; --show ID: one whole")],
161                &[],
162                crate::msg::INBOX_FLAGS,
163            ),
164            cmd(
165                "listen",
166                &[("[--off]", "wake this session when a message arrives while it is idle"), ("--wait|--stream|--queue", "the waiter (started by borg)")],
167                &[],
168                crate::listen::FLAGS,
169            ),
170            cmd(
171                "pause",
172                &[("<session|drone|local|collective> [note]", "refuse a session's tool calls until it is resumed")],
173                &["local", "collective", "all"],
174                crate::msg::STEER_FLAGS,
175            ),
176            cmd(
177                "resume",
178                &[("<session|drone|local|collective> [note]", "let a paused session's tool calls run again")],
179                &["local", "collective", "all"],
180                crate::msg::STEER_FLAGS,
181            ),
182        ],
183    ),
184];
185
186/// `borg debug <command>`: evaluation and debugging tools, out of the main help.
187pub const DEBUG: &[Command] = &[
188    Command { path: true, ..cmd("recall", &[("<lessons.jsonl> [before_ms]", "rank lessons for text on stdin")], &[], &[]) },
189    Command { path: true, ..cmd("resolve", &[("<lessons.jsonl>", "the word rule's changed/ignored for {asked, before, edits, final} on stdin")], &[], &[]) },
190    Command { path: true, ..cmd("prefilter", &[("<lessons.jsonl> [before_ms]", "the free gate's score for a turn on stdin")], &[], &[]) },
191    Command { path: true, ..cmd("memory", &[("<lessons.jsonl> [--session ID]", "each lesson's activation and usefulness")], &[], &["--session"]) },
192    Command {
193        path: true,
194        ..cmd("expert", &[("<repo> --at <commit> --q <text>", "at most 3 cited claims from an expert repo")], &[], &["--at", "--version", "--q"])
195    },
196    cmd("vectors", &[("--query [--store LESSONS]", "the vector shortlist for a context on stdin")], &[], &["--query", "--store"]),
197    cmd("ope", &[("[--dir DIR | --file FILE] [--json]", "off-policy estimates of the belief's hand-set weights")], &[], &["--dir", "--file", "--json"]),
198    cmd(
199        "select",
200        &[(
201            "[--replay] [--rebuild] [--dir DIR | --file FILE] [--json] [--eval RUNS_DIR --qrels FILE]",
202            "the lesson selection policy and its pre-registered checks",
203        )],
204        &[],
205        &["--replay", "--rebuild", "--dir", "--file", "--json", "--eval", "--qrels"],
206    ),
207];
208
209/// What hooks and drones run, never listed: dispatched, not shown.
210pub const INTERNAL: &[&str] = &["hook"];
211
212/// Every command of the main help, in its order.
213pub fn commands() -> impl Iterator<Item = &'static Command> {
214    GROUPS.iter().flat_map(|(_, cmds)| cmds.iter())
215}
216
217/// Whether `name` is a top-level borg command (dispatched by main.rs): listed, `debug`, `help`, the
218/// version flags or internal.
219pub fn known(name: &str) -> bool {
220    commands().any(|c| c.name == name) || INTERNAL.contains(&name) || matches!(name, "debug" | "help" | "-h" | "--help" | "-V" | "--version")
221}
222
223/// The completions' commands: the main help's, then `debug` with the debug commands as subcommands and
224/// all their flags.
225fn completed() -> Vec<(&'static str, Vec<&'static str>, Vec<&'static str>, bool)> {
226    let mut out: Vec<_> = commands().map(|c| (c.name, subs_of(c.subs), c.flags.to_vec(), c.path)).collect();
227    let mut flags: Vec<&str> = DEBUG.iter().flat_map(|c| c.flags.iter().copied()).collect();
228    flags.sort_unstable();
229    flags.dedup();
230    out.push(("debug", DEBUG.iter().map(|c| c.name).chain(["help"]).collect(), flags, true));
231    out
232}
233
234/// The debug commands that take subcommands of their own: (name, its subcommands and flags). Completed
235/// by the third word, so such a command offers its own subcommands rather than the debug commands again.
236fn nested() -> Vec<(&'static str, String)> {
237    DEBUG.iter().filter(|c| !c.subs.is_empty()).map(|c| (c.name, [subs_of(c.subs).as_slice(), c.flags].concat().join(" "))).collect()
238}
239
240const USAGE: &str = "usage: borg completions <bash|zsh|fish>
241  bash: borg completions bash > ~/.local/share/bash-completion/completions/borg
242  zsh:  borg completions zsh > \"${fpath[1]}/_borg\"   (then restart the shell)
243  fish: borg completions fish > ~/.config/fish/completions/borg.fish";
244
245pub fn main(args: &[&str]) -> i32 {
246    match args.first().copied() {
247        Some("bash") => print!("{}", bash()),
248        Some("zsh") => print!("{}", zsh()),
249        Some("fish") => print!("{}", fish()),
250        _ => {
251            eprintln!("{USAGE}");
252            return 2;
253        }
254    }
255    0
256}
257
258/// A command's subcommands, `HARNESSES` spelled out.
259fn subs_of(subs: &[&'static str]) -> Vec<&'static str> {
260    subs.iter().flat_map(|s| if *s == HARNESSES { crate::harness::visible().map(|h| h.name()).collect() } else { vec![*s] }).collect()
261}
262
263/// The shell's `case` lines: `line(command, its subcommands and flags, takes a path)` for each command.
264fn cases(line: impl Fn(&str, &str, bool) -> String) -> String {
265    completed().iter().map(|(cmd, subs, flags, path)| line(cmd, &[subs.as_slice(), flags].concat().join(" "), *path)).collect()
266}
267
268fn names() -> String {
269    completed().iter().map(|c| c.0).collect::<Vec<_>>().join(" ")
270}
271
272pub fn bash() -> String {
273    let cases = cases(|cmd, words, path| format!("        {cmd}) words=\"{words}\"; files=\"{}\" ;;\n", if path { " -f" } else { "" }));
274    let nested: String =
275        nested().iter().map(|(cmd, words)| format!("            {cmd}) COMPREPLY=($(compgen -W \"{words}\" -- \"$cur\")); return ;;\n")).collect();
276    format!(
277        r#"# bash completion for borg (borg completions bash)
278_borg() {{
279    local cur="${{COMP_WORDS[COMP_CWORD]}}" words="" files=""
280    if [ "$COMP_CWORD" -eq 1 ]; then
281        COMPREPLY=($(compgen -W "{names}" -- "$cur"))
282        return
283    fi
284    if [ "$COMP_CWORD" -gt 2 ] && [ "${{COMP_WORDS[1]}}" = debug ]; then
285        case "${{COMP_WORDS[2]}}" in
286{nested}        esac
287    fi
288    case "${{COMP_WORDS[1]}}" in
289{cases}    esac
290    COMPREPLY=($(compgen -W "$words" -- "$cur"))
291    if [ -n "$files" ] && [ "${{cur:0:1}}" != "-" ]; then
292        COMPREPLY+=($(compgen -f -- "$cur"))
293    fi
294}}
295complete -o default -F _borg borg
296"#,
297        names = names()
298    )
299}
300
301pub fn zsh() -> String {
302    let cases = cases(|cmd, words, path| format!("        {cmd}) compadd -- {words}{} ;;\n", if path { "; _files" } else { "" }));
303    let nested: String = nested().iter().map(|(cmd, words)| format!("            {cmd}) compadd -- {words}; return ;;\n")).collect();
304    format!(
305        r#"#compdef borg
306# zsh completion for borg (borg completions zsh)
307_borg() {{
308    if (( CURRENT == 2 )); then
309        compadd -- {names}
310        return
311    fi
312    if (( CURRENT > 3 )) && [[ ${{words[2]}} == debug ]]; then
313        case "${{words[3]}}" in
314{nested}        esac
315    fi
316    case "${{words[2]}}" in
317{cases}    esac
318}}
319_borg "$@"
320"#,
321        names = names()
322    )
323}
324
325pub fn fish() -> String {
326    let mut out =
327        format!("# fish completion for borg (borg completions fish)\ncomplete -c borg -f\ncomplete -c borg -n __fish_use_subcommand -a '{}'\n", names());
328    // fish sees every word: `borg debug vectors` has also seen `vectors`, so a command a debug one shares a
329    // name with completes only outside `debug`, and a nested debug command's subcommands only inside it.
330    for (cmd, subs, flags, path) in completed() {
331        let when = if DEBUG.iter().any(|d| d.name == cmd) {
332            format!("__fish_seen_subcommand_from {cmd}; and not __fish_seen_subcommand_from debug")
333        } else {
334            format!("__fish_seen_subcommand_from {cmd}")
335        };
336        if !subs.is_empty() {
337            out.push_str(&format!("complete -c borg -n '{when}' -a '{}'\n", subs.join(" ")));
338        }
339        for f in flags {
340            out.push_str(&format!("complete -c borg -n '{when}' -l {}\n", f.trim_start_matches("--")));
341        }
342        if path {
343            out.push_str(&format!("complete -c borg -n '{when}' -F\n"));
344        }
345    }
346    for c in DEBUG.iter().filter(|c| !c.subs.is_empty()) {
347        let subs = subs_of(c.subs).join(" ");
348        out.push_str(&format!("complete -c borg -n '__fish_seen_subcommand_from debug; and __fish_seen_subcommand_from {}' -a '{subs}'\n", c.name));
349    }
350    out
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356
357    #[test]
358    fn every_shell_names_every_command() {
359        for script in [bash(), zsh(), fish()] {
360            for (cmd, ..) in completed() {
361                assert!(script.contains(cmd), "{cmd} missing");
362            }
363        }
364        assert!(bash().contains("queen) words=\"show ask answer"));
365        assert!(zsh().starts_with("#compdef borg"));
366        assert!(fish().contains("-n '__fish_seen_subcommand_from install' -l apply"));
367        assert!(bash().contains("install) words=\"claude omp opencode codex all --apply"), "{}", bash());
368        assert!(!bash().contains(" sim ") && !bash().contains(HARNESSES), "the simulated harness stays hidden");
369    }
370
371    #[test]
372    fn a_command_shared_with_debug_completes_outside_debug_only() {
373        let fish = fish();
374        assert!(fish.contains("-n '__fish_seen_subcommand_from vectors; and not __fish_seen_subcommand_from debug' -l fetch"), "{fish}");
375        assert!(fish.contains("-n '__fish_seen_subcommand_from debug' -a 'recall"), "{fish}");
376    }
377}