sqry-db 10.0.1

Salsa-style incremental computation engine for sqry semantic code search
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
//! Semantic diff implementation for [`super::ComparativeQueryDb`].
//!
//! Ported from `sqry-mcp::execution::diff_comparator` (which in turn adapted
//! `sqry-core::graph::diff::GraphComparator`) as part of Phase 3C / DB20. The
//! MCP copy diverged from sqry-core's in three ways, all of which are
//! preserved here so the MCP wire format is byte-for-byte stable:
//!
//! 1. Qualified names are formatted through
//!    [`sqry_core::graph::unified::resolution::display_graph_qualified_name`]
//!    when a known language is associated with the source file. This lets
//!    per-language plugins override the stored qualified name (e.g. Swift
//!    inserting `Type.` for `is_static` members).
//! 2. The `is_static` flag is threaded through the comparator so the above
//!    display logic receives the same information the graph node stored.
//! 3. Line numbers / columns / paths are reported as plain fields on
//!    [`NodeLocation`]; the MCP handler wraps them in its transport DTO
//!    (`NodeRefData` + `fileUri`) so the wire format is owned by MCP.
//!
//! Rename detection heuristics (Levenshtein over signatures weighted 70%,
//! location proximity weighted 30%, 90% confidence threshold) match the
//! previous MCP `GraphComparator` bit-for-bit.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use sqry_core::graph::Language;
use sqry_core::graph::unified::concurrent::GraphSnapshot;
use sqry_core::graph::unified::node::kind::NodeKind;
use sqry_core::graph::unified::resolution::display_graph_qualified_name;

// ============================================================================
// Rename heuristic constants (frozen; match the pre-DB20 MCP comparator)
// ============================================================================

const SIGNATURE_WEIGHT: f64 = 0.7;
const LOCATION_WEIGHT: f64 = 0.3;
const SIGNATURE_MIN_SCORE: f64 = 0.7;
const RENAME_CONFIDENCE_THRESHOLD: f64 = 0.9;
const SAME_FILE_LINE_WINDOW: i32 = 50;
const SAME_FILE_LINE_NORMALIZER: f64 = 100.0;
const SAME_FILE_MAX_PENALTY: f64 = 0.5;
const SAME_FILE_FAR_SCORE: f64 = 0.3;
const CROSS_FILE_LOCATION_SCORE: f64 = 0.7;

// ============================================================================
// Public output types
// ============================================================================

/// Kind of change detected between the two snapshots.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ChangeType {
    /// Node is present in the new snapshot but not the old.
    Added,
    /// Node is present in the old snapshot but not the new.
    Removed,
    /// Node exists on both sides but its body / location changed while the
    /// signature stayed identical.
    Modified,
    /// Node was matched heuristically as a renamed version of a node that
    /// disappeared (>= 90% confidence via signature + location scoring).
    Renamed,
    /// Node exists on both sides and its signature changed.
    SignatureChanged,
    /// Node exists unchanged on both sides. Callers opt into emitting these
    /// via their own filter logic — [`compute_diff`] never emits this variant
    /// directly.
    Unchanged,
}

impl ChangeType {
    /// Returns the stable wire-format string for this change type. The
    /// mapping matches the pre-DB20 MCP and CLI outputs exactly.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            ChangeType::Added => "added",
            ChangeType::Removed => "removed",
            ChangeType::Modified => "modified",
            ChangeType::Renamed => "renamed",
            ChangeType::SignatureChanged => "signature_changed",
            ChangeType::Unchanged => "unchanged",
        }
    }
}

/// Location of a single changed node, reported in sqry-db-owned terms.
///
/// `file_path` is either absolute (when the caller supplied worktree roots
/// via [`DiffOptions`]) or workspace-relative (when no worktree root was
/// supplied — tests, CLI callers). Lines are 1-indexed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NodeLocation {
    /// File path; prefixed with the matching worktree root if the caller
    /// supplied one, otherwise the path stored in the graph.
    pub file_path: PathBuf,
    /// Language id reported by the graph's file registry (e.g. `"rust"`,
    /// `"python"`). `"unknown"` if the registry had no mapping.
    pub language: String,
    /// Start line (1-indexed, as stored in the graph node arena).
    pub start_line: u32,
    /// End line (1-indexed).
    pub end_line: u32,
    /// Start column (0-indexed).
    pub start_column: u32,
    /// End column (0-indexed).
    pub end_column: u32,
}

