rustbrain-core 0.3.3

Core engine for rustbrain: SQLite knowledge graph, ranked FTS, CSR mmap cache, and graph-aware AI context
Documentation
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
//! Deterministic workspace bootstrap for mature repositories.
//!
//! Creates docs scaffolds, optional `.rustbrainignore`, README-derived goals,
//! and an AST module map — **without** inventing ADRs or calling cloud models.

use crate::error::{BrainError, Result};
use crate::ignore::{recommended_ignore_extras, write_rustbrainignore};

use serde::{Deserialize, Serialize};
use std::io::{self, BufRead, IsTerminal, Write};
use std::path::{Path, PathBuf};

/// How to handle interactive prompts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BootstrapMode {
    /// Prompt on a TTY; use defaults when stdin is not a terminal.
    Interactive,
    /// Never prompt; use options as given.
    NonInteractive,
}

/// Options for [`bootstrap_workspace`].
#[derive(Debug, Clone)]
pub struct BootstrapOptions {
    /// Interaction mode.
    pub mode: BootstrapMode,
    /// Write files (false = dry-run report only).
    pub write: bool,
    /// Overwrite generated files that already exist.
    pub force: bool,
    /// Create / update `.rustbrainignore`.
    pub setup_ignore: Option<bool>,
    /// Import root `.gitignore` into `.rustbrainignore`.
    pub import_gitignore: Option<bool>,
    /// Append recommended extra ignore patterns.
    pub ignore_extras: bool,
    /// Harvest README into docs/goals/from-readme.md.
    pub harvest_readme: bool,
    /// Generate AST module map under docs/implementation/.
    pub module_map: bool,
    /// Scaffold docs/ directory tree + templates.
    pub scaffold_docs: bool,
    /// Write root `AGENTS.md` (agent cookbook for this repo). Default true when `None`.
    pub write_agents_md: Option<bool>,
    /// Optional path to a custom `AGENTS.md` template file (overrides discovery + built-in).
    pub agents_template: Option<PathBuf>,
}

impl Default for BootstrapOptions {
    fn default() -> Self {
        Self {
            mode: BootstrapMode::Interactive,
            write: true,
            force: false,
            setup_ignore: None,
            import_gitignore: None,
            ignore_extras: true,
            harvest_readme: true,
            module_map: true,
            scaffold_docs: true,
            write_agents_md: None,
            agents_template: None,
        }
    }
}

/// One planned or performed action.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BootstrapAction {
    /// Short verb (create, skip, would_create).
    pub action: String,
    /// Relative path affected.
    pub path: String,
    /// Detail message.
    pub detail: String,
}

/// Result of bootstrap.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BootstrapReport {
    /// Workspace.
    pub workspace: PathBuf,
    /// Whether files were written.
    pub wrote: bool,
    /// Actions taken or planned.
    pub actions: Vec<BootstrapAction>,
}

const DOC_DIRS: &[&str] = &[
    "docs/goals",
    "docs/adr",
    "docs/concepts",
    "docs/edge_cases",
    "docs/implementation",
    "docs/experience",
];

