remembrall-core 0.4.2

Field-aware code graph plus persistent memory for AI agents - Rust, Postgres + pgvector
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
use sqlx::PgPool;
use uuid::Uuid;

use crate::config::validate_schema_name;
use crate::error::{RemembrallError, Result};
use super::types::*;

/// Code graph storage backed by Postgres adjacency tables + recursive CTEs.
pub struct GraphStore {
    pool: PgPool,
    schema: String,
}

impl GraphStore {
    pub fn new(pool: PgPool, schema: String) -> Result<Self> {
        validate_schema_name(&schema)
            .map_err(RemembrallError::InvalidInput)?;
        Ok(Self { pool, schema })
    }

    /// Initialize graph tables.
    pub async fn init(&self) -> Result<()> {
        // Ensure schema exists
        sqlx::query(&format!("CREATE SCHEMA IF NOT EXISTS {}", self.schema))
            .execute(&self.pool)
            .await?;

        sqlx::query(&format!(
            r#"
            CREATE TABLE IF NOT EXISTS {schema}.symbols (
                id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                name TEXT NOT NULL,
                symbol_type TEXT NOT NULL,
                file_path TEXT NOT NULL,
                start_line INTEGER,
                end_line INTEGER,
                language TEXT NOT NULL,
                project TEXT NOT NULL,
                signature TEXT,
                file_mtime TIMESTAMPTZ NOT NULL,
                layer TEXT,
                created_at TIMESTAMPTZ DEFAULT NOW()
            )
            "#,
            schema = self.schema,
        ))
        .execute(&self.pool)
        .await?;

        // Add field-tracking columns to existing installs (no migration framework;
        // CREATE TABLE IF NOT EXISTS above does not add columns to an existing table, so
        // these idempotent ALTERs self-migrate on every boot without data loss).
        sqlx::query(&format!(
            r#"
            ALTER TABLE {schema}.symbols
                ADD COLUMN IF NOT EXISTS parent_symbol_id UUID,
                ADD COLUMN IF NOT EXISTS moniker TEXT
            "#,
            schema = self.schema,
        ))
        .execute(&self.pool)
        .await?;

        sqlx::query(&format!(
            r#"
            CREATE TABLE IF NOT EXISTS {schema}.relationships (
                source_id UUID NOT NULL REFERENCES {schema}.symbols(id) ON DELETE CASCADE,
                target_id UUID NOT NULL REFERENCES {schema}.symbols(id) ON DELETE CASCADE,
                rel_type TEXT NOT NULL,
                confidence REAL NOT NULL DEFAULT 1.0,
                created_at TIMESTAMPTZ DEFAULT NOW(),
                PRIMARY KEY (source_id, target_id, rel_type)
            )
            "#,
            schema = self.schema,
        ))
        .execute(&self.pool)
        .await?;

        // Indexes for fast traversal
        sqlx::query(&format!(
            r#"
            CREATE INDEX IF NOT EXISTS idx_symbols_file ON {schema}.symbols (file_path);
            "#,
            schema = self.schema,
        ))
        .execute(&self.pool)
        .await?;

        sqlx::query(&format!(
            r#"
            CREATE INDEX IF NOT EXISTS idx_symbols_name ON {schema}.symbols (name, symbol_type);
            "#,
            schema = self.schema,
        ))
        .execute(&self.pool)
        .await?;

        sqlx::query(&format!(
            r#"
            CREATE INDEX IF NOT EXISTS idx_symbols_parent ON {schema}.symbols (parent_symbol_id);
            "#,
            schema = self.schema,
        ))
        .execute(&self.pool)
        .await?;

        sqlx::query(&format!(
            r#"
            CREATE INDEX IF NOT EXISTS idx_relationships_source ON {schema}.relationships (source_id);
            "#,
            schema = self.schema,
        ))
        .execute(&self.pool)
        .await?;

        sqlx::query(&format!(
            r#"
            CREATE INDEX IF NOT EXISTS idx_relationships_target ON {schema}.relationships (target_id);
            "#,
            schema = self.schema,
        ))
        .execute(&self.pool)
        .await?;

        tracing::info!("Graph store initialized in schema '{}'", self.schema);
        Ok(())
    }