/// A single change record.
#[derive(Debug, Clone)]
pub struct NodeChange {
    /// Short symbol name (e.g. `foo`).
    pub symbol_name: String,
    /// Display-form qualified name, run through
    /// [`display_graph_qualified_name`] when the language is known.
    pub qualified_name: String,
    /// Lowercase node kind string (`"function"`, `"method"`, …). Matches the
    /// pre-DB20 MCP string taxonomy used by `filters.symbol_kinds`.
    pub kind: String,
    /// What kind of change was detected.
    pub change_type: ChangeType,
    /// Location in the "old" snapshot (populated for `Removed`, `Modified`,
    /// `Renamed`, `SignatureChanged`).
    pub base_location: Option<NodeLocation>,
    /// Location in the "new" snapshot (populated for `Added`, `Modified`,
    /// `Renamed`, `SignatureChanged`).
    pub target_location: Option<NodeLocation>,
    /// Signature string in the "old" snapshot, if any.
    pub signature_before: Option<String>,
    /// Signature string in the "new" snapshot, if any.
    pub signature_after: Option<String>,
}

/// Summary counts for a diff.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DiffSummary {
    /// Count of [`ChangeType::Added`] records.
    pub added: u64,
    /// Count of [`ChangeType::Removed`] records.
    pub removed: u64,
    /// Count of [`ChangeType::Modified`] records.
    pub modified: u64,
    /// Count of [`ChangeType::Renamed`] records.
    pub renamed: u64,
    /// Count of [`ChangeType::SignatureChanged`] records.
    pub signature_changed: u64,
    /// Count of [`ChangeType::Unchanged`] records (set by callers that
    /// post-process the diff to include unchanged nodes).
    pub unchanged: u64,
}

impl DiffSummary {
    /// Recomputes a summary from an existing slice of changes. Useful for
    /// callers that filter `compute_diff`'s output before rendering.
    #[must_use]
    pub fn from_changes(changes: &[NodeChange]) -> Self {
        let mut summary = Self::default();
        for change in changes {
            match change.change_type {
                ChangeType::Added => summary.added += 1,
                ChangeType::Removed => summary.removed += 1,
                ChangeType::Modified => summary.modified += 1,
                ChangeType::Renamed => summary.renamed += 1,
                ChangeType::SignatureChanged => summary.signature_changed += 1,
                ChangeType::Unchanged => summary.unchanged += 1,
            }
        }
        summary
    }
}

/// Output of [`compute_diff`] / [`super::ComparativeQueryDb::diff`].
#[derive(Debug, Clone, Default)]
pub struct DiffOutput {
    /// All detected changes, in the order the underlying HashMap iteration
    /// produces (caller-visible ordering should sort/paginate as needed).
    pub changes: Vec<NodeChange>,
    /// Pre-filter summary (matches `changes` bucket counts before any
    /// caller-side filter is applied).
    pub summary: DiffSummary,
}

/// Options controlling the diff computation.
///
/// All fields default to empty; callers that need worktree translation
/// populate `old_worktree_path` / `new_worktree_path` with the absolute root
/// of each git worktree. See `sqry_mcp::execution::git_worktree::WorktreeManager`
/// for an example producer.
#[derive(Debug, Clone, Default)]
pub struct DiffOptions {
    /// Absolute path of the worktree backing the "old" snapshot. When
    /// non-empty, every resolved per-node file path is joined onto this
    /// root so downstream callers can turn it into a `file://` URI.
    pub old_worktree_path: PathBuf,
    /// Absolute path of the worktree backing the "new" snapshot.
    pub new_worktree_path: PathBuf,
}

// ============================================================================
// Implementation
// ============================================================================

/// Internal snapshot of a single node used during comparison.
#[derive(Clone)]
struct NodeSnap {
    name: String,
    qualified_name: String,
    kind: NodeKind,
    kind_str: String,
    is_static: bool,
    signature: Option<String>,
    file_path: PathBuf,
    language: String,
    start_line: u32,
    end_line: u32,
    start_column: u32,
    end_column: u32,
}

impl NodeSnap {
    fn display_qualified_name(&self) -> String {
        Language::from_id(&self.language).map_or_else(
            || self.qualified_name.clone(),
            |language| {
                display_graph_qualified_name(
                    language,
                    &self.qualified_name,
                    self.kind,
                    self.is_static,
                )
            },
        )
    }