/// Run deterministic bootstrap for `workspace`.
pub fn bootstrap_workspace(workspace: &Path, mut opts: BootstrapOptions) -> Result<BootstrapReport> {
    let workspace = if workspace.exists() {
        workspace.canonicalize()?
    } else {
        std::fs::create_dir_all(workspace)?;
        workspace.canonicalize()?
    };

    resolve_interactive(&workspace, &mut opts)?;

    let mut actions = Vec::new();
    let wrote = opts.write;

    if opts.scaffold_docs {
        scaffold_docs(&workspace, opts.write, opts.force, &mut actions)?;
    }

    if opts.setup_ignore.unwrap_or(false) {
        setup_ignore(
            &workspace,
            opts.write,
            opts.force,
            opts.import_gitignore.unwrap_or(false),
            opts.ignore_extras,
            &mut actions,
        )?;
    }

    if opts.harvest_readme {
        harvest_readme(&workspace, opts.write, opts.force, &mut actions)?;
    }

    if opts.module_map {
        #[cfg(feature = "ast")]
        generate_module_map(&workspace, opts.write, opts.force, &mut actions)?;
        #[cfg(not(feature = "ast"))]
        {
            actions.push(BootstrapAction {
                action: "skip".into(),
                path: "docs/implementation/module-map.generated.md".into(),
                detail: "ast feature disabled — module map not generated".into(),
            });
        }
    }

    if opts.write_agents_md.unwrap_or(true) {
        write_agents_md(
            &workspace,
            opts.write,
            opts.force,
            opts.agents_template.as_deref(),
            &mut actions,
        )?;
    } else {
        actions.push(BootstrapAction {
            action: "skip".into(),
            path: "AGENTS.md".into(),
            detail: "disabled (--no-agents-md / write_agents_md=false)".into(),
        });
    }

    // Ensure brain exists when writing
    if opts.write {
        let brain = workspace.join(".brain");
        if !brain.join("db.sqlite").exists() {
            std::fs::create_dir_all(&brain)?;
            let _ = crate::storage::Database::open(brain.join("db.sqlite"))?;
            actions.push(BootstrapAction {
                action: "create".into(),
                path: ".brain/db.sqlite".into(),
                detail: "initialized empty brain database".into(),
            });
            let marker = brain.join("workspace.json");
            if !marker.exists() {
                let meta = serde_json::json!({
                    "version": 1,
                    "workspace": workspace.to_string_lossy(),
                    "bootstrapped": true,
                });
                std::fs::write(&marker, serde_json::to_string_pretty(&meta)?)?;
            }
        }
        ensure_gitignore_brain(&workspace, true, &mut actions)?;
    }

    actions.push(BootstrapAction {
        action: "next".into(),
        path: ".".into(),
        detail: if wrote {
            "run `rustbrain sync` then `rustbrain doctor` (or `rustbrain setup --yes` next time)".into()
        } else {
            "re-run with --write to apply".into()
        },
    });

    Ok(BootstrapReport {
        workspace,
        wrote,
        actions,
    })
}

fn resolve_interactive(workspace: &Path, opts: &mut BootstrapOptions) -> Result<()> {
    if opts.mode != BootstrapMode::Interactive {
        // Non-interactive defaults
        if opts.setup_ignore.is_none() {
            opts.setup_ignore = Some(true);
        }
        if opts.import_gitignore.is_none() {
            opts.import_gitignore = Some(workspace.join(".gitignore").is_file());
        }
        if opts.write_agents_md.is_none() {
            opts.write_agents_md = Some(true);
        }
        return Ok(());
    }

    let tty = io::stdin().is_terminal() && io::stdout().is_terminal();
    if !tty {
        if opts.setup_ignore.is_none() {
            opts.setup_ignore = Some(true);
        }
        if opts.import_gitignore.is_none() {
            opts.import_gitignore = Some(workspace.join(".gitignore").is_file());
        }
        if opts.write_agents_md.is_none() {
            opts.write_agents_md = Some(true);
        }
        return Ok(());
    }

    println!("rustbrain bootstrap — {}", workspace.display());
    println!("Deterministic setup (no cloud AI). Press Enter to accept [defaults].\n");

    if opts.setup_ignore.is_none() {
        let has = workspace.join(".rustbrainignore").is_file();
        let def = if has { "n" } else { "Y" };
        let ans = prompt(
            &format!(
                "Create/update .rustbrainignore? [Y/n] (default {def})"
            ),
            def,
        )?;
        opts.setup_ignore = Some(ans_yes(&ans, !has));
    }

    if opts.setup_ignore == Some(true) && opts.import_gitignore.is_none() {
        let has_gi = workspace.join(".gitignore").is_file();
        if has_gi {
            let ans = prompt(
                "Import patterns from root .gitignore into .rustbrainignore? [Y/n]",
                "Y",
            )?;
            opts.import_gitignore = Some(ans_yes(&ans, true));
        } else {
            opts.import_gitignore = Some(false);
            println!("  (no .gitignore found — skipping import)");
        }
    }

    if opts.setup_ignore == Some(true) {
        let ans = prompt(
            "Append recommended extras (target/, data/, *.parquet, .env, …)? [Y/n]",
            "Y",
        )?;
        opts.ignore_extras = ans_yes(&ans, true);

        // Offer free-form extra lines
        let ans = prompt(
            "Add extra ignore patterns now? (comma-separated, or empty) []",
            "",
        )?;
        if !ans.trim().is_empty() {
            // Stash extras in a side channel via env-like temporary — use a file write later
            // We'll append them in setup_ignore by reading a thread-local... cleaner: store on opts
            // Extend BootstrapOptions - for simplicity append into recommended via env
            std::env::set_var("RUSTBRAIN_BOOTSTRAP_EXTRA_IGNORES", ans.trim());
        }
    }

    if opts.harvest_readme {
        // already true; allow disable
        if workspace.join("README.md").is_file() {
            let ans = prompt("Harvest README.md into docs/goals/from-readme.md? [Y/n]", "Y")?;
            opts.harvest_readme = ans_yes(&ans, true);
        }
    }

    #[cfg(feature = "ast")]
    {
        let ans = prompt(
            "Generate docs/implementation/module-map.generated.md from Rust AST? [Y/n]",
            "Y",
        )?;
        opts.module_map = ans_yes(&ans, true);
    }

    let ans = prompt("Scaffold docs/ tree + ADR/goal templates? [Y/n]", "Y")?;
    opts.scaffold_docs = ans_yes(&ans, true);

    if opts.write_agents_md.is_none() {
        let has = workspace.join("AGENTS.md").is_file();
        let def = if has { "n" } else { "Y" };
        let ans = prompt(
            &format!(
                "Write root AGENTS.md (agent cookbook for rustbrain)? [Y/n] (default {def})"
            ),
            def,
        )?;
        opts.write_agents_md = Some(ans_yes(&ans, !has));
    }

    if opts.write_agents_md == Some(true) && opts.agents_template.is_none() {
        let ans = prompt(
            "Custom AGENTS.md template path? (empty = built-in or AGENTS.template.md) []",
            "",
        )?;
        if !ans.trim().is_empty() {
            opts.agents_template = Some(PathBuf::from(ans.trim()));
        }
    }

    if !opts.write {
        let ans = prompt("Write files to disk? [Y/n]", "Y")?;
        opts.write = ans_yes(&ans, true);
    }

    Ok(())
}