    /// Insert or update a symbol. Returns the ID.
    pub async fn upsert_symbol(&self, symbol: &Symbol) -> Result<Uuid> {
        let symbol_type = symbol.symbol_type.to_string();

        let (id,) = sqlx::query_as::<_, (Uuid,)>(&format!(
            r#"
            INSERT INTO {schema}.symbols
                (id, name, symbol_type, file_path, start_line, end_line, language, project, signature, file_mtime, layer, parent_symbol_id, moniker)
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
            ON CONFLICT (id) DO UPDATE SET
                name = EXCLUDED.name,
                symbol_type = EXCLUDED.symbol_type,
                start_line = EXCLUDED.start_line,
                end_line = EXCLUDED.end_line,
                signature = EXCLUDED.signature,
                file_mtime = EXCLUDED.file_mtime,
                layer = EXCLUDED.layer,
                parent_symbol_id = EXCLUDED.parent_symbol_id,
                moniker = EXCLUDED.moniker
            RETURNING id
            "#,
            schema = self.schema,
        ))
        .bind(symbol.id)
        .bind(&symbol.name)
        .bind(&symbol_type)
        .bind(&symbol.file_path)
        .bind(symbol.start_line)
        .bind(symbol.end_line)
        .bind(&symbol.language)
        .bind(&symbol.project)
        .bind(&symbol.signature)
        .bind(symbol.file_mtime)
        .bind(&symbol.layer)
        .bind(symbol.parent_symbol_id)
        .bind(&symbol.moniker)
        .fetch_one(&self.pool)
        .await?;

        Ok(id)
    }

    /// Insert or update a batch of symbols. Processes in chunks of 500.
    pub async fn upsert_symbols_batch(&self, symbols: &[Symbol]) -> Result<()> {
        if symbols.is_empty() {
            return Ok(());
        }

        for chunk in symbols.chunks(500) {
            // Build: INSERT INTO schema.symbols (col, ...) VALUES ($1,$2,...), ($N,...) ON CONFLICT ...
            let mut query_str = format!(
                "INSERT INTO {schema}.symbols \
                 (id, name, symbol_type, file_path, start_line, end_line, language, project, signature, file_mtime, layer, parent_symbol_id, moniker) \
                 VALUES ",
                schema = self.schema,
            );

            let cols_per_row: usize = 13;
            for (i, _) in chunk.iter().enumerate() {
                if i > 0 {
                    query_str.push_str(", ");
                }
                let base = i * cols_per_row + 1;
                query_str.push_str(&format!(
                    "(${}, ${}, ${}, ${}, ${}, ${}, ${}, ${}, ${}, ${}, ${}, ${}, ${})",
                    base,
                    base + 1,
                    base + 2,
                    base + 3,
                    base + 4,
                    base + 5,
                    base + 6,
                    base + 7,
                    base + 8,
                    base + 9,
                    base + 10,
                    base + 11,
                    base + 12,
                ));
            }

            query_str.push_str(
                " ON CONFLICT (id) DO UPDATE SET \
                 name = EXCLUDED.name, \
                 symbol_type = EXCLUDED.symbol_type, \
                 start_line = EXCLUDED.start_line, \
                 end_line = EXCLUDED.end_line, \
                 signature = EXCLUDED.signature, \
                 file_mtime = EXCLUDED.file_mtime, \
                 layer = EXCLUDED.layer, \
                 parent_symbol_id = EXCLUDED.parent_symbol_id, \
                 moniker = EXCLUDED.moniker",
            );

            let mut query = sqlx::query(&query_str);
            for sym in chunk {
                let symbol_type = sym.symbol_type.to_string();
                query = query
                    .bind(sym.id)
                    .bind(&sym.name)
                    .bind(symbol_type)
                    .bind(&sym.file_path)
                    .bind(sym.start_line)
                    .bind(sym.end_line)
                    .bind(&sym.language)
                    .bind(&sym.project)
                    .bind(&sym.signature)
                    .bind(sym.file_mtime)
                    .bind(&sym.layer)
                    .bind(sym.parent_symbol_id)
                    .bind(&sym.moniker);
            }
            query.execute(&self.pool).await?;
        }

        Ok(())
    }

