1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! # rustbrain CLI
//!
//! Command-line interface for [rustbrain](https://github.com/shan-alexander/rustbrain).
//!
//! ```bash
//! rustbrain setup --yes # init + bootstrap + sync (+ doctor)
//! rustbrain note new --type concept --title "X" --note "body for agents"
//! rustbrain query "topic" --no-symbols --scores
//! rustbrain context "why egui not tauri" -F markdown
//! ```
use anyhow::{bail, Context, Result};
use clap::{Parser, Subcommand};
use rustbrain_core::{
bootstrap_workspace, create_note, run_doctor, BootstrapMode, BootstrapOptions, Brain,
GlobalRegistry, NoteNewOptions, NodeType, QueryOptions,
};
use std::path::PathBuf;
use std::process::ExitCode;
#[derive(Parser)]
#[command(name = "rustbrain")]
#[command(
about = "Project-scoped, Rust-first second-brain knowledge engine for engineers and AI agents",
long_about = None,
version
)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Initialize a `.brain` directory in the workspace
Init {
/// Workspace directory (defaults to current directory)
#[arg(default_value = ".")]
workspace: PathBuf,
},
/// One-shot: init + bootstrap + sync (+ optional doctor) for agents/CI
Setup {
/// Workspace root
#[arg(default_value = ".")]
workspace: PathBuf,
/// Non-interactive (accepted for symmetry with bootstrap; setup is always non-interactive)
#[arg(long, short = 'y', default_value_t = true)]
yes: bool,
/// Overwrite generated bootstrap files
#[arg(long, default_value_t = false)]
force: bool,
/// Skip doctor at the end
#[arg(long, default_value_t = false)]
no_doctor: bool,
/// Skip bootstrap (only init + sync)
#[arg(long, default_value_t = false)]
no_bootstrap: bool,
},
/// Deterministic docs/ignore bootstrap for mature repositories
Bootstrap {
/// Workspace root
#[arg(default_value = ".")]
workspace: PathBuf,
/// Write files (default: true when --yes; otherwise interactive may ask)
#[arg(long, default_value_t = false)]
write: bool,
/// Dry-run: print plan only
#[arg(long, default_value_t = false)]
dry_run: bool,
/// Non-interactive (agents/CI): sensible defaults, no prompts
#[arg(long, short = 'y', default_value_t = false)]
yes: bool,
/// Overwrite existing generated files / ignore file
#[arg(long, default_value_t = false)]
force: bool,
/// Skip .rustbrainignore setup
#[arg(long, default_value_t = false)]
no_ignore: bool,
/// Force import of root .gitignore into .rustbrainignore
#[arg(long, default_value_t = false)]
import_gitignore: bool,
/// Do not import .gitignore
#[arg(long, default_value_t = false)]
no_import_gitignore: bool,
},
/// Health check: pending links, ratios, schema
Doctor {
/// Workspace root
#[arg(default_value = ".")]
workspace: PathBuf,
/// Emit JSON instead of text
#[arg(long, default_value_t = false)]
json: bool,
/// Exit 1 when unhealthy or when pending links exist
#[arg(long, default_value_t = false)]
strict: bool,
},
/// Create structured Markdown notes
Note {
#[command(subcommand)]
cmd: NoteCmd,
},
/// List unresolved WikiLink / symbol targets
Links {
/// Workspace root
#[arg(short = 'w', long, default_value = ".")]
workspace: PathBuf,
/// Only show pending (default true)
#[arg(long, default_value_t = true)]
pending: bool,
/// JSON output
#[arg(long, default_value_t = false)]
json: bool,
},
/// Index notes and code symbols; bake the CSR mmap cache
Sync {
/// Target workspace directory
#[arg(default_value = ".")]
workspace: PathBuf,
},
/// Query notes via ranked FTS5 + tag/alias boosts
Query {
/// Search query terms
query: String,
/// Query across all registered workspaces on this machine
#[arg(long, default_value_t = false)]
all_workspaces: bool,
/// Max results
#[arg(short = 'n', long, default_value_t = 25)]
limit: usize,
/// Show ranking scores
#[arg(long, default_value_t = false)]
scores: bool,
/// Exclude symbol nodes (typical for human search)
#[arg(long, default_value_t = false)]
no_symbols: bool,
/// Only these node types (comma-separated: goal,adr,concept,…)
#[arg(long, value_name = "TYPES")]
r#type: Option<String>,
/// Include all types including symbols (overrides --no-symbols)
#[arg(long, default_value_t = false)]
all_types: bool,
/// Workspace root containing `.brain/`
#[arg(short = 'w', long, default_value = ".")]
workspace: PathBuf,
},
/// Build graph-aware prompt context (FTS seeds + CSR neighbors)
Context {
/// Topic or prompt (positional; same as `-p`)
#[arg(value_name = "PROMPT")]
prompt: Option<String>,
/// Topic or prompt requirement (`-p` / `--for-prompt`)
#[arg(short = 'p', long = "for-prompt")]
for_prompt: Option<String>,
/// Approximate max tokens for context output
#[arg(short = 'm', long, default_value = "2048")]
max_tokens: usize,
/// Graph expansion hop depth (0 = seeds only)
#[arg(long, default_value_t = 1)]
hops: usize,
/// Include symbols as FTS seeds (default: notes-first; hops to symbols still allowed)
#[arg(long, default_value_t = false)]
with_symbols: bool,
/// Alias for `--with-symbols` (include every node type as seeds)
#[arg(long, default_value_t = false)]
all_types: bool,
/// Exclude symbols from graph-hop packing (as well as seeds)
#[arg(long, default_value_t = false)]
no_hop_symbols: bool,
/// Legacy alias: exclude symbol seeds (default behavior; kept for scripts)
#[arg(long, default_value_t = false, hide = true)]
no_symbols: bool,
/// Only these seed types (comma-separated)
#[arg(long, value_name = "TYPES")]
r#type: Option<String>,
/// Output format: `xml` or `markdown`
#[arg(short = 'F', long, default_value = "xml")]
format: String,
/// Workspace root (walks parents for `.brain` like git)
#[arg(short = 'w', long, default_value = ".")]
workspace: PathBuf,
},
/// Watch workspace for changes and re-index (debounced)
Watch {
/// Workspace root
#[arg(default_value = ".")]
workspace: PathBuf,
/// Debounce window in milliseconds
#[arg(long, default_value_t = 300)]
debounce_ms: u64,
},
/// Export brain into a portable `.brainbundle` file
Export {
/// Output path for export bundle
#[arg(short, long)]
out: PathBuf,
/// Strip repo-local AST symbol nodes and file paths
#[arg(long, default_value_t = true)]
decouple_ast: bool,
/// Workspace root
#[arg(short = 'w', long, default_value = ".")]
workspace: PathBuf,
},
/// Import a `.brainbundle` into the workspace brain
Import {
/// Input bundle path
#[arg(short, long)]
input: PathBuf,
/// Workspace root
#[arg(short = 'w', long, default_value = ".")]
workspace: PathBuf,
},
}
#[derive(Subcommand)]
enum NoteCmd {
/// Create a new Markdown note under docs/
New {
/// Node type: goal, adr, alternative, concept, reference, edge_case
#[arg(long, value_name = "TYPE")]
r#type: String,
/// Title (H1 + filename slug)
#[arg(long)]
title: String,
/// Body text after the title (efficient for AI agents)
#[arg(long)]
note: Option<String>,
/// Comma-separated tags
#[arg(long)]
tags: Option<String>,
/// Comma-separated aliases
#[arg(long)]
aliases: Option<String>,
/// Override directory (default from type)
#[arg(long)]
dir: Option<PathBuf>,
/// Overwrite if the file exists
#[arg(long, default_value_t = false)]
force: bool,
/// Workspace root
#[arg(short = 'w', long, default_value = ".")]
workspace: PathBuf,
/// Sync immediately after write
#[arg(long, default_value_t = false)]
sync: bool,
},
}
fn main() -> ExitCode {
match run() {
Ok(code) => code,
Err(e) => {
eprintln!("error: {e:#}");
ExitCode::FAILURE
}
}
}
fn run() -> Result<ExitCode> {
let cli = Cli::parse();
match cli.command {
Commands::Init { workspace } => {
let brain = Brain::create(&workspace)
.with_context(|| format!("failed to init brain in {}", workspace.display()))?;
println!(
"initialized rustbrain at {}",
brain.brain_dir().join("db.sqlite").display()
);
println!("nodes: {}", brain.database().count_nodes()?);
println!("hint: run `rustbrain setup --yes` (or bootstrap --yes --write && sync)");
if let Ok(mut reg) = GlobalRegistry::load() {
let _ = reg.register(brain.workspace());
}
Ok(ExitCode::SUCCESS)
}
Commands::Setup {
workspace,
yes,
force,
no_doctor,
no_bootstrap,
} => {
let _ = yes; // always non-interactive for setup
let brain = Brain::create(&workspace)
.with_context(|| format!("failed to init brain in {}", workspace.display()))?;
println!(
"setup: initialized {}",
brain.brain_dir().join("db.sqlite").display()
);
if let Ok(mut reg) = GlobalRegistry::load() {
let _ = reg.register(brain.workspace());
}
if !no_bootstrap {
let import = workspace.join(".gitignore").is_file();
let opts = BootstrapOptions {
mode: BootstrapMode::NonInteractive,
write: true,
force,
setup_ignore: Some(true),
import_gitignore: Some(import),
ignore_extras: true,
harvest_readme: true,
module_map: true,
scaffold_docs: true,
};
let report = bootstrap_workspace(&workspace, opts)?;
for a in &report.actions {
if a.action != "next" {
println!(" [{}] {} — {}", a.action, a.path, a.detail);
}
}
println!("setup: bootstrap complete");
}
let mut brain = Brain::open_or_create(&workspace)?;
println!("setup: syncing {} ...", brain.workspace().display());
let stats = brain.sync()?;
println!(
"setup: sync complete nodes_upserted={} symbols={} pending={} file_errors={}",
stats.nodes_upserted, stats.symbol_anchors, stats.edges_pending, stats.file_errors
);
if let Ok(mut reg) = GlobalRegistry::load() {
let _ = reg.register(brain.workspace());
}
if !no_doctor {
let report = run_doctor(brain.workspace())?;
print!("{}", report.to_text());
if !report.healthy {
return Ok(ExitCode::FAILURE);
}
}
println!("setup: done — try `rustbrain context \"topic\" -F markdown`");
Ok(ExitCode::SUCCESS)
}
Commands::Bootstrap {
workspace,
write,
dry_run,
yes,
force,
no_ignore,
import_gitignore,
no_import_gitignore,
} => {
let write = if dry_run { false } else { write || yes };
let mode = if yes {
BootstrapMode::NonInteractive
} else {
BootstrapMode::Interactive
};
let import = if no_import_gitignore {
Some(false)
} else if import_gitignore {
Some(true)
} else if yes {
Some(workspace.join(".gitignore").is_file())
} else {
None // interactive may ask
};
let opts = BootstrapOptions {
mode,
write,
force,
setup_ignore: if no_ignore { Some(false) } else if yes { Some(true) } else { None },
import_gitignore: import,
ignore_extras: true,
harvest_readme: true,
module_map: true,
scaffold_docs: true,
};
let report = bootstrap_workspace(&workspace, opts)?;
for a in &report.actions {
println!("[{}] {} — {}", a.action, a.path, a.detail);
}
if report.wrote {
println!("\nbootstrap wrote files under {}", report.workspace.display());
println!("next: rustbrain sync && rustbrain doctor");
} else {
println!("\ndry-run complete (no files written). pass --write or --yes --write");
}
Ok(ExitCode::SUCCESS)
}
Commands::Doctor {
workspace,
json,
strict,
} => {
let report = run_doctor(&workspace)?;
if json {
println!("{}", serde_json::to_string_pretty(&report)?);
} else {
print!("{}", report.to_text());
}
let fail = !report.healthy || (strict && report.pending_links > 0);
Ok(if fail {
ExitCode::FAILURE
} else {
ExitCode::SUCCESS
})
}
Commands::Note { cmd } => match cmd {
NoteCmd::New {
r#type,
title,
note,
tags,
aliases,
dir,
force,
workspace,
sync,
} => {
let node_type = NodeType::parse(&r#type).ok_or_else(|| {
anyhow::anyhow!(
"unknown type '{type}'. use: goal, adr, alternative, concept, reference, edge_case"
)
})?;
let tags = tags
.map(|s| {
s.split(',')
.map(|t| t.trim().to_string())
.filter(|t| !t.is_empty())
.collect()
})
.unwrap_or_default();
let aliases = aliases
.map(|s| {
s.split(',')
.map(|t| t.trim().to_string())
.filter(|t| !t.is_empty())
.collect()
})
.unwrap_or_default();
let created = create_note(
&workspace,
&NoteNewOptions {
node_type,
title,
note,
tags,
aliases,
dir,
force,
},
)?;
println!(
"wrote {} (node id after sync: {})",
created.rel_path.display(),
created.node_id
);
if sync {
let mut brain = Brain::open_or_create(&workspace)?;
let stats = brain.sync()?;
println!(
"synced: upserted={} pending={} file_errors={}",
stats.nodes_upserted, stats.edges_pending, stats.file_errors
);
}
Ok(ExitCode::SUCCESS)
}
},
Commands::Links {
workspace,
pending,
json,
} => {
let brain = Brain::open(&workspace).with_context(|| {
format!(
"database not found under {}. run `rustbrain sync` first",
workspace.display()
)
})?;
if pending {
let list = brain.database().list_pending_links()?;
if json {
println!("{}", serde_json::to_string_pretty(&list)?);
} else if list.is_empty() {
println!("no pending links");
} else {
println!("{} pending link(s):", list.len());
for p in &list {
println!(
" {} -[{}]-> {}",
p.source_id, p.relation_type, p.raw_target
);
}
}
}
Ok(ExitCode::SUCCESS)
}
Commands::Sync { workspace } => {
let mut brain = Brain::open_or_create(&workspace)
.with_context(|| format!("failed to open brain in {}", workspace.display()))?;
println!("indexing workspace {} ...", brain.workspace().display());
let stats = brain.sync()?;
println!(
"sync complete: md={} canvas={} rs={} nodes_upserted={} skipped={} edges={} pending={} symbols={} mmap={} file_errors={}",
stats.markdown_files,
stats.canvas_files,
stats.rust_files,
stats.nodes_upserted,
stats.nodes_skipped_unchanged,
stats.edges_created,
stats.edges_pending,
stats.symbol_anchors,
stats.mmap_written,
stats.file_errors
);
if let Ok(mut reg) = GlobalRegistry::load() {
let _ = reg.register(brain.workspace());
}
Ok(ExitCode::SUCCESS)
}
Commands::Query {
query,
all_workspaces,
limit,
scores,
no_symbols,
r#type,
all_types,
workspace,
} => {
let mut opts = if no_symbols && !all_types {
QueryOptions::human()
} else {
QueryOptions::default()
};
opts.limit = limit;
if all_types {
opts.no_symbols = false;
opts.include_types.clear();
}
if let Some(types) = r#type {
opts.include_types = parse_types_list(&types)?;
opts.no_symbols = false;
}
if all_workspaces {
println!("searching all registered workspaces for '{query}' ...");
let reg = GlobalRegistry::load()?;
let results = reg.search_all_ranked(&query, &opts)?;
if results.is_empty() {
println!("no matching nodes found");
return Ok(ExitCode::SUCCESS);
}
for (idx, gh) in results.iter().enumerate() {
let node = &gh.hit.node;
if scores {
println!(
"{}. [{:.3}] [{}] {} (id: {}) @{}",
idx + 1,
gh.hit.score,
node.node_type,
node.title,
node.id,
gh.workspace
);
} else {
println!(
"{}. [{}] {} (id: {}) @{}",
idx + 1,
node.node_type,
node.title,
node.id,
gh.workspace
);
}
}
return Ok(ExitCode::SUCCESS);
}
let brain = Brain::open(&workspace).with_context(|| {
format!(
"no brain found at {} or parents. run `rustbrain setup --yes` or `rustbrain sync`",
workspace.display()
)
})?;
println!("searching for '{query}' ...");
let results = brain.query_ranked(&query, &opts)?;
if results.is_empty() {
println!("no nodes found matching '{query}'");
} else {
for (idx, hit) in results.iter().enumerate() {
let node = &hit.node;
if scores {
println!(
"{}. [{:.3}] [{}] {} (id: {})",
idx + 1,
hit.score,
node.node_type,
node.title,
node.id
);
} else {
println!(
"{}. [{}] {} (id: {})",
idx + 1,
node.node_type,
node.title,
node.id
);
}
if let Some(path) = &node.file_path {
println!(" path: {path}");
}
if let Some(sum) = &node.summary {
println!(" summary: {sum}");
}
}
}
Ok(ExitCode::SUCCESS)
}
Commands::Context {
prompt,
for_prompt,
max_tokens,
hops,
with_symbols,
all_types,
no_hop_symbols,
no_symbols,
r#type,
format,
workspace,
} => {
let topic = for_prompt
.or(prompt)
.ok_or_else(|| {
anyhow::anyhow!(
"missing prompt: pass a positional topic or `-p \"…\"` / `--for-prompt`"
)
})?;
let brain = Brain::open(&workspace).with_context(|| {
format!(
"no brain found at {} or parents (looking for .brain/db.sqlite). run `rustbrain setup --yes`",
workspace.display()
)
})?;
let include_symbol_seeds = with_symbols || all_types;
let _ = no_symbols; // accepted for back-compat with older scripts
let mut opts = rustbrain_core::ContextOptions {
max_tokens,
hop_depth: hops,
// Note-first by default; symbols still hop in via anchors unless --no-hop-symbols.
no_symbols: !include_symbol_seeds,
hop_to_symbols: !no_hop_symbols,
..rustbrain_core::ContextOptions::default()
};
if let Some(types) = r#type {
opts.include_types = parse_types_list(&types)?;
opts.no_symbols = false;
}
let bundle = brain.context_for_prompt_with(&topic, &opts)?;
match format.as_str() {
"markdown" | "md" => print!("{}", bundle.to_markdown()),
"xml" => print!("{}", bundle.to_xml()),
other => bail!("unknown format '{other}' (expected xml or markdown)"),
}
Ok(ExitCode::SUCCESS)
}
Commands::Watch {
workspace,
debounce_ms,
} => {
let brain = Brain::open_or_create(&workspace)?;
println!(
"watching {} (debounce {debounce_ms}ms); Ctrl-C to stop",
brain.workspace().display()
);
brain.watch(debounce_ms)?;
Ok(ExitCode::SUCCESS)
}
Commands::Export {
out,
decouple_ast,
workspace,
} => {
let brain = Brain::open(&workspace).with_context(|| {
format!(
"database not found under {}. run `rustbrain sync` first",
workspace.display()
)
})?;
println!(
"exporting to {} (decouple_ast={decouple_ast}) ...",
out.display()
);
brain.export(&out, decouple_ast)?;
println!("export complete");
Ok(ExitCode::SUCCESS)
}
Commands::Import { input, workspace } => {
let mut brain = Brain::open_or_create(&workspace)?;
println!("importing {} ...", input.display());
let n = brain.import(&input)?;
println!("imported {n} nodes");
Ok(ExitCode::SUCCESS)
}
}
}
fn parse_types_list(s: &str) -> Result<Vec<NodeType>> {
let mut out = Vec::new();
for part in s.split(',') {
let t = part.trim();
if t.is_empty() {
continue;
}
let ty = NodeType::parse(t).ok_or_else(|| {
anyhow::anyhow!(
"unknown node type '{t}'. use: goal, adr, alternative, concept, symbol, reference, edge_case"
)
})?;
out.push(ty);
}
if out.is_empty() {
bail!("--type requires at least one node type");
}
Ok(out)
}