fn prompt(msg: &str, default: &str) -> Result<String> {
    print!("{msg} ");
    io::stdout().flush()?;
    let mut line = String::new();
    io::stdin().lock().read_line(&mut line)?;
    let t = line.trim();
    if t.is_empty() {
        Ok(default.to_string())
    } else {
        Ok(t.to_string())
    }
}

fn ans_yes(ans: &str, default_yes: bool) -> bool {
    match ans.trim().to_ascii_lowercase().as_str() {
        "y" | "yes" => true,
        "n" | "no" => false,
        "" => default_yes,
        _ => default_yes,
    }
}

fn scaffold_docs(
    workspace: &Path,
    write: bool,
    force: bool,
    actions: &mut Vec<BootstrapAction>,
) -> Result<()> {
    for d in DOC_DIRS {
        let path = workspace.join(d);
        if path.is_dir() {
            actions.push(BootstrapAction {
                action: "exists".into(),
                path: d.to_string(),
                detail: "directory already present".into(),
            });
        } else if write {
            std::fs::create_dir_all(&path)?;
            actions.push(BootstrapAction {
                action: "create".into(),
                path: d.to_string(),
                detail: "created directory".into(),
            });
        } else {
            actions.push(BootstrapAction {
                action: "would_create".into(),
                path: d.to_string(),
                detail: "directory".into(),
            });
        }
    }

    // ADR template
    let adr_tpl = workspace.join("docs/adr/TEMPLATE.md");
    write_if_allowed(
        &adr_tpl,
        "docs/adr/TEMPLATE.md",
        ADR_TEMPLATE,
        write,
        force,
        actions,
    )?;

    // Goals placeholder if empty
    let goals_readme = workspace.join("docs/goals/README.md");
    write_if_allowed(
        &goals_readme,
        "docs/goals/README.md",
        GOALS_DIR_README,
        write,
        force,
        actions,
    )?;

    // Checklist
    let checklist = workspace.join("docs/BOOTSTRAP_CHECKLIST.md");
    write_if_allowed(
        &checklist,
        "docs/BOOTSTRAP_CHECKLIST.md",
        BOOTSTRAP_CHECKLIST,
        write,
        force,
        actions,
    )?;

    Ok(())
}

fn setup_ignore(
    workspace: &Path,
    write: bool,
    force: bool,
    import_gitignore: bool,
    extras: bool,
    actions: &mut Vec<BootstrapAction>,
) -> Result<()> {
    let path = workspace.join(".rustbrainignore");
    let rel = ".rustbrainignore";
    if path.exists() && !force {
        actions.push(BootstrapAction {
            action: "skip".into(),
            path: rel.into(),
            detail: "already exists (use --force to overwrite)".into(),
        });
        return Ok(());
    }

    let mut extra_lines: Vec<String> = Vec::new();
    extra_lines.push("# rustbrain: import-gitignore".into());
    if !import_gitignore {
        // comment marker only for documentation; runtime only imports when present
        // If user declined import, remove the directive
        extra_lines.clear();
    }

    if extras {
        for l in recommended_ignore_extras() {
            extra_lines.push(l.to_string());
        }
    }

    if let Ok(more) = std::env::var("RUSTBRAIN_BOOTSTRAP_EXTRA_IGNORES") {
        for part in more.split(',') {
            let p = part.trim();
            if !p.is_empty() {
                extra_lines.push(p.to_string());
            }
        }
    }

    let extras_ref: Vec<&str> = extra_lines.iter().map(|s| s.as_str()).collect();

    if write {
        write_rustbrainignore(workspace, import_gitignore, &extras_ref)?;
        actions.push(BootstrapAction {
            action: "create".into(),
            path: rel.into(),
            detail: format!(
                "ignore file (import_gitignore={import_gitignore}, extras={extras})"
            ),
        });
    } else {
        actions.push(BootstrapAction {
            action: "would_create".into(),
            path: rel.into(),
            detail: format!(
                "ignore file (import_gitignore={import_gitignore}, extras={extras})"
            ),
        });
    }
    Ok(())
}