    /// Insert or update a batch of relationships. Processes in chunks of 1000.
    /// Relationships with unknown source/target IDs or self-references are skipped.
    pub async fn add_relationships_batch(&self, rels: &[Relationship]) -> Result<()> {
        if rels.is_empty() {
            return Ok(());
        }

        // Collect all known symbol IDs to filter out FK violations before batching.
        let known_ids: std::collections::HashSet<Uuid> = sqlx::query_as::<_, (Uuid,)>(
            &format!("SELECT id FROM {schema}.symbols", schema = self.schema),
        )
        .fetch_all(&self.pool)
        .await?
        .into_iter()
        .map(|(id,)| id)
        .collect();

        for chunk in rels.chunks(1000) {
            // Filter self-references, unknown IDs, and deduplicate within the chunk.
            let mut seen = std::collections::HashSet::new();
            let filtered: Vec<&Relationship> = chunk
                .iter()
                .filter(|r| r.source_id != r.target_id)
                .filter(|r| known_ids.contains(&r.source_id) && known_ids.contains(&r.target_id))
                .filter(|r| seen.insert((r.source_id, r.target_id, r.rel_type.to_string())))
                .collect();

            if filtered.is_empty() {
                continue;
            }

            let mut query_str = format!(
                "INSERT INTO {schema}.relationships (source_id, target_id, rel_type, confidence) VALUES ",
                schema = self.schema,
            );

            for (i, _) in filtered.iter().enumerate() {
                if i > 0 {
                    query_str.push_str(", ");
                }
                let base = i * 4 + 1;
                query_str.push_str(&format!(
                    "(${}, ${}, ${}, ${})",
                    base,
                    base + 1,
                    base + 2,
                    base + 3,
                ));
            }

            query_str.push_str(
                " ON CONFLICT (source_id, target_id, rel_type) DO UPDATE SET \
                 confidence = EXCLUDED.confidence",
            );

            let mut query = sqlx::query(&query_str);
            for rel in &filtered {
                query = query
                    .bind(rel.source_id)
                    .bind(rel.target_id)
                    .bind(rel.rel_type.to_string())
                    .bind(rel.confidence);
            }
            query.execute(&self.pool).await?;
        }

        Ok(())
    }

