coraline 0.8.0

Coraline: semantic code knowledge graph for faster AI-assisted development.
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
#![forbid(unsafe_code)]

//! File system tools for reading files and listing directory contents.

use std::path::PathBuf;
#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
use std::sync::Mutex;
#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
use std::time::{Duration, Instant};

use serde_json::{Value, json};

use crate::db;

use super::{Tool, ToolError, ToolResult};

/// Tool for reading file contents with optional line range
pub struct ReadFileTool {
    project_root: PathBuf,
}

impl ReadFileTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for ReadFileTool {
    fn name(&self) -> &'static str {
        "coraline_read_file"
    }

    fn description(&self) -> &'static str {
        "Read the contents of a file, optionally limited to a line range."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to the file (relative to project root or absolute)"
                },
                "start_line": {
                    "type": "number",
                    "description": "First line to read (1-indexed, inclusive). Defaults to 1."
                },
                "limit": {
                    "type": "number",
                    "description": "Maximum number of lines to return. Defaults to 200."
                }
            },
            "required": ["path"]
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let raw_path = params
            .get("path")
            .and_then(Value::as_str)
            .ok_or_else(|| ToolError::invalid_params("path must be a string"))?;

        let path = resolve_path(&self.project_root, raw_path);

        let start_line = params
            .get("start_line")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok())
            .unwrap_or(1)
            .max(1);

        let limit = params
            .get("limit")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok())
            .unwrap_or(200);

        let text = std::fs::read_to_string(&path).map_err(|e| {
            ToolError::not_found(format!("Cannot read file {}: {e}", path.display()))
        })?;

        let all_lines: Vec<&str> = text.lines().collect();
        let total_lines = all_lines.len();

        let start_idx = start_line.saturating_sub(1).min(total_lines);
        let end_idx = (start_idx + limit).min(total_lines);

        let content = all_lines
            .get(start_idx..end_idx)
            .unwrap_or_default()
            .join("\n");

        Ok(json!({
            "path": path,
            "content": content,
            "start_line": start_line,
            "end_line": start_idx + (end_idx - start_idx),
            "total_lines": total_lines,
            "truncated": end_idx < total_lines,
        }))
    }
}

/// Tool for listing directory contents
pub struct ListDirTool {
    project_root: PathBuf,
}

impl ListDirTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for ListDirTool {
    fn name(&self) -> &'static str {
        "coraline_list_dir"
    }

    fn description(&self) -> &'static str {
        "List the contents of a directory within the project."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Directory path (relative to project root or absolute). Defaults to project root."
                }
            }
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let raw_path = params.get("path").and_then(Value::as_str).unwrap_or(".");

        let dir = resolve_path(&self.project_root, raw_path);

        let entries = std::fs::read_dir(&dir).map_err(|e| {
            ToolError::not_found(format!("Cannot read directory {}: {e}", dir.display()))
        })?;

        let mut items = Vec::new();
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().to_string();
            // Skip hidden files/dirs and common noise dirs
            if name.starts_with('.') {
                continue;
            }
            let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
            let display = if is_dir {
                format!("{name}/")
            } else {
                name.clone()
            };
            items.push(json!({
                "name": display,
                "is_dir": is_dir,
            }));
        }

        items.sort_by(|a, b| {
            let a_dir = a["is_dir"].as_bool().unwrap_or(false);
            let b_dir = b["is_dir"].as_bool().unwrap_or(false);
            // Directories first, then alphabetical
            b_dir
                .cmp(&a_dir)
                .then_with(|| a["name"].as_str().cmp(&b["name"].as_str()))
        });

        Ok(json!({
            "path": dir,
            "entries": items,
            "count": items.len(),
        }))
    }
}

/// Tool for getting all indexed nodes in a file
pub struct GetFileNodesTool {
    project_root: PathBuf,
}