fn harvest_readme(
    workspace: &Path,
    write: bool,
    force: bool,
    actions: &mut Vec<BootstrapAction>,
) -> Result<()> {
    let readme = workspace.join("README.md");
    let out_rel = "docs/goals/from-readme.md";
    let out = workspace.join(out_rel);
    if !readme.is_file() {
        actions.push(BootstrapAction {
            action: "skip".into(),
            path: out_rel.into(),
            detail: "no README.md at workspace root".into(),
        });
        return Ok(());
    }

    let text = std::fs::read_to_string(&readme)?;
    let body = extract_readme_sections(&text);
    let title = first_h1(&text).unwrap_or_else(|| {
        workspace
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("Project")
            .to_string()
    });

    let content = format!(
        "---\n\
         tags: [goal, readme, generated]\n\
         node_type: goal\n\
         aliases: [from-readme, {title}]\n\
         generated: true\n\
         source: README.md\n\
         ---\n\
         # Goals harvested from README\n\n\
         > Generated by `rustbrain bootstrap`. Edit freely; re-run with `--force` to regenerate.\n\n\
         Project title: **{title}**\n\n\
         {body}\n"
    );

    write_if_allowed(&out, out_rel, &content, write, force, actions)?;
    Ok(())
}

fn extract_readme_sections(text: &str) -> String {
    // Pull sections whose headings look goal-related, plus first paragraphs.
    let mut out = String::new();
    let mut capture = true; // preamble
    let mut current = String::new();
    let mut current_title = String::from("Overview");

    let flush = |title: &str, body: &str, out: &mut String| {
        let body = body.trim();
        if body.is_empty() {
            return;
        }
        out.push_str(&format!("## {title}\n\n{body}\n\n"));
    };

    for line in text.lines() {
        if let Some(rest) = line.strip_prefix("# ") {
            // top title — skip as section
            let _ = rest;
            continue;
        }
        if let Some(rest) = line.strip_prefix("## ") {
            flush(&current_title, &current, &mut out);
            current_title = rest.trim().to_string();
            current.clear();
            let lower = current_title.to_ascii_lowercase();
            capture = lower.contains("goal")
                || lower.contains("why")
                || lower.contains("feature")
                || lower.contains("non-goal")
                || lower.contains("non goal")
                || lower.contains("about")
                || lower.contains("overview")
                || lower.contains("require")
                || lower.contains("architect");
            continue;
        }
        if capture {
            current.push_str(line);
            current.push('\n');
        }
    }
    flush(&current_title, &current, &mut out);

    if out.trim().is_empty() {
        // Fallback: first 40 non-empty lines
        let mut n = 0;
        out.push_str("## Overview\n\n");
        for line in text.lines() {
            if line.trim().is_empty() {
                continue;
            }
            if line.starts_with('#') {
                continue;
            }
            out.push_str(line);
            out.push('\n');
            n += 1;
            if n >= 40 {
                break;
            }
        }
    }
    out
}

fn first_h1(text: &str) -> Option<String> {
    for line in text.lines() {
        if let Some(rest) = line.strip_prefix("# ") {
            let t = rest.trim();
            if !t.is_empty() {
                return Some(t.to_string());
            }
        }
    }
    None
}

