1pub const HARNESSES: &str = "<harnesses>";
10
11pub 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
25pub 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 cmd("facets", &[("[--apply] [--store FILE] [--jobs N]", "search facets for lessons")], &[], &["--apply", "--store", "--jobs"]),
68 cmd(
69 "memory",
70 &[
71 ("export [--json] [--absorbed] [--since DATE] [--dir DIR]", "each lesson's evidence, for a store outside borg to take over"),
72 ("absorb <id>... [--note TEXT]", "a lesson is held outside borg now: borg stops delivering it"),
73 ("release <id>...", "an absorbed lesson: borg delivers it again"),
74 ],
75 crate::memory_export::SUBS,
76 crate::memory_export::FLAGS,
77 ),
78 ],
79 ),
80 (
81 "Decisions",
82 &[
83 cmd(
84 "queen",
85 &[("[show|ask|answer|skip|dismiss|dedupe]", "open decisions waiting for you")],
86 &["show", "ask", "answer", "skip", "dismiss", "dedupe"],
87 &["--json", "--repo", "--dir", "--collective", "--apply"],
88 ),
89 Command {
90 path: true,
91 ..cmd("why", &[("<path>[:<line>[-<line>]] | <commit>", "the reasoning behind code [--full] [--json]")], &[], &["--full", "--json", "--dir"])
92 },
93 cmd("notes", &[("fetch [<commit>...]", "fetch the team's reasoning notes behind commits")], &["fetch"], &["--dir"]),
94 cmd(
95 "regress",
96 &[("[--replay A..B] [--explain] [--json]", "which earlier decisions later commits fixed (dry run)")],
97 &[],
98 crate::notes::regress_cli::FLAGS,
99 ),
100 cmd(
101 "review-fix",
102 &[("[--since DATE] [--json]", "bugs workflow reviews found and fix steps fixed, before any commit")],
103 &[],
104 crate::review_fix::FLAGS,
105 ),
106 cmd("trust", &[("[--dir DIR]", "trust per engineer and area")], &[], &["--dir"]),
107 ],
108 ),
109 (
110 "Watching",
111 &[
112 cmd("top", &[("[--once] [--json] [--dir DIR]", "the drones running across the team, live (q quits)")], &[], &["--once", "--json", "--dir"]),
113 cmd("web", &[("[--port PORT] [--dir DIR]", "a live page of knowledge and stats on 127.0.0.1")], &[], &["--port", "--dir"]),
114 ],
115 ),
116 (
117 "Team",
118 &[
119 cmd(
120 "mesh",
121 &[("<command>", "sync with team members (borg mesh --help)")],
122 &["id", "init", "invite", "invites", "join", "revoke", "members", "peer", "serve", "sync", "fetch"],
123 &["--collective", "--apply", "--paths", "--role", "--expires", "--uses", "--png", "--revoke"],
124 ),
125 cmd(
126 "tell",
127 &[(
128 "<session|drone|local|collective|engineer> <text> [--re ID]",
129 "a message to other sessions: local is this machine's, collective (or all) every member's",
130 )],
131 &["local", "collective", "all"],
132 crate::msg::FLAGS,
133 ),
134 cmd(
135 "ask",
136 &[("<session|drone|local|collective|engineer> <question> [--re ID]", "a message that asks for a reply")],
137 &["local", "collective", "all"],
138 crate::msg::FLAGS,
139 ),
140 cmd(
141 "inbox",
142 &[("[--all] [--json] [--show ID]", "this session's messages; from a terminal, every recent one; --show ID: one whole")],
143 &[],
144 crate::msg::INBOX_FLAGS,
145 ),
146 cmd(
147 "listen",
148 &[("[--off]", "wake this session when a message arrives while it is idle"), ("--wait|--stream|--queue", "the waiter (started by borg)")],
149 &[],
150 crate::listen::FLAGS,
151 ),
152 cmd(
153 "pause",
154 &[("<session|drone|local|collective> [note]", "refuse a session's tool calls until it is resumed")],
155 &["local", "collective", "all"],
156 crate::msg::STEER_FLAGS,
157 ),
158 cmd(
159 "resume",
160 &[("<session|drone|local|collective> [note]", "let a paused session's tool calls run again")],
161 &["local", "collective", "all"],
162 crate::msg::STEER_FLAGS,
163 ),
164 ],
165 ),
166];
167
168pub const DEBUG: &[Command] = &[
170 Command { path: true, ..cmd("recall", &[("<lessons.jsonl> [before_ms]", "rank lessons for text on stdin")], &[], &[]) },
171 Command { path: true, ..cmd("resolve", &[("<lessons.jsonl>", "the word rule's changed/ignored for {asked, before, edits, final} on stdin")], &[], &[]) },
172 Command { path: true, ..cmd("prefilter", &[("<lessons.jsonl> [before_ms]", "the free gate's score for a turn on stdin")], &[], &[]) },
173 Command { path: true, ..cmd("memory", &[("<lessons.jsonl> [--session ID]", "each lesson's activation and usefulness")], &[], &["--session"]) },
174 Command {
175 path: true,
176 ..cmd("expert", &[("<repo> --at <commit> --q <text>", "at most 3 cited claims from an expert repo")], &[], &["--at", "--version", "--q"])
177 },
178 cmd("vectors", &[("--query [--store LESSONS]", "the vector shortlist for a context on stdin")], &[], &["--query", "--store"]),
179 cmd("ope", &[("[--dir DIR | --file FILE] [--json]", "off-policy estimates of the belief's hand-set weights")], &[], &["--dir", "--file", "--json"]),
180 cmd(
181 "select",
182 &[(
183 "[--replay] [--rebuild] [--dir DIR | --file FILE] [--json] [--eval RUNS_DIR --qrels FILE]",
184 "the lesson selection policy and its pre-registered checks",
185 )],
186 &[],
187 &["--replay", "--rebuild", "--dir", "--file", "--json", "--eval", "--qrels"],
188 ),
189];
190
191pub const INTERNAL: &[&str] = &["hook", "check"];
193
194pub fn commands() -> impl Iterator<Item = &'static Command> {
196 GROUPS.iter().flat_map(|(_, cmds)| cmds.iter())
197}
198
199pub fn known(name: &str) -> bool {
202 commands().any(|c| c.name == name) || INTERNAL.contains(&name) || matches!(name, "debug" | "help" | "-h" | "--help" | "-V" | "--version")
203}
204
205fn completed() -> Vec<(&'static str, Vec<&'static str>, Vec<&'static str>, bool)> {
208 let mut out: Vec<_> = commands().map(|c| (c.name, subs_of(c.subs), c.flags.to_vec(), c.path)).collect();
209 let mut flags: Vec<&str> = DEBUG.iter().flat_map(|c| c.flags.iter().copied()).collect();
210 flags.sort_unstable();
211 flags.dedup();
212 out.push(("debug", DEBUG.iter().map(|c| c.name).chain(["help"]).collect(), flags, true));
213 out
214}
215
216fn nested() -> Vec<(&'static str, String)> {
219 DEBUG.iter().filter(|c| !c.subs.is_empty()).map(|c| (c.name, [subs_of(c.subs).as_slice(), c.flags].concat().join(" "))).collect()
220}
221
222const USAGE: &str = "usage: borg completions <bash|zsh|fish>
223 bash: borg completions bash > ~/.local/share/bash-completion/completions/borg
224 zsh: borg completions zsh > \"${fpath[1]}/_borg\" (then restart the shell)
225 fish: borg completions fish > ~/.config/fish/completions/borg.fish";
226
227pub fn main(args: &[&str]) -> i32 {
228 match args.first().copied() {
229 Some("bash") => print!("{}", bash()),
230 Some("zsh") => print!("{}", zsh()),
231 Some("fish") => print!("{}", fish()),
232 _ => {
233 eprintln!("{USAGE}");
234 return 2;
235 }
236 }
237 0
238}
239
240fn subs_of(subs: &[&'static str]) -> Vec<&'static str> {
242 subs.iter().flat_map(|s| if *s == HARNESSES { crate::harness::visible().map(|h| h.name()).collect() } else { vec![*s] }).collect()
243}
244
245fn cases(line: impl Fn(&str, &str, bool) -> String) -> String {
247 completed().iter().map(|(cmd, subs, flags, path)| line(cmd, &[subs.as_slice(), flags].concat().join(" "), *path)).collect()
248}
249
250fn names() -> String {
251 completed().iter().map(|c| c.0).collect::<Vec<_>>().join(" ")
252}
253
254pub fn bash() -> String {
255 let cases = cases(|cmd, words, path| format!(" {cmd}) words=\"{words}\"; files=\"{}\" ;;\n", if path { " -f" } else { "" }));
256 let nested: String =
257 nested().iter().map(|(cmd, words)| format!(" {cmd}) COMPREPLY=($(compgen -W \"{words}\" -- \"$cur\")); return ;;\n")).collect();
258 format!(
259 r#"# bash completion for borg (borg completions bash)
260_borg() {{
261 local cur="${{COMP_WORDS[COMP_CWORD]}}" words="" files=""
262 if [ "$COMP_CWORD" -eq 1 ]; then
263 COMPREPLY=($(compgen -W "{names}" -- "$cur"))
264 return
265 fi
266 if [ "$COMP_CWORD" -gt 2 ] && [ "${{COMP_WORDS[1]}}" = debug ]; then
267 case "${{COMP_WORDS[2]}}" in
268{nested} esac
269 fi
270 case "${{COMP_WORDS[1]}}" in
271{cases} esac
272 COMPREPLY=($(compgen -W "$words" -- "$cur"))
273 if [ -n "$files" ] && [ "${{cur:0:1}}" != "-" ]; then
274 COMPREPLY+=($(compgen -f -- "$cur"))
275 fi
276}}
277complete -o default -F _borg borg
278"#,
279 names = names()
280 )
281}
282
283pub fn zsh() -> String {
284 let cases = cases(|cmd, words, path| format!(" {cmd}) compadd -- {words}{} ;;\n", if path { "; _files" } else { "" }));
285 let nested: String = nested().iter().map(|(cmd, words)| format!(" {cmd}) compadd -- {words}; return ;;\n")).collect();
286 format!(
287 r#"#compdef borg
288# zsh completion for borg (borg completions zsh)
289_borg() {{
290 if (( CURRENT == 2 )); then
291 compadd -- {names}
292 return
293 fi
294 if (( CURRENT > 3 )) && [[ ${{words[2]}} == debug ]]; then
295 case "${{words[3]}}" in
296{nested} esac
297 fi
298 case "${{words[2]}}" in
299{cases} esac
300}}
301_borg "$@"
302"#,
303 names = names()
304 )
305}
306
307pub fn fish() -> String {
308 let mut out =
309 format!("# fish completion for borg (borg completions fish)\ncomplete -c borg -f\ncomplete -c borg -n __fish_use_subcommand -a '{}'\n", names());
310 for (cmd, subs, flags, path) in completed() {
313 let when = if DEBUG.iter().any(|d| d.name == cmd) {
314 format!("__fish_seen_subcommand_from {cmd}; and not __fish_seen_subcommand_from debug")
315 } else {
316 format!("__fish_seen_subcommand_from {cmd}")
317 };
318 if !subs.is_empty() {
319 out.push_str(&format!("complete -c borg -n '{when}' -a '{}'\n", subs.join(" ")));
320 }
321 for f in flags {
322 out.push_str(&format!("complete -c borg -n '{when}' -l {}\n", f.trim_start_matches("--")));
323 }
324 if path {
325 out.push_str(&format!("complete -c borg -n '{when}' -F\n"));
326 }
327 }
328 for c in DEBUG.iter().filter(|c| !c.subs.is_empty()) {
329 let subs = subs_of(c.subs).join(" ");
330 out.push_str(&format!("complete -c borg -n '__fish_seen_subcommand_from debug; and __fish_seen_subcommand_from {}' -a '{subs}'\n", c.name));
331 }
332 out
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338
339 #[test]
340 fn every_shell_names_every_command() {
341 for script in [bash(), zsh(), fish()] {
342 for (cmd, ..) in completed() {
343 assert!(script.contains(cmd), "{cmd} missing");
344 }
345 }
346 assert!(bash().contains("queen) words=\"show ask answer"));
347 assert!(zsh().starts_with("#compdef borg"));
348 assert!(fish().contains("-n '__fish_seen_subcommand_from install' -l apply"));
349 assert!(bash().contains("install) words=\"claude omp opencode codex all --apply"), "{}", bash());
350 assert!(!bash().contains(" sim ") && !bash().contains(HARNESSES), "the simulated harness stays hidden");
351 }
352
353 #[test]
354 fn a_command_shared_with_debug_completes_outside_debug_only() {
355 let fish = fish();
356 assert!(fish.contains("-n '__fish_seen_subcommand_from vectors; and not __fish_seen_subcommand_from debug' -l fetch"), "{fish}");
357 assert!(fish.contains("-n '__fish_seen_subcommand_from debug' -a 'recall"), "{fish}");
358 }
359}