impl GetFileNodesTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for GetFileNodesTool {
    fn name(&self) -> &'static str {
        "coraline_get_file_nodes"
    }

    fn description(&self) -> &'static str {
        "Get all indexed code symbols (nodes) in a specific file, ordered by line number."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "file_path": {
                    "type": "string",
                    "description": "Path to the file (relative to project root or absolute)"
                },
                "kind": {
                    "type": "string",
                    "description": "Optional node kind filter",
                    "enum": ["function", "method", "class", "struct", "interface", "trait", "module"]
                }
            },
            "required": ["file_path"]
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let raw_path = params
            .get("file_path")
            .and_then(Value::as_str)
            .ok_or_else(|| ToolError::invalid_params("file_path must be a string"))?;

        let kind = params
            .get("kind")
            .and_then(Value::as_str)
            .and_then(str_to_node_kind);

        let abs_path = resolve_path(&self.project_root, raw_path)
            .to_string_lossy()
            .to_string();

        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        // Try absolute path first, fall back to raw_path (in case stored relative)
        let nodes = {
            let mut n = db::get_nodes_by_file(&conn, &abs_path, kind)
                .map_err(|e| ToolError::internal_error(format!("Failed to query nodes: {e}")))?;
            if n.is_empty() {
                n = db::get_nodes_by_file(&conn, raw_path, kind).map_err(|e| {
                    ToolError::internal_error(format!("Failed to query nodes: {e}"))
                })?;
            }
            n
        };

        let symbols: Vec<Value> = nodes
            .iter()
            .map(|n| {
                json!({
                    "id": n.id,
                    "kind": n.kind,
                    "name": n.name,
                    "qualified_name": n.qualified_name,
                    "start_line": n.start_line,
                    "end_line": n.end_line,
                    "signature": n.signature,
                    "is_exported": n.is_exported,
                })
            })
            .collect();

        Ok(json!({
            "file_path": abs_path,
            "nodes": symbols,
            "count": symbols.len(),
        }))
    }
}

/// Tool for finding files by name or glob pattern
pub struct FindFileTool {
    project_root: PathBuf,
}

impl FindFileTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for FindFileTool {
    fn name(&self) -> &'static str {
        "coraline_find_file"
    }

    fn description(&self) -> &'static str {
        "Search for files by name substring or glob pattern across the project. \
         Returns matching file paths relative to the project root."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "File name substring or glob pattern (e.g. '*.rs', 'mod.rs', 'graph')"
                },
                "limit": {
                    "type": "number",
                    "description": "Maximum number of results to return",
                    "default": 50
                }
            },
            "required": ["pattern"]
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let pattern = params
            .get("pattern")
            .and_then(Value::as_str)
            .ok_or_else(|| ToolError::invalid_params("pattern must be a string"))?;

        let limit = params
            .get("limit")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok())
            .unwrap_or(50);

        let is_glob = pattern.contains('*') || pattern.contains('?') || pattern.contains('[');

        let mut matches = Vec::new();
        find_files_recursive(
            &self.project_root,
            &self.project_root,
            pattern,
            is_glob,
            limit,
            &mut matches,
        );

        Ok(json!({
            "pattern": pattern,
            "matches": matches,
            "count": matches.len(),
            "truncated": matches.len() >= limit,
        }))
    }
}

fn find_files_recursive(
    root: &std::path::Path,
    dir: &std::path::Path,
    pattern: &str,
    is_glob: bool,
    limit: usize,
    results: &mut Vec<String>,
) {
    if results.len() >= limit {
        return;
    }

    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };

    for entry in entries.flatten() {
        if results.len() >= limit {
            return;
        }

        let name = entry.file_name().to_string_lossy().to_string();

        // Skip hidden dirs, .git, node_modules, target, .coraline
        if name.starts_with('.')
            || name == "node_modules"
            || name == "target"
            || name == ".coraline"
        {
            continue;
        }

        let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);

        if !is_dir {
            let matched = if is_glob {
                glob_match(pattern, &name)
            } else {
                name.contains(pattern)
            };

            if matched {
                let rel = entry.path().strip_prefix(root).map_or_else(
                    |_| entry.path().to_string_lossy().to_string(),
                    |p| p.to_string_lossy().to_string(),
                );
                results.push(rel);
            }
        }

        if is_dir {
            find_files_recursive(root, &entry.path(), pattern, is_glob, limit, results);
        }
    }
}

/// Simple glob matching supporting `*`, `?`, and character classes `[abc]`.
fn glob_match(pattern: &str, name: &str) -> bool {
    let pattern_chars: Vec<char> = pattern.chars().collect();
    let name_chars: Vec<char> = name.chars().collect();
    glob_match_inner(&pattern_chars, &name_chars)
}