#[cfg(feature = "ast")]
fn generate_module_map(
    workspace: &Path,
    write: bool,
    force: bool,
    actions: &mut Vec<BootstrapAction>,
) -> Result<()> {
    use crate::ast::CodeAstParser;
    use crate::id::rel_path_from_workspace;

    let out_rel = "docs/implementation/module-map.generated.md";
    let out = workspace.join(out_rel);
    let mut parser = CodeAstParser::new_rust().map_err(|e| BrainError::Ast(e.to_string()))?;

    let crate_name = workspace
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("crate")
        .to_string();

    // Prefer package name from Cargo.toml
    let crate_name = read_package_name(workspace).unwrap_or(crate_name);

    let mut sections: Vec<(String, Vec<String>)> = Vec::new();
    walk_rs(workspace, &mut |path| {
        let rel = rel_path_from_workspace(workspace, path);
        let rel_str = rel.to_string_lossy().replace('\\', "/");
        if rel_str.starts_with("target/") {
            return;
        }
        let Ok(src) = std::fs::read_to_string(path) else {
            return;
        };
        let Ok(anchors) = parser.parse_symbols(&crate_name, &rel_str, &src) else {
            return;
        };
        if anchors.is_empty() {
            return;
        }
        let mut lines = Vec::new();
        for a in anchors {
            // Prefer public-looking / type-level items first in display
            lines.push(format!(
                "- `{}` — symbol:{}::{}::{} (`{}` L{}-{})",
                a.symbol_name,
                a.crate_name,
                a.module_path,
                a.symbol_name,
                a.file_path,
                a.start_line,
                a.end_line
            ));
        }
        sections.push((rel_str, lines));
    })?;

    sections.sort_by(|a, b| a.0.cmp(&b.0));

    let mut body = String::from(
        "---\n\
         tags: [implementation, generated, ast]\n\
         node_type: concept\n\
         aliases: [module-map, generated-module-map]\n\
         generated: true\n\
         ---\n\
         # Module map (generated)\n\n\
         > Generated by `rustbrain bootstrap` from Tree-Sitter. Do not hand-edit;\n\
         > re-run bootstrap with `--force` to refresh.\n\n",
    );

    if sections.is_empty() {
        body.push_str("_No Rust symbols found._\n");
    } else {
        for (file, lines) in &sections {
            body.push_str(&format!("## `{file}`\n\n"));
            for l in lines {
                body.push_str(l);
                body.push('\n');
            }
            body.push('\n');
        }
    }

    write_if_allowed(&out, out_rel, &body, write, force, actions)?;
    Ok(())
}

#[cfg(feature = "ast")]
fn walk_rs(dir: &Path, f: &mut dyn FnMut(&Path)) -> Result<()> {
    if !dir.is_dir() {
        return Ok(());
    }
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                if matches!(
                    name,
                    "target" | ".git" | ".brain" | "node_modules" | "vendor"
                ) || name.starts_with('.')
                {
                    continue;
                }
            }
            walk_rs(&path, f)?;
        } else if path.extension().and_then(|e| e.to_str()) == Some("rs") {
            f(&path);
        }
    }
    Ok(())
}

fn read_package_name(workspace: &Path) -> Option<String> {
    let text = std::fs::read_to_string(workspace.join("Cargo.toml")).ok()?;
    let mut in_package = false;
    for line in text.lines() {
        let t = line.trim();
        if t.starts_with('[') {
            in_package = t == "[package]";
            continue;
        }
        if in_package {
            if let Some(rest) = t.strip_prefix("name") {
                let rest = rest.trim().trim_start_matches('=').trim();
                let name = rest.trim_matches('"').trim_matches('\'').to_string();
                if !name.is_empty() {
                    return Some(name);
                }
            }
        }
    }
    None
}

fn write_if_allowed(
    abs: &Path,
    rel: &str,
    content: &str,
    write: bool,
    force: bool,
    actions: &mut Vec<BootstrapAction>,
) -> Result<()> {
    if abs.exists() && !force {
        // Allow overwrite of generated files marked generated: true
        if let Ok(existing) = std::fs::read_to_string(abs) {
            if existing.contains("generated: true") && write {
                std::fs::write(abs, content)?;
                actions.push(BootstrapAction {
                    action: "update".into(),
                    path: rel.into(),
                    detail: "regenerated (generated: true)".into(),
                });
                return Ok(());
            }
        }
        actions.push(BootstrapAction {
            action: "skip".into(),
            path: rel.into(),
            detail: "exists (use --force to overwrite)".into(),
        });
        return Ok(());
    }
    if write {
        if let Some(parent) = abs.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(abs, content)?;
        actions.push(BootstrapAction {
            action: "create".into(),
            path: rel.into(),
            detail: "wrote file".into(),
        });
    } else {
        actions.push(BootstrapAction {
            action: "would_create".into(),
            path: rel.into(),
            detail: "file".into(),
        });
    }
    Ok(())
}

const ADR_TEMPLATE: &str = r#"---
tags: [adr]
node_type: adr
---
# ADR-XXXX: Title