    fn into_location(self) -> NodeLocation {
        NodeLocation {
            file_path: self.file_path,
            language: self.language,
            start_line: self.start_line,
            end_line: self.end_line,
            start_column: self.start_column,
            end_column: self.end_column,
        }
    }

    fn to_location(&self) -> NodeLocation {
        NodeLocation {
            file_path: self.file_path.clone(),
            language: self.language.clone(),
            start_line: self.start_line,
            end_line: self.end_line,
            start_column: self.start_column,
            end_column: self.end_column,
        }
    }
}

/// Entry point: computes the semantic diff between `old` and `new`.
///
/// The algorithm is the same one the pre-DB20 MCP `GraphComparator` used:
///
/// 1. Build two `qualified_name -> NodeSnap` maps, skipping nodes without
///    qualified names (call sites, imports, etc.).
/// 2. Walk the "new" map: nodes absent from "old" are added candidates;
///    nodes present on both sides are checked for signature / body changes
///    (producing `SignatureChanged` or `Modified`).
/// 3. Walk the "old" map: nodes absent from "new" are removed candidates.
/// 4. Run heuristic rename detection between the remaining removed and
///    added sets (same kind, signature similarity >= 0.7, location scoring,
///    confidence threshold 0.9). Matched pairs emit `Renamed` records and
///    are removed from the added/removed pools.
/// 5. Emit the remaining `Added` and `Removed` records.
///
/// Output is pre-filter; callers apply their own `include_unchanged` /
/// `change_types` / `symbol_kinds` filters.
#[must_use]
pub fn compute_diff(old: &GraphSnapshot, new: &GraphSnapshot, opts: &DiffOptions) -> DiffOutput {
    let base_map = build_node_map(old, &opts.old_worktree_path);
    let target_map = build_node_map(new, &opts.new_worktree_path);

    let (added_nodes, modified_changes) = collect_added_and_modified(&base_map, &target_map, opts);
    let removed_nodes = collect_removed_nodes(&base_map, &target_map);

    let mut changes = modified_changes;

    let (rename_changes, renamed_qnames) = collect_renames(&removed_nodes, &added_nodes, opts);
    changes.extend(rename_changes);

    append_removed_changes(&mut changes, &removed_nodes, &renamed_qnames);
    append_added_changes(&mut changes, &added_nodes, &renamed_qnames);

    let summary = DiffSummary::from_changes(&changes);
    DiffOutput { changes, summary }
}

/// Builds a `qualified_name -> NodeSnap` map from a snapshot, joining each
/// node's stored file path onto `worktree_path` when the latter is set.
fn build_node_map(snapshot: &GraphSnapshot, worktree_path: &Path) -> HashMap<String, NodeSnap> {
    let strings = snapshot.strings();
    let files = snapshot.files();
    let mut map = HashMap::new();

    for (_node_id, entry) in snapshot.iter_nodes() {
        // Gate 0d iter-2 fix: skip unified losers from
        // `semantic_diff` node map. Losers have no name /
        // qualified_name / signature post-merge; the explicit guard
        // makes that contract visible to readers.
        // See `NodeEntry::is_unified_loser`.
        if entry.is_unified_loser() {
            continue;
        }
        let name = strings
            .resolve(entry.name)
            .map(|s| s.to_string())
            .unwrap_or_default();

        let qualified_name = entry
            .qualified_name
            .and_then(|sid| strings.resolve(sid))
            .map_or_else(|| name.clone(), |s| s.to_string());

        // Skip nodes without qualified names (call sites, imports, etc.).
        if qualified_name.is_empty() {
            continue;
        }

        let signature = entry
            .signature
            .and_then(|sid| strings.resolve(sid))
            .map(|s| s.to_string());

        let file_path = files
            .resolve(entry.file)
            .map(|p| {
                if worktree_path.as_os_str().is_empty() {
                    PathBuf::from(p.as_ref())
                } else {
                    worktree_path.join(p.as_ref())
                }
            })
            .unwrap_or_default();

        let language = files
            .language_for_file(entry.file)
            .map_or_else(|| "unknown".to_string(), |l| l.to_string());

        let snap = NodeSnap {
            name,
            qualified_name: qualified_name.clone(),
            kind: entry.kind,
            kind_str: node_kind_to_string(entry.kind),
            is_static: entry.is_static,
            signature,
            file_path,
            language,
            start_line: entry.start_line,
            end_line: entry.end_line,
            start_column: entry.start_column,
            end_column: entry.end_column,
        };

        map.insert(qualified_name, snap);
    }

    map
}

