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