fn glob_match_inner(pattern: &[char], name: &[char]) -> bool {
    match (pattern.first(), name.first()) {
        (None, None) => true,
        (Some('*'), _) => {
            // Try matching zero chars or one char from name
            glob_match_inner(pattern.get(1..).unwrap_or_default(), name)
                || (!name.is_empty()
                    && glob_match_inner(pattern, name.get(1..).unwrap_or_default()))
        }
        (Some('?'), Some(_)) => glob_match_inner(
            pattern.get(1..).unwrap_or_default(),
            name.get(1..).unwrap_or_default(),
        ),
        (Some('['), _) => {
            // Find closing bracket
            pattern.iter().position(|&c| c == ']').map_or_else(
                || {
                    // Malformed pattern, treat [ as literal
                    pattern.first() == name.first()
                        && glob_match_inner(
                            pattern.get(1..).unwrap_or_default(),
                            name.get(1..).unwrap_or_default(),
                        )
                },
                |end| {
                    let class = pattern.get(1..end).unwrap_or_default();
                    let matches_class = name.first().is_some_and(|nc| class.contains(nc));
                    if matches_class {
                        glob_match_inner(
                            pattern.get(end + 1..).unwrap_or_default(),
                            name.get(1..).unwrap_or_default(),
                        )
                    } else {
                        false
                    }
                },
            )
        }
        (Some(pc), Some(nc)) if *pc == *nc => glob_match_inner(
            pattern.get(1..).unwrap_or_default(),
            name.get(1..).unwrap_or_default(),
        ),
        _ => false,
    }
}

/// Tool for project index status and statistics
pub struct StatusTool {
    project_root: PathBuf,
}

impl StatusTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for StatusTool {
    fn name(&self) -> &'static str {
        "coraline_status"
    }

    fn description(&self) -> &'static str {
        "Get the current index status and statistics for the project."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {}
        })
    }

    fn execute(&self, _params: Value) -> ToolResult {
        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        let stats = db::get_db_stats(&conn)
            .map_err(|e| ToolError::internal_error(format!("Failed to get stats: {e}")))?;

        let db_path = db::database_path(&self.project_root);
        let db_size = std::fs::metadata(&db_path).map(|m| m.len()).unwrap_or(0);

        Ok(json!({
            "project_root": self.project_root,
            "database": db_path,
            "database_size_bytes": db_size,
            "stats": {
                "nodes": stats.node_count,
                "edges": stats.edge_count,
                "files": stats.file_count,
                "unresolved_references": stats.unresolved_count,
            }
        }))
    }
}

// ── Helpers ──────────────────────────────────────────────────────────────────

fn resolve_path(project_root: &std::path::Path, raw: &str) -> PathBuf {
    let p = std::path::Path::new(raw);
    if p.is_absolute() {
        p.to_path_buf()
    } else {
        project_root.join(raw)
    }
}

fn str_to_node_kind(s: &str) -> Option<crate::types::NodeKind> {
    use crate::types::NodeKind;
    match s {
        "function" => Some(NodeKind::Function),
        "method" => Some(NodeKind::Method),
        "class" => Some(NodeKind::Class),
        "struct" => Some(NodeKind::Struct),
        "interface" => Some(NodeKind::Interface),
        "trait" => Some(NodeKind::Trait),
        "module" => Some(NodeKind::Module),
        _ => None,
    }
}

/// Tool for reading the current project configuration
pub struct GetConfigTool {
    project_root: PathBuf,
}

impl GetConfigTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for GetConfigTool {
    fn name(&self) -> &'static str {
        "coraline_get_config"
    }

    fn description(&self) -> &'static str {
        "Read the current Coraline project configuration (config.toml). Returns all sections with their effective values."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "section": {
                    "type": "string",
                    "description": "Optional: return only this section (indexing, context, sync, vectors)",
                    "enum": ["indexing", "context", "sync", "vectors"]
                }
            }
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let cfg = crate::config::load_toml_config(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to load config: {e}")))?;

        let full = serde_json::to_value(&cfg)
            .map_err(|e| ToolError::internal_error(format!("Serialization failed: {e}")))?;

        let result = if let Some(section) = params.get("section").and_then(Value::as_str) {
            full.get(section).cloned().unwrap_or(Value::Null)
        } else {
            full
        };

        let config_path = crate::config::toml_config_path(&self.project_root);
        Ok(json!({
            "config_path": config_path,
            "config_exists": config_path.exists(),
            "config": result,
        }))
    }
}

