rustbrain-core 0.2.0

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
//! Workspace walker: Markdown notes, optional Canvas, optional Rust AST.
//!
//! [`WorkspaceIndexer`] is the engine behind [`crate::Brain::sync`]. It owns a
//! [`Database`], walks the workspace (skipping `target/`, `.git/`, etc.), and:
//!
//! 1. Upserts Markdown nodes transactionally (FTS + tags + aliases + edges)
//! 2. Indexes Obsidian Canvas relationships when the `obsidian` feature is on
//! 3. Extracts Rust symbols when the `ast` feature is on
//! 4. Resolves pending WikiLink / `symbol:` targets
//! 5. Compiles `.brain/graph.mmap` when the `mmap` feature is on

use crate::error::{BrainError, Result};
use crate::id::{content_hash, node_id_from_rel_path, rel_path_from_workspace, resolve_link_target};
use crate::ignore::IgnoreSet;
use crate::storage::Database;
use crate::types::{Edge, Node, NodeType, SyncStats};
use chrono::Utc;
use std::path::{Path, PathBuf};

/// Indexes a workspace directory into a [`Database`].
pub struct WorkspaceIndexer {
    db: Database,
    workspace: PathBuf,
    ignore: IgnoreSet,
}

impl WorkspaceIndexer {
    /// Create an indexer for `workspace` writing into `db`.
    ///
    /// Loads `.rustbrainignore` (if present) plus built-in skips. When the env
    /// var `RUSTBRAIN_IMPORT_GITIGNORE=1` is set, also merges root `.gitignore`.
    pub fn new(db: Database, workspace: impl Into<PathBuf>) -> Self {
        let workspace = workspace.into();
        let import_gi = std::env::var_os("RUSTBRAIN_IMPORT_GITIGNORE")
            .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
            .unwrap_or(false);
        // Also auto-import gitignore when .rustbrainignore asks for it.
        let import_gi = import_gi || rustbrainignore_requests_gitignore(&workspace);
        let ignore = IgnoreSet::load(&workspace, import_gi).unwrap_or_default();
        Self {
            db,
            workspace,
            ignore,
        }
    }

    /// Borrow the database.
    pub fn database(&self) -> &Database {
        &self.db
    }

    /// Consume the indexer and return the database.
    pub fn into_database(self) -> Database {
        self.db
    }

    /// Index all supported files under the workspace and bake the mmap cache.
    pub fn index_workspace(&self) -> Result<SyncStats> {
        let mut stats = SyncStats::default();

        #[cfg(feature = "ast")]
        let mut ast_parser = crate::ast::CodeAstParser::new_rust()
            .map_err(|e| BrainError::Ast(e.to_string()))?;

        self.walk_and_index(
            &self.workspace,
            &mut stats,
            #[cfg(feature = "ast")]
            &mut ast_parser,
        )?;

        // Phase 2: resolve any pending WikiLinks now that all nodes exist.
        let (resolved, still) = self.db.resolve_pending_links()?;
        stats.edges_created += resolved;
        stats.edges_pending = still;

        // Bake CSR mmap if feature enabled and .brain dir exists.
        let brain_dir = self.workspace.join(".brain");
        if brain_dir.exists() {
            #[cfg(feature = "mmap")]
            {
                let mmap_path = brain_dir.join("graph.mmap");
                self.compile_mmap(&mmap_path)?;
                stats.mmap_written = true;
            }
        }

        Ok(stats)
    }

    /// Bake current database into zero-copy CSR mmap (atomic replace).
    pub fn compile_mmap(&self, output_path: &Path) -> Result<()> {
        #[cfg(feature = "mmap")]
        {
            let node_ids = self.db.get_all_node_ids()?;
            let edges = self.db.get_csr_edges()?;
            // Phase A: no embeddings yet — vector_dim = 0.
            crate::mmap::CsrCompiler::compile(output_path, &node_ids, &edges, None, 0)?;
            Ok(())
        }
        #[cfg(not(feature = "mmap"))]
        {
            let _ = output_path;
            Err(BrainError::FeatureDisabled("mmap"))
        }
    }