fn collect_added_and_modified(
    base_map: &HashMap<String, NodeSnap>,
    target_map: &HashMap<String, NodeSnap>,
    opts: &DiffOptions,
) -> (Vec<NodeSnap>, Vec<NodeChange>) {
    let mut added = Vec::new();
    let mut changes = Vec::new();

    for (qname, target_snap) in target_map {
        match base_map.get(qname) {
            None => added.push(target_snap.clone()),
            Some(base_snap) => {
                if let Some(change) = detect_modification(base_snap, target_snap, opts) {
                    changes.push(change);
                }
            }
        }
    }

    (added, changes)
}

fn collect_removed_nodes(
    base_map: &HashMap<String, NodeSnap>,
    target_map: &HashMap<String, NodeSnap>,
) -> Vec<NodeSnap> {
    base_map
        .iter()
        .filter(|(qname, _)| !target_map.contains_key(*qname))
        .map(|(_, snap)| snap.clone())
        .collect()
}

fn detect_modification(
    base_snap: &NodeSnap,
    target_snap: &NodeSnap,
    opts: &DiffOptions,
) -> Option<NodeChange> {
    let signature_changed = base_snap.signature != target_snap.signature;

    // Normalise file paths so "same path in different worktrees" does not
    // register as a body change.
    let base_rel = strip_worktree_prefix(&base_snap.file_path, opts);
    let target_rel = strip_worktree_prefix(&target_snap.file_path, opts);

    let body_changed = base_snap.start_line != target_snap.start_line
        || base_snap.end_line != target_snap.end_line
        || base_rel != target_rel;

    if signature_changed {
        Some(NodeChange {
            symbol_name: target_snap.name.clone(),
            qualified_name: target_snap.display_qualified_name(),
            kind: target_snap.kind_str.clone(),
            change_type: ChangeType::SignatureChanged,
            base_location: Some(base_snap.to_location()),
            target_location: Some(target_snap.to_location()),
            signature_before: base_snap.signature.clone(),
            signature_after: target_snap.signature.clone(),
        })
    } else if body_changed {
        Some(NodeChange {
            symbol_name: target_snap.name.clone(),
            qualified_name: target_snap.display_qualified_name(),
            kind: target_snap.kind_str.clone(),
            change_type: ChangeType::Modified,
            base_location: Some(base_snap.to_location()),
            target_location: Some(target_snap.to_location()),
            signature_before: base_snap.signature.clone(),
            signature_after: target_snap.signature.clone(),
        })
    } else {
        None
    }
}

fn collect_renames(
    removed: &[NodeSnap],
    added: &[NodeSnap],
    opts: &DiffOptions,
) -> (Vec<NodeChange>, HashSet<String>) {
    let renames = detect_renames(removed, added, opts);
    let mut rename_changes = Vec::new();
    let mut renamed_qnames = HashSet::new();

    for (base_snap, target_snap) in &renames {
        renamed_qnames.insert(base_snap.qualified_name.clone());
        renamed_qnames.insert(target_snap.qualified_name.clone());
        rename_changes.push(create_renamed_change(base_snap, target_snap));
    }

    (rename_changes, renamed_qnames)
}

fn detect_renames(
    removed: &[NodeSnap],
    added: &[NodeSnap],
    opts: &DiffOptions,
) -> Vec<(NodeSnap, NodeSnap)> {
    let mut renames = Vec::new();
    let mut matched_added: HashSet<usize> = HashSet::new();

    for removed_snap in removed {
        let mut best_match: Option<(usize, f64)> = None;

        for (idx, added_snap) in added.iter().enumerate() {
            if matched_added.contains(&idx) {
                continue;
            }
            let Some(score) = is_likely_rename(removed_snap, added_snap, opts) else {
                continue;
            };
            let is_better = match best_match {
                Some((_, best_score)) => score > best_score,
                None => true,
            };
            if is_better {
                best_match = Some((idx, score));
            }
        }

        if let Some((idx, score)) = best_match
            && score >= RENAME_CONFIDENCE_THRESHOLD
        {
            matched_added.insert(idx);
            renames.push((removed_snap.clone(), added[idx].clone()));
        }
    }

    renames
}