## Status

Proposed

## Context

<!-- Why is this decision needed? -->

## Decision

<!-- What did we decide? -->

## Consequences

<!-- Trade-offs, follow-ups -->

<!-- After writing, rename to docs/adr/000N-slug.md and link from goals/concepts. -->
"#;

const GOALS_DIR_README: &str = r#"---
tags: [goal, index]
node_type: goal
---
# Goals index

Place project goals and non-goals here.

- `from-readme.md` — harvested by `rustbrain bootstrap` (when README exists)
- Add ADRs under `docs/adr/` for decisions that achieve these goals
"#;

const BOOTSTRAP_CHECKLIST: &str = r#"# Bootstrap checklist

Generated by `rustbrain bootstrap`. Tick items as you promote drafts into real knowledge.

- [ ] Review `docs/goals/from-readme.md` (edit for accuracy)
- [ ] Promote real architectural decisions into `docs/adr/0001-….md` (do **not** invent history)
- [ ] Skim `docs/implementation/module-map.generated.md` and link key symbols from concepts
- [ ] Add `edge_case` notes for known traps
- [ ] Read / customize root `AGENTS.md` for AI coding agents
- [ ] Run `rustbrain sync`
- [ ] Run `rustbrain doctor` and clear pending links
- [ ] Optional: `rustbrain note new --type concept --title "…" --note "…"` for atomic notes
"#;

/// Built-in root `AGENTS.md` body written by bootstrap/setup.
///
/// Override with `--agents-template`, `RUSTBRAIN_AGENTS_TEMPLATE`, or
/// workspace `AGENTS.template.md` / `.rustbrain/AGENTS.template.md`.
pub fn default_agents_md_template() -> &'static str {
    DEFAULT_AGENTS_MD
}

/// Resolve template content: explicit path → env → workspace templates → built-in.
pub fn resolve_agents_md_template(
    workspace: &Path,
    explicit: Option<&Path>,
) -> Result<(String, String)> {
    if let Some(p) = explicit {
        let text = std::fs::read_to_string(p).map_err(|e| {
            BrainError::Indexer(format!(
                "failed to read AGENTS template {}: {e}",
                p.display()
            ))
        })?;
        return Ok((text, format!("file:{}", p.display())));
    }
    if let Ok(env_path) = std::env::var("RUSTBRAIN_AGENTS_TEMPLATE") {
        let p = PathBuf::from(env_path.trim());
        if !p.as_os_str().is_empty() && p.is_file() {
            let text = std::fs::read_to_string(&p)?;
            return Ok((text, format!("env:{}", p.display())));
        }
    }
    for rel in [
        ".rustbrain/AGENTS.template.md",
        "AGENTS.template.md",
    ] {
        let p = workspace.join(rel);
        if p.is_file() {
            let text = std::fs::read_to_string(&p)?;
            return Ok((text, format!("workspace:{rel}")));
        }
    }
    Ok((DEFAULT_AGENTS_MD.to_string(), "builtin".into()))
}

fn write_agents_md(
    workspace: &Path,
    write: bool,
    force: bool,
    explicit_template: Option<&Path>,
    actions: &mut Vec<BootstrapAction>,
) -> Result<()> {
    let (content, source) = resolve_agents_md_template(workspace, explicit_template)?;
    let out = workspace.join("AGENTS.md");
    // Prefer not clobbering a hand-edited AGENTS.md unless --force.
    // If content is still the rustbrain-generated header, allow --force refresh.
    if out.is_file() && !force {
        actions.push(BootstrapAction {
            action: "skip".into(),
            path: "AGENTS.md".into(),
            detail: format!("exists (use --force to overwrite; template source was {source})"),
        });
        return Ok(());
    }
    write_if_allowed(
        &out,
        "AGENTS.md",
        &content,
        write,
        force,
        actions,
    )?;
    if let Some(last) = actions.last_mut() {
        if last.path == "AGENTS.md" && (last.action == "create" || last.action == "would_create" || last.action == "update") {
            last.detail = format!("{} (template={source})", last.detail);
        }
    }
    Ok(())
}

/// Convenience used by CLI tests / agents: non-interactive write bootstrap.
pub fn bootstrap_noninteractive(workspace: &Path, write: bool, force: bool) -> Result<BootstrapReport> {
    bootstrap_workspace(
        workspace,
        BootstrapOptions {
            mode: BootstrapMode::NonInteractive,
            write,
            force,
            setup_ignore: Some(true),
            import_gitignore: Some(workspace.join(".gitignore").is_file()),
            ignore_extras: true,
            harvest_readme: true,
            module_map: true,
            scaffold_docs: true,
            write_agents_md: Some(true),
            agents_template: None,
        },
    )
}