    /// Index a single Markdown note (transactional, content-hash aware).
    pub fn index_markdown_file(&self, file_path: &Path, stats: &mut SyncStats) -> Result<()> {
        if !file_path.exists() || file_path.extension().and_then(|e| e.to_str()) != Some("md") {
            return Ok(());
        }

        let raw_bytes = std::fs::read(file_path)?;
        let hash = content_hash(&raw_bytes);
        let content = String::from_utf8_lossy(&raw_bytes);

        let rel = rel_path_from_workspace(&self.workspace, file_path);
        let rel_str = rel.to_string_lossy().replace('\\', "/");
        if self.ignore.is_ignored(&rel_str, false) {
            return Ok(());
        }

        let is_readme_hub = is_root_readme(&rel);
        let node_id = if is_readme_hub {
            "readme".to_string()
        } else {
            node_id_from_rel_path(&rel)
        };

        if let Some(existing) = self.db.get_content_hash(&node_id)? {
            if existing == hash {
                stats.nodes_skipped_unchanged += 1;
                return Ok(());
            }
        }

        #[cfg(feature = "obsidian")]
        let (frontmatter, body) = crate::obsidian::parse_frontmatter(&content);
        #[cfg(not(feature = "obsidian"))]
        let (frontmatter, body): (Option<()>, &str) = (None, content.as_ref());

        let title = resolve_title(
            #[cfg(feature = "obsidian")]
            frontmatter.as_ref(),
            #[cfg(not(feature = "obsidian"))]
            None,
            body,
            &rel,
        );

        let node_type = {
            #[cfg(feature = "obsidian")]
            {
                let parsed = frontmatter
                    .as_ref()
                    .and_then(|fm| fm.node_type.as_deref())
                    .and_then(NodeType::parse);
                if is_readme_hub {
                    // Root README is the project hub; default to Goal unless author overrides.
                    parsed.unwrap_or(NodeType::Goal)
                } else {
                    parsed.unwrap_or(NodeType::Concept)
                }
            }
            #[cfg(not(feature = "obsidian"))]
            {
                if is_readme_hub {
                    NodeType::Goal
                } else {
                    NodeType::Concept
                }
            }
        };

        let now = Utc::now().timestamp();
        let summary = first_substantive_line(body);

        let tags: Vec<String> = {
            #[cfg(feature = "obsidian")]
            {
                frontmatter
                    .as_ref()
                    .map(|fm| fm.tags.clone())
                    .unwrap_or_default()
            }
            #[cfg(not(feature = "obsidian"))]
            {
                Vec::new()
            }
        };

        let aliases: Vec<String> = {
            #[cfg(feature = "obsidian")]
            {
                frontmatter
                    .as_ref()
                    .map(|fm| fm.aliases.clone())
                    .unwrap_or_default()
            }
            #[cfg(not(feature = "obsidian"))]
            {
                Vec::new()
            }
        };

        // Collect wikilinks before the transaction writes.
        #[cfg(feature = "obsidian")]
        let wikilinks = crate::obsidian::extract_wikilinks(body);
        #[cfg(not(feature = "obsidian"))]
        let wikilinks: Vec<RawLink> = Vec::new();

        // Architecture plan: symbol:crate::module::Name anchors in notes.
        let symbol_refs = crate::symbols::extract_symbol_refs(body);

        let node = Node {
            id: node_id.clone(),
            node_type,
            title: title.clone(),
            file_path: Some(rel_str),
            symbol_hash: None,
            summary: Some(summary),
            content_hash: Some(hash),
            created_at: now,
            updated_at: now,
        };

        let tags_str = tags.join(" ");
        let mut links_for_tx: Vec<(String, String)> = {
            #[cfg(feature = "obsidian")]
            {
                wikilinks
                    .iter()
                    .map(|l| {
                        // WikiLinks of form [[symbol:…]] become anchors, not relates_to.
                        if let Some(rest) = l.target_node.strip_prefix("symbol:") {
                            (format!("symbol:{rest}"), "anchors".to_string())
                        } else {
                            (l.target_node.clone(), "relates_to".to_string())
                        }
                    })
                    .collect()
            }
            #[cfg(not(feature = "obsidian"))]
            {
                let _ = &wikilinks;
                Vec::new()
            }
        };
        for sref in &symbol_refs {
            links_for_tx.push((format!("symbol:{}", sref.raw), "anchors".to_string()));
        }

        // Also register file stem and title as aliases for link resolution.
        let mut extra_aliases = aliases.clone();
        if let Some(stem) = Path::new(&node.file_path.as_deref().unwrap_or(""))
            .file_stem()
            .and_then(|s| s.to_str())
        {
            extra_aliases.push(stem.to_string());
        }
        extra_aliases.push(title.clone());
        if is_readme_hub {
            extra_aliases.push("readme".into());
            extra_aliases.push("hub".into());
            extra_aliases.push("home".into());
            if let Some(name) = self.workspace.file_name().and_then(|n| n.to_str()) {
                extra_aliases.push(name.to_string());
            }
        }

        self.db.with_transaction(|conn| {
            self.db.insert_node_on(conn, &node)?;
            self.db.replace_node_tags_on(conn, &node_id, &tags)?;
            self.db
                .replace_node_aliases_on(conn, &node_id, &extra_aliases)?;
            self.db
                .index_fts_on(conn, &node_id, &title, body, &tags_str)?;

            // Clear prior outbound edges + pending for this source (idempotent).
            self.db
                .clear_edges_from_on(conn, &node_id, "relates_to")?;
            self.db.clear_edges_from_on(conn, &node_id, "anchors")?;
            self.db.clear_pending_links_for_on(conn, &node_id)?;

            for (raw_target, rel_type) in &links_for_tx {
                let resolved = if let Some(sym_path) = raw_target.strip_prefix("symbol:") {
                    resolve_symbol_against_conn(conn, sym_path)?
                } else {
                    resolve_against_conn(conn, raw_target)?
                };

                if let Some(target_id) = resolved {
                    let edge = Edge {
                        source_id: node_id.clone(),
                        target_id,
                        relation_type: rel_type.clone(),
                        weight: 1.0,
                        decay_rate: 0.0,
                        created_at: now,
                    };
                    self.db.insert_edge_on(conn, &edge)?;
                    stats.edges_created += 1;
                } else {
                    self.db.insert_pending_link_on(
                        conn,
                        &node_id,
                        raw_target,
                        rel_type,
                        now,
                    )?;
                    stats.edges_pending += 1;
                }
            }
            Ok(())
        })?;

        stats.markdown_files += 1;
        stats.nodes_upserted += 1;
        Ok(())
    }