fn is_likely_rename(base: &NodeSnap, target: &NodeSnap, opts: &DiffOptions) -> Option<f64> {
    // Criterion 1: same node kind.
    if base.kind != target.kind {
        return None;
    }

    // Criterion 2: signature similarity (70% weight).
    let sig_score = match (&base.signature, &target.signature) {
        (Some(base_sig), Some(target_sig)) => {
            if base_sig == target_sig {
                1.0
            } else {
                levenshtein_similarity(base_sig, target_sig)
            }
        }
        (None, None) => 1.0,
        _ => return None,
    };
    if sig_score < SIGNATURE_MIN_SCORE {
        return None;
    }
    let mut confidence = sig_score * SIGNATURE_WEIGHT;

    // Criterion 3: location proximity (30% weight).
    let base_rel = strip_worktree_prefix(&base.file_path, opts);
    let target_rel = strip_worktree_prefix(&target.file_path, opts);
    let location_score = if base_rel == target_rel {
        let base_line: i32 = base.start_line.try_into().unwrap_or(i32::MAX);
        let target_line: i32 = target.start_line.try_into().unwrap_or(i32::MAX);
        let line_diff = (base_line - target_line).abs();
        if line_diff <= SAME_FILE_LINE_WINDOW {
            1.0 - (f64::from(line_diff) / SAME_FILE_LINE_NORMALIZER).min(SAME_FILE_MAX_PENALTY)
        } else {
            SAME_FILE_FAR_SCORE
        }
    } else {
        CROSS_FILE_LOCATION_SCORE
    };
    confidence += location_score * LOCATION_WEIGHT;

    Some(confidence)
}

fn create_renamed_change(base: &NodeSnap, target: &NodeSnap) -> NodeChange {
    NodeChange {
        symbol_name: target.name.clone(),
        qualified_name: target.display_qualified_name(),
        kind: target.kind_str.clone(),
        change_type: ChangeType::Renamed,
        base_location: Some(base.to_location()),
        target_location: Some(target.to_location()),
        signature_before: base.signature.clone(),
        signature_after: target.signature.clone(),
    }
}

fn append_removed_changes(
    changes: &mut Vec<NodeChange>,
    removed: &[NodeSnap],
    renamed_qnames: &HashSet<String>,
) {
    for snap in removed {
        if !renamed_qnames.contains(&snap.qualified_name) {
            changes.push(NodeChange {
                symbol_name: snap.name.clone(),
                qualified_name: snap.display_qualified_name(),
                kind: snap.kind_str.clone(),
                change_type: ChangeType::Removed,
                base_location: Some(snap.clone().into_location()),
                target_location: None,
                signature_before: snap.signature.clone(),
                signature_after: None,
            });
        }
    }
}

fn append_added_changes(
    changes: &mut Vec<NodeChange>,
    added: &[NodeSnap],
    renamed_qnames: &HashSet<String>,
) {
    for snap in added {
        if !renamed_qnames.contains(&snap.qualified_name) {
            changes.push(NodeChange {
                symbol_name: snap.name.clone(),
                qualified_name: snap.display_qualified_name(),
                kind: snap.kind_str.clone(),
                change_type: ChangeType::Added,
                base_location: None,
                target_location: Some(snap.clone().into_location()),
                signature_before: None,
                signature_after: snap.signature.clone(),
            });
        }
    }
}

/// Strips whichever of the two worktree prefixes from `path` matches.
fn strip_worktree_prefix(path: &Path, opts: &DiffOptions) -> PathBuf {
    if !opts.old_worktree_path.as_os_str().is_empty()
        && let Ok(relative) = path.strip_prefix(&opts.old_worktree_path)
    {
        return relative.to_path_buf();
    }
    if !opts.new_worktree_path.as_os_str().is_empty()
        && let Ok(relative) = path.strip_prefix(&opts.new_worktree_path)
    {
        return relative.to_path_buf();
    }
    path.to_path_buf()
}

/// Normalised Levenshtein similarity in `[0.0, 1.0]`.
fn levenshtein_similarity(a: &str, b: &str) -> f64 {
    let distance = strsim::levenshtein(a, b);
    let max_len = a.len().max(b.len());
    if max_len == 0 {
        return 1.0;
    }
    let distance = f64::from(u32::try_from(distance).unwrap_or(u32::MAX));
    let max_len = f64::from(u32::try_from(max_len).unwrap_or(u32::MAX));
    1.0 - (distance / max_len)
}