/// Tool for updating a single config value
pub struct UpdateConfigTool {
    project_root: PathBuf,
}

impl UpdateConfigTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for UpdateConfigTool {
    fn name(&self) -> &'static str {
        "coraline_update_config"
    }

    fn description(&self) -> &'static str {
        "Update a single value in the Coraline config.toml. Specify the section and key to update."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "section": {
                    "type": "string",
                    "description": "Config section to update",
                    "enum": ["indexing", "context", "sync", "vectors"]
                },
                "key": {
                    "type": "string",
                    "description": "The config key within the section"
                },
                "value": {
                    "description": "New value (must match the expected type for that key)"
                }
            },
            "required": ["section", "key", "value"]
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let section = params
            .get("section")
            .and_then(Value::as_str)
            .ok_or_else(|| ToolError::invalid_params("section must be a string"))?;

        let key = params
            .get("key")
            .and_then(Value::as_str)
            .ok_or_else(|| ToolError::invalid_params("key must be a string"))?;

        let new_value = params
            .get("value")
            .ok_or_else(|| ToolError::invalid_params("value is required"))?
            .clone();

        // Load current config, mutate it as JSON, write back
        let cfg = crate::config::load_toml_config(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to load config: {e}")))?;

        let mut cfg_json = serde_json::to_value(&cfg)
            .map_err(|e| ToolError::internal_error(format!("Serialization failed: {e}")))?;

        let section_obj = cfg_json
            .get_mut(section)
            .ok_or_else(|| ToolError::invalid_params(format!("Unknown section: {section}")))?;

        let obj = section_obj
            .as_object_mut()
            .ok_or_else(|| ToolError::internal_error("Section is not an object"))?;

        if !obj.contains_key(key) {
            return Err(ToolError::invalid_params(format!(
                "Unknown key '{key}' in section '{section}'"
            )));
        }

        obj.insert(key.to_string(), new_value.clone());

        let updated: crate::config::CoralineConfig =
            serde_json::from_value(cfg_json).map_err(|e| {
                ToolError::invalid_params(format!("Invalid value for {section}.{key}: {e}"))
            })?;

        crate::config::save_toml_config(&self.project_root, &updated)
            .map_err(|e| ToolError::internal_error(format!("Failed to save config: {e}")))?;

        Ok(json!({
            "updated": true,
            "section": section,
            "key": key,
            "new_value": new_value,
        }))
    }
}

/// Tool for triggering an incremental index sync.
pub struct SyncTool {
    project_root: PathBuf,
}

impl SyncTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for SyncTool {
    fn name(&self) -> &'static str {
        "coraline_sync"
    }

    fn description(&self) -> &'static str {
        "Trigger an incremental sync of the Coraline index. \
         Detects files added, modified, or removed since the last index run \
         and updates only what changed. Run this after editing source files \
         so the graph reflects your latest changes."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {}
        })
    }

    fn execute(&self, _params: Value) -> ToolResult {
        let mut cfg = crate::config::load_config(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to load config: {e}")))?;
        if let Ok(toml_cfg) = crate::config::load_toml_config(&self.project_root) {
            crate::config::apply_toml_to_code_graph(&mut cfg, &toml_cfg);
        }

        let result = crate::extraction::sync(&self.project_root, &cfg, None)
            .map_err(|e| ToolError::internal_error(format!("Sync failed: {e}")))?;

        Ok(json!({
            "files_checked":  result.files_checked,
            "files_added":    result.files_added,
            "files_modified": result.files_modified,
            "files_removed":  result.files_removed,
            "nodes_updated":  result.nodes_updated,
            "duration_ms":    result.duration_ms,
        }))
    }
}

/// Tool for semantic (vector) search over indexed nodes.
#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
pub struct SemanticSearchTool {
    project_root: PathBuf,
    freshness_state: Mutex<SemanticFreshnessState>,
}

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
impl SemanticSearchTool {
    pub fn new(project_root: PathBuf) -> Self {
        Self {
            project_root,
            freshness_state: Mutex::new(SemanticFreshnessState::default()),
        }
    }