    /// Index an Obsidian Canvas (`.canvas`) file into graph edges.
    ///
    /// Resolves file/text node labels to existing note ids when possible;
    /// otherwise records pending links. Requires the `obsidian` feature.
    #[cfg(feature = "obsidian")]
    pub fn index_canvas_file(&self, file_path: &Path, stats: &mut SyncStats) -> Result<()> {
        if !file_path.exists() || file_path.extension().and_then(|e| e.to_str()) != Some("canvas")
        {
            return Ok(());
        }

        let content = std::fs::read_to_string(file_path)?;
        let canvas = crate::obsidian::ObsidianCanvas::parse_str(&content)
            .map_err(|e| BrainError::indexer(e.to_string()))?;
        let now = Utc::now().timestamp();
        let relationships = canvas.extract_relationships();

        let (ids, aliases, titles) = self.db.link_resolution_maps()?;

        self.db.with_transaction(|conn| {
            for (src_raw, dst_raw, rel) in &relationships {
                let src = resolve_link_target(src_raw, &ids, &aliases, &titles);
                let dst = resolve_link_target(dst_raw, &ids, &aliases, &titles);
                match (src, dst) {
                    (Some(s), Some(d)) => {
                        let edge = Edge {
                            source_id: s,
                            target_id: d,
                            relation_type: rel.clone(),
                            weight: 1.0,
                            decay_rate: 0.0,
                            created_at: now,
                        };
                        self.db.insert_edge_on(conn, &edge)?;
                        stats.edges_created += 1;
                    }
                    (Some(s), None) => {
                        self.db
                            .insert_pending_link_on(conn, &s, dst_raw, rel, now)?;
                        stats.edges_pending += 1;
                    }
                    _ => {
                        // Source unknown — skip with pending if we can map nothing.
                        stats.edges_pending += 1;
                    }
                }
            }
            Ok(())
        })?;

        stats.canvas_files += 1;
        Ok(())
    }