/// Lowercase node-kind strings matching the pre-DB20 MCP taxonomy. Any kind
/// not explicitly listed collapses to `"other"` — this matches the legacy
/// behaviour so `filters.symbol_kinds` keeps its existing acceptance set.
fn node_kind_to_string(kind: NodeKind) -> String {
    match kind {
        NodeKind::Function => "function",
        NodeKind::Method => "method",
        NodeKind::Class => "class",
        NodeKind::Interface => "interface",
        NodeKind::Trait => "trait",
        NodeKind::Module => "module",
        NodeKind::Variable => "variable",
        NodeKind::Constant => "constant",
        NodeKind::Type => "type",
        NodeKind::Struct => "struct",
        NodeKind::Enum => "enum",
        NodeKind::EnumVariant => "enum_variant",
        NodeKind::Macro => "macro",
        NodeKind::Parameter => "parameter",
        NodeKind::Property => "property",
        NodeKind::Import => "import",
        NodeKind::Export => "export",
        NodeKind::Component => "component",
        NodeKind::Service => "service",
        NodeKind::Resource => "resource",
        NodeKind::Endpoint => "endpoint",
        NodeKind::Test => "test",
        _ => "other",
    }
    .to_string()
}

// ============================================================================
// Unit tests
// ============================================================================

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

    #[test]
    fn levenshtein_similarity_bounds() {
        assert!((levenshtein_similarity("hello", "hello") - 1.0).abs() < 1e-10);
        assert!((levenshtein_similarity("", "") - 1.0).abs() < 1e-10);
        assert!(levenshtein_similarity("hello", "hallo") > 0.7);
        assert!(levenshtein_similarity("hello", "world") < 0.5);
    }

    #[test]
    fn change_type_wire_strings_match_pre_db20() {
        assert_eq!(ChangeType::Added.as_str(), "added");
        assert_eq!(ChangeType::Removed.as_str(), "removed");
        assert_eq!(ChangeType::Modified.as_str(), "modified");
        assert_eq!(ChangeType::Renamed.as_str(), "renamed");
        assert_eq!(ChangeType::SignatureChanged.as_str(), "signature_changed");
        assert_eq!(ChangeType::Unchanged.as_str(), "unchanged");
    }

    #[test]
    fn diff_summary_from_changes_tallies_each_bucket() {
        let changes = vec![
            NodeChange {
                symbol_name: "a".into(),
                qualified_name: "a".into(),
                kind: "function".into(),
                change_type: ChangeType::Added,
                base_location: None,
                target_location: None,
                signature_before: None,
                signature_after: None,
            },
            NodeChange {
                symbol_name: "b".into(),
                qualified_name: "b".into(),
                kind: "function".into(),
                change_type: ChangeType::Removed,
                base_location: None,
                target_location: None,
                signature_before: None,
                signature_after: None,
            },
            NodeChange {
                symbol_name: "c".into(),
                qualified_name: "c".into(),
                kind: "function".into(),
                change_type: ChangeType::SignatureChanged,
                base_location: None,
                target_location: None,
                signature_before: None,
                signature_after: None,
            },
        ];
        let summary = DiffSummary::from_changes(&changes);
        assert_eq!(summary.added, 1);
        assert_eq!(summary.removed, 1);
        assert_eq!(summary.signature_changed, 1);
        assert_eq!(summary.modified, 0);
        assert_eq!(summary.renamed, 0);
        assert_eq!(summary.unchanged, 0);
    }

    #[test]
    fn empty_snapshots_produce_empty_diff() {
        use std::sync::Arc;

        use sqry_core::graph::unified::concurrent::CodeGraph;

        let old = Arc::new(CodeGraph::new().snapshot());
        let new = Arc::new(CodeGraph::new().snapshot());

        let cmp = super::super::ComparativeQueryDb::new(old, new);
        let out = cmp.diff_default();
        assert!(out.changes.is_empty());
        assert_eq!(out.summary, DiffSummary::default());
    }

    #[test]
    fn strip_worktree_prefix_falls_back_when_empty() {
        let p = PathBuf::from("/tmp/foo/bar.rs");
        let out = strip_worktree_prefix(&p, &DiffOptions::default());
        // Default opts have empty paths → strip is a no-op.
        assert_eq!(out, p);
    }

    #[test]
    fn strip_worktree_prefix_strips_old_root() {
        let opts = DiffOptions {
            old_worktree_path: PathBuf::from("/tmp/old"),
            new_worktree_path: PathBuf::from("/tmp/new"),
        };
        let p = PathBuf::from("/tmp/old/src/foo.rs");
        let out = strip_worktree_prefix(&p, &opts);
        assert_eq!(out, PathBuf::from("src/foo.rs"));
    }
}