    fn maybe_refresh_index_and_embeddings(
        &self,
        vm: Option<&mut crate::vectors::VectorManager>,
    ) -> Result<FreshnessUpdate, ToolError> {
        let now = Instant::now();
        let should_check = {
            let state = self
                .freshness_state
                .lock()
                .map_err(|_| ToolError::internal_error("freshness state lock poisoned"))?;
            !matches!(state.last_checked_at, Some(last) if now.saturating_duration_since(last)
                        < Duration::from_secs(FRESHNESS_CHECK_INTERVAL_SECS))
        };

        if !should_check {
            return Ok(FreshnessUpdate::default());
        }

        let mut update = FreshnessUpdate {
            checked: true,
            ..FreshnessUpdate::default()
        };

        let mut cfg = crate::config::load_config(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to load config: {e}")))?;
        if let Ok(toml_cfg) = crate::config::load_toml_config(&self.project_root) {
            crate::config::apply_toml_to_code_graph(&mut cfg, &toml_cfg);
        }

        let sync_status = crate::extraction::needs_sync(&self.project_root, &cfg)
            .map_err(|e| ToolError::internal_error(format!("Sync-state check failed: {e}")))?;

        update.stale_files_added = sync_status.files_added;
        update.stale_files_modified = sync_status.files_modified;
        update.stale_files_removed = sync_status.files_removed;

        if sync_status.is_stale() {
            let result = crate::extraction::sync(&self.project_root, &cfg, None)
                .map_err(|e| ToolError::internal_error(format!("Auto-sync failed: {e}")))?;
            update.synced = true;
            update.files_added = result.files_added;
            update.files_modified = result.files_modified;
            update.files_removed = result.files_removed;
        }

        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("DB error: {e}")))?;

        let stale_count = stale_embedding_count(&conn)
            .map_err(|e| ToolError::internal_error(format!("Embedding-state check failed: {e}")))?;

        if stale_count > 0 {
            let refreshed = if let Some(vm) = vm {
                refresh_stale_embeddings(&conn, vm).map_err(|e| {
                    ToolError::internal_error(format!("Embedding refresh failed: {e}"))
                })?
            } else {
                let mut vm = crate::vectors::VectorManager::from_project(&self.project_root).map_err(|e| {
                    ToolError::internal_error(format!(
                        "Could not load embedding model: {e}. Download the model and run 'coraline embed' first."
                    ))
                })?;
                refresh_stale_embeddings(&conn, &mut vm).map_err(|e| {
                    ToolError::internal_error(format!("Embedding refresh failed: {e}"))
                })?
            };

            update.embeddings_refreshed = true;
            update.embeddings_refreshed_count = refreshed;
        }

        {
            let mut state = self
                .freshness_state
                .lock()
                .map_err(|_| ToolError::internal_error("freshness state lock poisoned"))?;
            state.last_checked_at = Some(now);
        }