    fn walk_and_index(
        &self,
        dir: &Path,
        stats: &mut SyncStats,
        #[cfg(feature = "ast")] ast_parser: &mut crate::ast::CodeAstParser,
    ) -> Result<()> {
        if !dir.exists() {
            return Ok(());
        }

        let entries = std::fs::read_dir(dir)?;
        for entry in entries {
            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 self.ignore.skip_dir_name(name) {
                        continue;
                    }
                }
                let rel = rel_path_from_workspace(&self.workspace, &path);
                let rel_str = rel.to_string_lossy().replace('\\', "/");
                if self.ignore.is_ignored(&rel_str, true) {
                    continue;
                }
                self.walk_and_index(
                    &path,
                    stats,
                    #[cfg(feature = "ast")]
                    ast_parser,
                )?;
            } else {
                let rel = rel_path_from_workspace(&self.workspace, &path);
                let rel_str = rel.to_string_lossy().replace('\\', "/");
                if self.ignore.is_ignored(&rel_str, false) {
                    continue;
                }
                let ext = path.extension().and_then(|e| e.to_str());
                let result = match ext {
                    Some("md") => self.index_markdown_file(&path, stats),
                    #[cfg(feature = "obsidian")]
                    Some("canvas") => self.index_canvas_file(&path, stats),
                    #[cfg(feature = "ast")]
                    Some("rs") => self.index_rust_file(&path, ast_parser, stats),
                    _ => Ok(()),
                };
                if let Err(e) = result {
                    // Never abort a full-workspace sync for one bad file.
                    stats.file_errors += 1;
                    eprintln!(
                        "rustbrain: skip {} ({e})",
                        path.display()
                    );
                }
            }
        }
        Ok(())
    }

    #[cfg(feature = "ast")]
    fn index_rust_file(
        &self,
        path: &Path,
        ast_parser: &mut crate::ast::CodeAstParser,
        stats: &mut SyncStats,
    ) -> Result<()> {
        let rel = rel_path_from_workspace(&self.workspace, path);
        let rel_str = rel.to_string_lossy().replace('\\', "/");
        if self.ignore.is_ignored(&rel_str, false) {
            return Ok(());
        }
        let crate_name = infer_crate_name(&self.workspace, path);
        let source = std::fs::read_to_string(path)?;
        let anchors = ast_parser
            .parse_symbols(&crate_name, &rel_str, &source)
            .map_err(|e| BrainError::Ast(e.to_string()))?;

        for anchor in &anchors {
            self.db.insert_symbol_anchor(anchor)?;

            let node_id = crate::symbols::symbol_node_id(
                &anchor.crate_name,
                &anchor.module_path,
                &anchor.symbol_name,
            );
            // Content hash from signature so unchanged symbols are skipped next sync.
            let sig = format!(
                "{}::{}::{}@{}-{}",
                anchor.crate_name,
                anchor.module_path,
                anchor.symbol_name,
                anchor.start_line,
                anchor.end_line
            );
            let chash = crate::id::content_hash(sig.as_bytes());
            if let Some(existing) = self.db.get_content_hash(&node_id)? {
                if existing == chash {
                    stats.nodes_skipped_unchanged += 1;
                    stats.symbol_anchors += 1;
                    continue;
                }
            }

            let now = Utc::now().timestamp();
            let node = Node {
                id: node_id.clone(),
                node_type: NodeType::Symbol,
                title: anchor.symbol_name.clone(),
                file_path: Some(anchor.file_path.clone()),
                symbol_hash: Some(anchor.symbol_hash),
                summary: anchor.doc_comment.clone(),
                content_hash: Some(chash),
                created_at: now,
                updated_at: now,
            };
            self.db.insert_node(&node)?;

            // Aliases for resolution: bare name, Type::method, full path.
            let mut aliases = vec![anchor.symbol_name.clone()];
            if let Some((_, method)) = anchor.symbol_name.split_once("::") {
                aliases.push(method.to_string());
            }
            aliases.push(format!(
                "{}::{}::{}",
                anchor.crate_name, anchor.module_path, anchor.symbol_name
            ));
            self.db.replace_node_aliases(&node_id, &aliases)?;

            let fts_body = format!(
                "{} {} {} {}",
                anchor.symbol_name,
                anchor.module_path,
                anchor.crate_name,
                anchor.doc_comment.as_deref().unwrap_or("")
            );
            self.db
                .index_fts(&node_id, &anchor.symbol_name, &fts_body, "symbol")?;

            stats.nodes_upserted += 1;
            stats.symbol_anchors += 1;
        }
        stats.rust_files += 1;
        Ok(())
    }
}

fn is_root_readme(rel: &Path) -> bool {
    let comps: Vec<_> = rel
        .components()
        .filter(|c| matches!(c, std::path::Component::Normal(_)))
        .collect();
    if comps.len() != 1 {
        return false;
    }
    rel.file_name()
        .and_then(|n| n.to_str())
        .map(|n| n.eq_ignore_ascii_case("README.md"))
        .unwrap_or(false)
}