    /// Add a relationship between two symbols.
    pub async fn add_relationship(&self, rel: &Relationship) -> Result<()> {
        let rel_type = rel.rel_type.to_string();

        sqlx::query(&format!(
            r#"
            INSERT INTO {schema}.relationships (source_id, target_id, rel_type, confidence)
            VALUES ($1, $2, $3, $4)
            ON CONFLICT (source_id, target_id, rel_type) DO UPDATE SET
                confidence = EXCLUDED.confidence
            "#,
            schema = self.schema,
        ))
        .bind(rel.source_id)
        .bind(rel.target_id)
        .bind(&rel_type)
        .bind(rel.confidence)
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    /// Impact analysis: find all symbols affected by a change, using recursive CTE.
    /// This is the killer feature - "what breaks if I change this function?"
    pub async fn impact_analysis(
        &self,
        symbol_id: Uuid,
        direction: Direction,
        max_depth: i32,
    ) -> Result<Vec<ImpactResult>> {
        if let Direction::Both = direction {
            let mut upstream = Box::pin(self.impact_analysis(symbol_id, Direction::Upstream, max_depth)).await?;
            let downstream = Box::pin(self.impact_analysis(symbol_id, Direction::Downstream, max_depth)).await?;
            upstream.extend(downstream);
            return Ok(upstream);
        }

        let (join_col, match_col) = match direction {
            Direction::Upstream => ("target_id", "source_id"),
            Direction::Downstream => ("source_id", "target_id"),
            Direction::Both => unreachable!(),
        };

        let sql = format!(
            r#"
            WITH RECURSIVE impact AS (
                -- Base case: direct relationships
                SELECT
                    r.{match_col} AS symbol_id,
                    r.rel_type,
                    r.confidence,
                    1 AS depth,
                    ARRAY[r.{join_col}, r.{match_col}] AS path
                FROM {schema}.relationships r
                WHERE r.{join_col} = $1

                UNION ALL

                -- Recursive: follow the chain
                SELECT
                    r.{match_col} AS symbol_id,
                    r.rel_type,
                    r.confidence * i.confidence AS confidence,
                    i.depth + 1 AS depth,
                    i.path || r.{match_col} AS path
                FROM {schema}.relationships r
                JOIN impact i ON r.{join_col} = i.symbol_id
                WHERE i.depth < $2
                AND NOT r.{match_col} = ANY(i.path)  -- prevent cycles
            )
            SELECT
                s.id, s.name, s.symbol_type, s.file_path, s.start_line, s.end_line,
                s.language, s.project, s.signature, s.file_mtime, s.layer,
                s.parent_symbol_id, s.moniker,
                i.depth, i.path, i.rel_type, i.confidence
            FROM impact i
            JOIN {schema}.symbols s ON s.id = i.symbol_id
            ORDER BY i.depth ASC, i.confidence DESC
            "#,
            schema = self.schema,
        );

        let rows = sqlx::query_as::<_, ImpactRow>(&sql)
            .bind(symbol_id)
            .bind(max_depth)
            .fetch_all(&self.pool)
            .await?;

        Ok(rows.into_iter().map(|r| r.into_impact_result()).collect())
    }

    /// Find a symbol by name or file basename, optionally filtered by type and/or project.
    ///
    /// Matching is case-insensitive and covers:
    /// - Exact name match (e.g. `UsersController`)
    /// - File basename without extension (e.g. `users_controller` matches `users_controller.rb`)
    ///
    /// Exact name matches are returned first. Results are capped at 50.
    pub async fn find_symbol(
        &self,
        name: &str,
        symbol_type: Option<&SymbolType>,
        project: Option<&str>,
    ) -> Result<Vec<Symbol>> {
        let type_filter = symbol_type.map(|t| t.to_string());

        // Build WHERE clauses dynamically based on which filters are provided.
        let mut param_idx = 2u32;
        let mut clauses = String::new();

        if type_filter.is_some() {
            clauses.push_str(&format!(" AND symbol_type = ${param_idx}"));
            param_idx += 1;
        }
        if project.is_some() {
            clauses.push_str(&format!(" AND project = ${param_idx}"));
        }

        let sql = format!(
            r#"
            SELECT id, name, symbol_type, file_path, start_line, end_line,
                   language, project, signature, file_mtime, layer,
                   parent_symbol_id, moniker
            FROM {schema}.symbols
            WHERE (
                name ILIKE $1
                OR regexp_replace(file_path, '^.*/', '') ILIKE ($1 || '.%')
                OR regexp_replace(file_path, '^.*/', '') ILIKE $1
            )
            {clauses}
            ORDER BY
                CASE WHEN lower(name) = lower($1) THEN 0 ELSE 1 END,
                name
            LIMIT 50
            "#,
            schema = self.schema,
        );

        let mut query = sqlx::query_as::<_, SymbolRow>(&sql).bind(name);
        if let Some(ref t) = type_filter {
            query = query.bind(t);
        }
        if let Some(p) = project {
            query = query.bind(p);
        }

        let rows = query.fetch_all(&self.pool).await?;
        Ok(rows.into_iter().map(|r| r.into_symbol()).collect())
    }

    /// Generate a topological ordering of files in a project, starting from entry points.
    ///
    /// Entry points are files with in-degree 0 in the import graph (nothing imports them),
    /// which are typically executables or top-level orchestrators. The algorithm runs
    /// Kahn's BFS topological sort so every dependency appears before the file that
    /// depends on it. Any files caught in a cycle are appended at the end.
    ///
    /// Returns at most `limit` stops (default 20).
    pub async fn generate_tour(&self, project: &str, limit: usize) -> Result<Vec<TourStop>> {
        // ------------------------------------------------------------------
        // 1. Fetch all file symbols for the project.
        // ------------------------------------------------------------------
        #[derive(sqlx::FromRow)]
        struct FileRow {
            id: uuid::Uuid,
            file_path: String,
            language: String,
        }

        let file_rows = sqlx::query_as::<_, FileRow>(&format!(
            r#"
            SELECT id, file_path, language
            FROM {schema}.symbols
            WHERE project = $1 AND symbol_type = 'file'
            "#,
            schema = self.schema,
        ))
        .bind(project)
        .fetch_all(&self.pool)
        .await?;

        if file_rows.is_empty() {
            return Ok(vec![]);
        }

        // Build index: file_path -> (uuid, language) - uuid kept for future use.
        let mut path_to_meta: std::collections::HashMap<String, (uuid::Uuid, String)> =
            std::collections::HashMap::new();
        for row in &file_rows {
            path_to_meta.insert(row.file_path.clone(), (row.id, row.language.clone()));
        }

        // ------------------------------------------------------------------
        // 2. Fetch all file-to-file import edges within the project.
        //    source_file imports target_file.
        // ------------------------------------------------------------------
        #[derive(sqlx::FromRow)]
        struct EdgeRow {
            source_file: String,
            target_file: String,
        }

        let edge_rows = sqlx::query_as::<_, EdgeRow>(&format!(
            r#"
            SELECT DISTINCT s.file_path AS source_file, t.file_path AS target_file
            FROM {schema}.relationships r
            JOIN {schema}.symbols s ON s.id = r.source_id
            JOIN {schema}.symbols t ON t.id = r.target_id
            WHERE r.rel_type = 'imports'
              AND s.project = $1
              AND t.project = $1
              AND s.symbol_type = 'file'
              AND t.symbol_type = 'file'
            "#,
            schema = self.schema,
        ))
        .bind(project)
        .fetch_all(&self.pool)
        .await?;

        // ------------------------------------------------------------------
        // 3. Build adjacency structures.
        //    imports_from[A] = files A imports (A depends on these).
        //    imported_by[A]  = files that import A.
        //    in_degree[A]    = number of files that import A.
        // ------------------------------------------------------------------
        let all_files: Vec<String> = file_rows.iter().map(|r| r.file_path.clone()).collect();

        let mut imports_from: std::collections::HashMap<String, Vec<String>> =
            all_files.iter().map(|f| (f.clone(), vec![])).collect();
        let mut imported_by: std::collections::HashMap<String, Vec<String>> =
            all_files.iter().map(|f| (f.clone(), vec![])).collect();

        for edge in &edge_rows {
            if imports_from.contains_key(&edge.source_file)
                && imported_by.contains_key(&edge.target_file)
            {
                imports_from
                    .entry(edge.source_file.clone())
                    .or_default()
                    .push(edge.target_file.clone());
                imported_by
                    .entry(edge.target_file.clone())
                    .or_default()
                    .push(edge.source_file.clone());
            }
        }

        // in_degree[f] = how many files import f.
        // Files with in_degree 0 are entry points (nobody imports them).
        let mut in_degree: std::collections::HashMap<String, usize> = all_files
            .iter()
            .map(|f| (f.clone(), imported_by[f].len()))
            .collect();

        // ------------------------------------------------------------------
        // 4. Fetch non-file symbol names grouped by file.
        // ------------------------------------------------------------------
        #[derive(sqlx::FromRow)]
        struct SymRow {
            file_path: String,
            name: String,
        }

        let sym_rows = sqlx::query_as::<_, SymRow>(&format!(
            r#"
            SELECT file_path, name
            FROM {schema}.symbols
            WHERE project = $1 AND symbol_type != 'file'
            ORDER BY file_path, start_line
            "#,
            schema = self.schema,
        ))
        .bind(project)
        .fetch_all(&self.pool)
        .await?;

        let mut file_symbols: std::collections::HashMap<String, Vec<String>> =
            all_files.iter().map(|f| (f.clone(), vec![])).collect();
        for row in sym_rows {
            file_symbols.entry(row.file_path).or_default().push(row.name);
        }

        // ------------------------------------------------------------------
        // 5. Kahn's BFS topological sort.
        //    Visit entry points (in_degree == 0) first. For each visited file
        //    decrement the in_degree of the files it imports; when a dependency
        //    reaches 0 it means all files that import it have been scheduled and
        //    it can now be added to the queue.
        // ------------------------------------------------------------------
        let mut initial_queue: Vec<String> = all_files
            .iter()
            .filter(|f| in_degree[*f] == 0)
            .cloned()
            .collect();
        initial_queue.sort();

        let mut queue: std::collections::VecDeque<String> =
            initial_queue.into_iter().collect();
        let mut visited: std::collections::HashSet<String> = std::collections::HashSet::new();
        let mut ordered: Vec<String> = Vec::new();

        while let Some(file) = queue.pop_front() {
            if visited.contains(&file) {
                continue;
            }
            visited.insert(file.clone());
            ordered.push(file.clone());

            // Decrement in_degree for everything this file imports.
            let mut deps: Vec<String> = imports_from
                .get(&file)
                .cloned()
                .unwrap_or_default();
            deps.sort();
            for dep in deps {
                let deg = in_degree.entry(dep.clone()).or_insert(1);
                if *deg > 0 {
                    *deg -= 1;
                }
                if *deg == 0 && !visited.contains(&dep) {
                    queue.push_back(dep);
                }
            }
        }

        // Append files not reached due to cycles.
        let mut remaining: Vec<String> = all_files
            .iter()
            .filter(|f| !visited.contains(*f))
            .cloned()
            .collect();
        remaining.sort();
        ordered.extend(remaining);

        // ------------------------------------------------------------------
        // 6. Build TourStop list, capped at limit.
        // ------------------------------------------------------------------
        let stops: Vec<TourStop> = ordered
            .into_iter()
            .take(limit)
            .enumerate()
            .map(|(idx, file)| {
                let order = idx + 1;
                let language = path_to_meta
                    .get(&file)
                    .map(|(_, lang)| lang.clone())
                    .unwrap_or_default();
                let symbols = file_symbols.get(&file).cloned().unwrap_or_default();
                let imp_from = imports_from.get(&file).cloned().unwrap_or_default();
                let imp_by = imported_by.get(&file).cloned().unwrap_or_default();

                let reason = if imp_by.is_empty() && imp_from.is_empty() {
                    "Standalone file - no import relationships recorded".to_string()
                } else if imp_by.is_empty() {
                    "Entry point - no other files import this".to_string()
                } else if imp_from.is_empty() {
                    format!(
                        "Core module - imported by {} file{}",
                        imp_by.len(),
                        if imp_by.len() == 1 { "" } else { "s" }
                    )
                } else {
                    let dep_names: Vec<&str> = imp_from
                        .iter()
                        .take(3)
                        .map(|s| s.rfind('/').map(|i| &s[i + 1..]).unwrap_or(s.as_str()))
                        .collect();
                    format!("Depends on: {} (read those first)", dep_names.join(", "))
                };

                TourStop {
                    order,
                    file_path: file,
                    language,
                    symbols,
                    imports_from: imp_from,
                    imported_by: imp_by,
                    reason,
                }
            })
            .collect();

        Ok(stops)
    }

    /// Remove all symbols and relationships for a given file (for incremental re-index).
    pub async fn remove_file(&self, file_path: &str, project: &str) -> Result<u64> {
        let result = sqlx::query(&format!(
            "DELETE FROM {schema}.symbols WHERE file_path = $1 AND project = $2",
            schema = self.schema,
        ))
        .bind(file_path)
        .bind(project)
        .execute(&self.pool)
        .await?;

        Ok(result.rows_affected())
    }

    /// Remove all symbols and relationships for a given project before a full re-index.
    pub async fn remove_project(&self, project: &str) -> Result<u64> {
        let result = sqlx::query(&format!(
            "DELETE FROM {schema}.symbols WHERE project = $1",
            schema = self.schema,
        ))
        .bind(project)
        .execute(&self.pool)
        .await?;

        Ok(result.rows_affected())
    }
}

#[derive(sqlx::FromRow)]
struct SymbolRow {
    id: Uuid,
    name: String,
    symbol_type: String,
    file_path: String,
    start_line: Option<i32>,
    end_line: Option<i32>,
    language: String,
    project: String,
    signature: Option<String>,
    file_mtime: chrono::DateTime<chrono::Utc>,
    layer: Option<String>,
    parent_symbol_id: Option<Uuid>,
    moniker: Option<String>,
}

impl SymbolRow {
    fn into_symbol(self) -> Symbol {
        Symbol {
            id: self.id,
            name: self.name,
            symbol_type: self.symbol_type.parse().unwrap_or(SymbolType::Function),
            file_path: self.file_path,
            start_line: self.start_line,
            end_line: self.end_line,
            language: self.language,
            project: self.project,
            signature: self.signature,
            file_mtime: self.file_mtime,
            layer: self.layer,
            parent_symbol_id: self.parent_symbol_id,
            moniker: self.moniker,
        }
    }
}

#[derive(sqlx::FromRow)]
struct ImpactRow {
    id: Uuid,
    name: String,
    symbol_type: String,
    file_path: String,
    start_line: Option<i32>,
    end_line: Option<i32>,
    language: String,
    project: String,
    signature: Option<String>,
    file_mtime: chrono::DateTime<chrono::Utc>,
    layer: Option<String>,
    parent_symbol_id: Option<Uuid>,
    moniker: Option<String>,
    depth: i32,
    path: Vec<Uuid>,
    rel_type: String,
    confidence: f32,
}

impl ImpactRow {
    fn into_impact_result(self) -> ImpactResult {
        ImpactResult {
            symbol: Symbol {
                id: self.id,
                name: self.name,
                symbol_type: self.symbol_type.parse().unwrap_or(SymbolType::Function),
                file_path: self.file_path,
                start_line: self.start_line,
                end_line: self.end_line,
                language: self.language,
                project: self.project,
                signature: self.signature,
                file_mtime: self.file_mtime,
                layer: self.layer,
                parent_symbol_id: self.parent_symbol_id,
                moniker: self.moniker,
            },
            depth: self.depth,
            path: self.path,
            relationship: self.rel_type.parse().unwrap_or(RelationType::Calls),
            confidence: self.confidence,
        }
    }
}