        Ok(update)
    }
}

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
const FRESHNESS_CHECK_INTERVAL_SECS: u64 = 30;

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
#[derive(Default)]
struct SemanticFreshnessState {
    last_checked_at: Option<Instant>,
}

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
#[derive(Default)]
struct FreshnessUpdate {
    checked: bool,
    stale_files_added: usize,
    stale_files_modified: usize,
    stale_files_removed: usize,
    synced: bool,
    files_added: usize,
    files_modified: usize,
    files_removed: usize,
    embeddings_refreshed: bool,
    embeddings_refreshed_count: usize,
}

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
fn stale_embedding_count(conn: &rusqlite::Connection) -> std::io::Result<usize> {
    let count = conn
        .query_row(
            "SELECT COUNT(*)
               FROM nodes n
          LEFT JOIN vectors v ON v.node_id = n.id
              WHERE v.created_at IS NULL OR n.updated_at > v.created_at",
            [],
            |row| row.get::<_, i64>(0),
        )
        .map_err(std::io::Error::other)?;

    usize::try_from(count).map_err(std::io::Error::other)
}

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
type StaleNodeRow = (String, String, String, Option<String>, Option<String>);

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
fn refresh_stale_embeddings(
    conn: &rusqlite::Connection,
    vm: &mut crate::vectors::VectorManager,
) -> std::io::Result<usize> {
    // Collect stale nodes into memory first so the statement borrow is released
    // before we open a transaction, allowing all stores to commit atomically.
    let stale_nodes: Vec<StaleNodeRow> = {
        let mut stmt = conn
            .prepare(
                "SELECT n.id, n.name, n.qualified_name, n.docstring, n.signature
                   FROM nodes n
              LEFT JOIN vectors v ON v.node_id = n.id
                  WHERE v.created_at IS NULL OR n.updated_at > v.created_at",
            )
            .map_err(std::io::Error::other)?;

        stmt.query_map([], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, Option<String>>(3)?,
                row.get::<_, Option<String>>(4)?,
            ))
        })
        .map_err(std::io::Error::other)?
        .collect::<Result<_, _>>()
        .map_err(std::io::Error::other)?
    }; // stmt dropped here — borrow on conn released

    let tx = conn
        .unchecked_transaction()
        .map_err(std::io::Error::other)?;

    let mut refreshed = 0usize;
    for (id, name, qualified_name, docstring, signature) in stale_nodes {
        let text = crate::vectors::node_embed_text(
            &name,
            &qualified_name,
            docstring.as_deref(),
            signature.as_deref(),
        );

        let embedding = vm.embed(&text)?;
        crate::vectors::store_embedding(&tx, &id, &embedding, vm.model_name())?;
        refreshed += 1;
    }

    tx.commit().map_err(std::io::Error::other)?;
    Ok(refreshed)
}

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
impl Tool for SemanticSearchTool {
    fn name(&self) -> &'static str {
        "coraline_semantic_search"
    }

    fn description(&self) -> &'static str {
        "Search indexed code nodes using natural-language vector similarity. \
         Requires embeddings to have been generated with `coraline embed`."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Natural-language description of what you are looking for"
                },
                "limit": {
                    "type": "number",
                    "description": "Maximum number of results (default 10)"
                },
                "min_similarity": {
                    "type": "number",
                    "description": "Minimum cosine similarity threshold 0–1 (default 0.3)"
                }
            },
            "required": ["query"]
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let query = params
            .get("query")
            .and_then(Value::as_str)
            .ok_or_else(|| ToolError::invalid_params("query must be a string"))?;

        let limit = params
            .get("limit")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok())
            .unwrap_or(10);
        #[allow(clippy::cast_possible_truncation)] // f64→f32: no lossless conversion in std
        let min_similarity = params
            .get("min_similarity")
            .and_then(Value::as_f64)
            .unwrap_or(0.3) as f32;

        let mut vm =
            crate::vectors::VectorManager::from_project(&self.project_root).map_err(|e| {
                ToolError::internal_error(format!(
                    "Could not load embedding model: {e}. \
                         Download the model and run 'coraline embed' first."
                ))
            })?;

        let freshness = self.maybe_refresh_index_and_embeddings(Some(&mut vm))?;

        let embedding = vm
            .embed(query)
            .map_err(|e| ToolError::internal_error(format!("Embedding failed: {e}")))?;

        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("DB error: {e}")))?;

        let results = crate::vectors::search_similar(&conn, &embedding, limit, min_similarity)
            .map_err(|e| ToolError::internal_error(format!("Search failed: {e}")))?;

        let items: Vec<Value> = results
            .into_iter()
            .map(|r| {
                json!({
                    "id":           r.node.id,
                    "name":         r.node.name,
                    "qualified_name": r.node.qualified_name,
                    "kind":         r.node.kind,
                    "file_path":    r.node.file_path,
                    "start_line":   r.node.start_line,
                    "docstring":    r.node.docstring,
                    "signature":    r.node.signature,
                    "score":        r.score,
                })
            })
            .collect();

        Ok(json!({
            "query": query,
            "freshness": {
                "checked": freshness.checked,
                "stale_files_added": freshness.stale_files_added,
                "stale_files_modified": freshness.stale_files_modified,
                "stale_files_removed": freshness.stale_files_removed,
                "synced": freshness.synced,
                "files_added": freshness.files_added,
                "files_modified": freshness.files_modified,
                "files_removed": freshness.files_removed,
                "embeddings_refreshed": freshness.embeddings_refreshed,
                "embeddings_refreshed_count": freshness.embeddings_refreshed_count,
                "check_interval_seconds": FRESHNESS_CHECK_INTERVAL_SECS,
            },
            "results": items
        }))
    }
}