fn rustbrainignore_requests_gitignore(workspace: &Path) -> bool {
    let path = workspace.join(".rustbrainignore");
    let Ok(text) = std::fs::read_to_string(path) else {
        return false;
    };
    text.lines().any(|l| {
        let t = l.trim().to_ascii_lowercase();
        t == "# rustbrain: import-gitignore"
            || t == "#!import-gitignore"
            || t.contains("rustbrain: import-gitignore")
    })
}

fn first_substantive_line(body: &str) -> String {
    for line in body.lines() {
        let t = line.trim();
        if t.is_empty() {
            continue;
        }
        // Skip pure heading markers only lines handled below
        let cleaned = t.trim_start_matches('#').trim();
        if !cleaned.is_empty() {
            return cleaned.to_string();
        }
    }
    String::new()
}

fn resolve_title(
    #[cfg(feature = "obsidian")] frontmatter: Option<&crate::obsidian::Frontmatter>,
    #[cfg(not(feature = "obsidian"))] frontmatter: Option<&()>,
    body: &str,
    rel: &Path,
) -> String {
    #[cfg(feature = "obsidian")]
    if let Some(fm) = frontmatter {
        if let Some(title) = fm.extra.get("title").and_then(|v| v.as_str()) {
            let t = title.trim();
            if !t.is_empty() {
                return t.to_string();
            }
        }
    }
    #[cfg(not(feature = "obsidian"))]
    let _ = frontmatter;

    // First H1
    for line in body.lines() {
        let t = line.trim();
        if let Some(rest) = t.strip_prefix("# ") {
            let t = rest.trim();
            if !t.is_empty() {
                return t.to_string();
            }
        }
    }

    rel.file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("Untitled")
        .to_string()
}

#[cfg(feature = "ast")]
fn infer_crate_name(workspace: &Path, file: &Path) -> String {
    // Walk up looking for Cargo.toml
    let mut cur = file.parent();
    while let Some(dir) = cur {
        let cargo = dir.join("Cargo.toml");
        if cargo.exists() {
            if let Ok(text) = std::fs::read_to_string(&cargo) {
                if let Some(name) = parse_cargo_package_name(&text) {
                    return name;
                }
            }
            if let Some(n) = dir.file_name().and_then(|n| n.to_str()) {
                return n.to_string();
            }
        }
        if dir == workspace {
            break;
        }
        cur = dir.parent();
    }
    workspace
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("workspace")
        .to_string()
}

#[cfg(feature = "ast")]
fn parse_cargo_package_name(toml: &str) -> Option<String> {
    let mut in_package = false;
    for line in toml.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
}

/// Resolve `symbol:…` path against symbol nodes / aliases.
fn resolve_symbol_against_conn(
    conn: &rusqlite::Connection,
    raw_path: &str,
) -> Result<Option<String>> {
    let Some(sym) = crate::symbols::parse_symbol_path(raw_path) else {
        return Ok(None);
    };

    // Collect all symbol node ids (type=symbol).
    let mut stmt = conn.prepare("SELECT id FROM nodes WHERE node_type = 'symbol'")?;
    let rows = stmt.query_map([], |row| row.get::<_, String>(0))?;
    let mut ids = std::collections::HashSet::new();
    for r in rows {
        ids.insert(r?);
    }

    if let Some(id) = crate::symbols::resolve_symbol_ref(&sym, &ids) {
        return Ok(Some(id));
    }

    // Fall back to alias / title resolution for the bare name.
    resolve_against_conn(conn, &sym.symbol_name)
}

/// Resolve a link target using the live connection (aliases + ids + titles).
fn resolve_against_conn(conn: &rusqlite::Connection, raw: &str) -> Result<Option<String>> {
    let key = raw.trim().to_lowercase();
    if key.is_empty() {
        return Ok(None);
    }

    // Exact id
    let exact: Option<String> = conn
        .query_row("SELECT id FROM nodes WHERE id = ?1", [&key], |row| row.get(0))
        .optional_compat()?;
    if exact.is_some() {
        return Ok(exact);
    }

    // Alias
    let by_alias: Option<String> = conn
        .query_row(
            "SELECT node_id FROM node_aliases WHERE alias = ?1",
            [&key],
            |row| row.get(0),
        )
        .optional_compat()?;
    if by_alias.is_some() {
        return Ok(by_alias);
    }

    // Title (case-insensitive) — may be ambiguous; take if unique
    let mut stmt = conn.prepare("SELECT id FROM nodes WHERE lower(title) = ?1")?;
    let rows = stmt.query_map([&key], |row| row.get::<_, String>(0))?;
    let mut hits = Vec::new();
    for r in rows {
        hits.push(r?);
    }
    if hits.len() == 1 {
        return Ok(Some(hits.remove(0)));
    }

    // Unique suffix match
    let mut stmt = conn.prepare("SELECT id FROM nodes")?;
    let rows = stmt.query_map([], |row| row.get::<_, String>(0))?;
    let mut suffix_hits = Vec::new();
    for r in rows {
        let id = r?;
        if id == key || id.ends_with(&format!("/{key}")) || id.rsplit('/').next() == Some(key.as_str())
        {
            suffix_hits.push(id);
        }
    }
    suffix_hits.sort();
    suffix_hits.dedup();
    if suffix_hits.len() == 1 {
        return Ok(Some(suffix_hits.remove(0)));
    }

    Ok(None)
}