const DEFAULT_AGENTS_MD: &str = r#"<!-- rustbrain-agents-md: generated by `rustbrain bootstrap` / `rustbrain setup`.
     Edit freely. Re-run with --force to replace from the template.
     Customize the template: AGENTS.template.md | .rustbrain/AGENTS.template.md
     | --agents-template PATH | RUSTBRAIN_AGENTS_TEMPLATE=PATH
     Skip: rustbrain bootstrap --no-agents-md  /  setup --no-agents-md
-->
# AGENTS.md — working in this repository

This project uses **[rustbrain](https://github.com/shan-alexander/rustbrain)**: a local Markdown + SQLite second brain for humans and AI agents.

## First time (or empty brain)

```bash
# ensure CLI is available
#   cargo install rustbrain --locked
#   export PATH="$HOME/.cargo/bin:$PATH"

rustbrain setup --yes
rustbrain doctor
```

Or step-by-step: `init` → `bootstrap --yes --write` → `sync` → `doctor`.

## Everyday agent loop

1. **Orient** — load decision/context pack (not raw `find` + hope):

   ```bash
   rustbrain context "why <decision> / how does <feature> work"
   # default output is markdown; use -F xml for tool protocols
   ```

2. **Search notes** (note-first; symbols only when needed):

   ```bash
   rustbrain query "topic" --scores
   rustbrain query "TypeName" --with-symbols
   ```

3. **Write knowledge** (auto-syncs so notes are immediately searchable):

   ```bash
   rustbrain note new \
     --type adr \
     --title "Short decision title" \
     --note "Context, decision, consequences. Link code with symbol:Type::method."
   # skip index: --no-sync
   ```

4. **After code or docs changes:**

   ```bash
   rustbrain sync
   rustbrain doctor
   rustbrain links    # unresolved WikiLinks / symbol: refs
   ```

## Where knowledge lives

| Path | Purpose |
|------|---------|
| `README.md` | Hub (indexed as node id `readme`) |
| `docs/goals/` | Goals / non-goals (`from-readme.md` is harvested) |
| `docs/adr/` | Architecture decisions (fill real ADRs; do not invent history) |
| `docs/concepts/` | Atomic notes |
| `docs/edge_cases/` | Traps, platform quirks |
| `docs/implementation/` | How it works; `module-map.generated.md` from AST |
| `docs/experience/` | Postmortems / learnings |
| `.brain/` | Local index (gitignored) — never commit |
| `.rustbrainignore` | Extra paths to skip while indexing |

## Conventions for good retrieval

- Prefer **short, factual** ADR/concept notes over chat logs.
- Link code with `symbol:Name` or `symbol:crate::mod::Name` (or `[[symbol:…]]`).
- Use frontmatter when useful:

  ```yaml
  ---
  tags: [topic]
  node_type: adr   # goal | adr | concept | edge_case | …
  aliases: [short-name]
  ---
  ```

- Natural-language questions work: e.g. `why egui not tauri` (stopwords stripped, multi-token OR).
- Overview prompts (`summarize architecture`) fall back to README / hub notes.

## Do / don't

**Do**

- Run `rustbrain context "…"` before large refactors that depend on prior decisions.
- Capture new decisions with `note new --type adr` as you make them.
- Keep `docs/` truthful; re-run `bootstrap --force` only for *generated* harvest files.

**Don't**

- Invent ADR history the repo never had.
- Commit `.brain/` databases.
- Assume `query` includes symbols by default (use `--with-symbols` for code search).

## Optional

```bash
rustbrain bootstrap --dry-run          # plan only
rustbrain bootstrap --no-agents-md     # skip writing this file
rustbrain watch                        # debounced re-index
rustbrain export --out brain.brainbundle
```

Full CLI: see the rustbrain `docs/CLI.md` in the rustbrain repository (or `rustbrain --help`).
"#;

/// Ensure `.brain/` is listed in the workspace `.gitignore` (create file if needed).
fn ensure_gitignore_brain(
    workspace: &Path,
    write: bool,
    actions: &mut Vec<BootstrapAction>,
) -> Result<()> {
    let gi = workspace.join(".gitignore");
    if gi.is_file() {
        let text = std::fs::read_to_string(&gi)?;
        let already = text.lines().any(|l| {
            let t = l.trim();
            t == ".brain/" || t == ".brain" || t == "**/.brain/" || t == "/.brain/"
        });
        if already {
            actions.push(BootstrapAction {
                action: "skip".into(),
                path: ".gitignore".into(),
                detail: ".brain/ already ignored".into(),
            });
            return Ok(());
        }
        if write {
            let mut out = text;
            if !out.ends_with('\n') && !out.is_empty() {
                out.push('\n');
            }
            out.push_str("\n# rustbrain local index\n.brain/\n");
            std::fs::write(&gi, out)?;
            actions.push(BootstrapAction {
                action: "update".into(),
                path: ".gitignore".into(),
                detail: "appended .brain/".into(),
            });
        } else {
            actions.push(BootstrapAction {
                action: "would_update".into(),
                path: ".gitignore".into(),
                detail: "append .brain/".into(),
            });
        }
    } else if write {
        std::fs::write(
            &gi,
            "# rustbrain local index\n.brain/\n",
        )?;
        actions.push(BootstrapAction {
            action: "create".into(),
            path: ".gitignore".into(),
            detail: "created with .brain/".into(),
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn bootstrap_writes_scaffold() {
        let dir = tempdir().unwrap();
        std::fs::write(
            dir.path().join("README.md"),
            "# Demo\n\n## Why\n\nFast local tools.\n\n## Features\n\n- A\n- B\n",
        )
        .unwrap();
        std::fs::write(dir.path().join(".gitignore"), "target/\n*.log\n").unwrap();
        std::fs::create_dir_all(dir.path().join("src")).unwrap();
        std::fs::write(dir.path().join("src/lib.rs"), "pub fn hello() {}\n").unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .unwrap();

        let report = bootstrap_noninteractive(dir.path(), true, false).unwrap();
        assert!(report.wrote);
        assert!(dir.path().join("docs/goals").is_dir());
        assert!(dir.path().join("docs/adr/TEMPLATE.md").is_file());
        assert!(dir.path().join(".rustbrainignore").is_file());
        assert!(dir.path().join("docs/goals/from-readme.md").is_file());
        let agents = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
        assert!(
            agents.contains("rustbrain"),
            "AGENTS.md should mention rustbrain"
        );
        assert!(agents.contains("rustbrain context") || agents.contains("setup --yes"));
        let gi = std::fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert!(gi.contains(".brain/"), "expected .brain/ in gitignore: {gi}");
        #[cfg(feature = "ast")]
        assert!(dir
            .path()
            .join("docs/implementation/module-map.generated.md")
            .is_file());
    }

    #[test]
    fn bootstrap_can_skip_agents_md() {
        let dir = tempdir().unwrap();
        bootstrap_workspace(
            dir.path(),
            BootstrapOptions {
                mode: BootstrapMode::NonInteractive,
                write: true,
                force: false,
                setup_ignore: Some(false),
                import_gitignore: Some(false),
                ignore_extras: false,
                harvest_readme: false,
                module_map: false,
                scaffold_docs: true,
                write_agents_md: Some(false),
                agents_template: None,
            },
        )
        .unwrap();
        assert!(!dir.path().join("AGENTS.md").exists());
    }

    #[test]
    fn bootstrap_uses_custom_agents_template() {
        let dir = tempdir().unwrap();
        let tpl = dir.path().join("my-agents.tpl");
        std::fs::write(&tpl, "# Custom agents file\n\nUse the force.\n").unwrap();
        bootstrap_workspace(
            dir.path(),
            BootstrapOptions {
                mode: BootstrapMode::NonInteractive,
                write: true,
                force: false,
                setup_ignore: Some(false),
                import_gitignore: Some(false),
                ignore_extras: false,
                harvest_readme: false,
                module_map: false,
                scaffold_docs: false,
                write_agents_md: Some(true),
                agents_template: Some(tpl),
            },
        )
        .unwrap();
        let agents = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
        assert!(agents.contains("Use the force"));
    }

    #[test]
    fn bootstrap_uses_workspace_agents_template_file() {
        let dir = tempdir().unwrap();
        std::fs::write(
            dir.path().join("AGENTS.template.md"),
            "# From workspace template\n",
        )
        .unwrap();
        bootstrap_workspace(
            dir.path(),
            BootstrapOptions {
                mode: BootstrapMode::NonInteractive,
                write: true,
                force: false,
                setup_ignore: Some(false),
                import_gitignore: Some(false),
                ignore_extras: false,
                harvest_readme: false,
                module_map: false,
                scaffold_docs: false,
                write_agents_md: Some(true),
                agents_template: None,
            },
        )
        .unwrap();
        let agents = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
        assert!(agents.contains("From workspace template"));
    }
}