/// Local trait shim so we can call `.optional()` style without importing OptionalExtension in every use.
trait OptionalCompat<T> {
    fn optional_compat(self) -> Result<Option<T>>;
}

impl<T> OptionalCompat<T> for std::result::Result<T, rusqlite::Error> {
    fn optional_compat(self) -> Result<Option<T>> {
        match self {
            Ok(v) => Ok(Some(v)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(BrainError::from(e)),
        }
    }
}

#[cfg(not(feature = "obsidian"))]
struct RawLink {
    target_node: String,
}

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

    #[test]
    fn index_workspace_and_fts_idempotent() {
        let dir = tempdir().unwrap();
        let docs = dir.path().join("docs");
        std::fs::create_dir_all(&docs).unwrap();
        std::fs::write(
            docs.join("raft.md"),
            "---\ntags: [raft]\nnode_type: concept\naliases: [Raft Consensus]\n---\n# Raft Consensus\nRelates to [[log-compaction]].\n",
        )
        .unwrap();
        std::fs::write(
            docs.join("log-compaction.md"),
            "---\ntags: [log]\nnode_type: concept\n---\n# Log Compaction\nSee [[raft]].\n",
        )
        .unwrap();

        let brain = dir.path().join(".brain");
        std::fs::create_dir_all(&brain).unwrap();
        let db = Database::open(brain.join("db.sqlite")).unwrap();
        let indexer = WorkspaceIndexer::new(db, dir.path());

        let s1 = indexer.index_workspace().unwrap();
        assert_eq!(s1.markdown_files, 2);
        assert!(s1.edges_created >= 2);
        let fts1 = indexer.database().count_fts_rows().unwrap();
        assert_eq!(fts1, 2);

        // Second sync should skip unchanged content and keep FTS row count stable.
        // Touch is not done — content hash matches → nodes_skipped.
        let s2 = indexer.index_workspace().unwrap();
        assert_eq!(s2.nodes_skipped_unchanged, 2);
        assert_eq!(indexer.database().count_fts_rows().unwrap(), 2);

        // Force reindex by changing content
        std::fs::write(
            docs.join("raft.md"),
            "---\ntags: [raft]\nnode_type: concept\n---\n# Raft Consensus\nUpdated body [[log-compaction]].\n",
        )
        .unwrap();
        let s3 = indexer.index_workspace().unwrap();
        assert_eq!(s3.nodes_upserted, 1);
        assert_eq!(indexer.database().count_fts_rows().unwrap(), 2);

        let hits = indexer.database().search_fts("raft").unwrap();
        assert!(!hits.is_empty());
        assert!(hits.iter().any(|n| n.id.contains("raft")));
    }

    #[test]
    fn pending_link_then_resolve() {
        let dir = tempdir().unwrap();
        let docs = dir.path().join("docs");
        std::fs::create_dir_all(&docs).unwrap();
        std::fs::write(
            docs.join("a.md"),
            "---\nnode_type: concept\n---\n# A\nLink to [[b]].\n",
        )
        .unwrap();

        let brain = dir.path().join(".brain");
        std::fs::create_dir_all(&brain).unwrap();
        let db = Database::open(brain.join("db.sqlite")).unwrap();
        let indexer = WorkspaceIndexer::new(db, dir.path());
        let s1 = indexer.index_workspace().unwrap();
        assert!(s1.edges_pending >= 1 || indexer.database().count_pending_links().unwrap() >= 1);

        std::fs::write(
            docs.join("b.md"),
            "---\nnode_type: concept\n---\n# B\nBack.\n",
        )
        .unwrap();
        let s2 = indexer.index_workspace().unwrap();
        assert!(s2.edges_created >= 1 || indexer.database().count_edges().unwrap() >= 1);
    }
}