codescout 0.14.0

High-performance coding agent toolkit MCP server
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
use super::severity;
use super::{RefCandidate, RefKind, Resolution, Severity, Verdict};
use std::path::Path;

pub struct ResolveCtx<'a> {
    pub repo_root: &'a Path,
    pub memory_globs: &'a [globset::Glob],
    pub lsp: Option<&'a dyn crate::lsp::ops::LspProvider>,
    pub degraded_languages: std::cell::RefCell<Vec<String>>,
    /// Basename → list of relative paths in the workspace. Used by
    /// `resolve_file_path` as a fallback when a bare basename (no `/`) doesn't
    /// literally exist at the repo root. Built once per audit run in
    /// `mod.rs::call`. Empty disables the fallback (treat misses as
    /// `Verdict::Missing` exactly as before).
    pub basename_index: std::collections::HashMap<String, Vec<std::path::PathBuf>>,
}

pub fn resolve_ref(c: &RefCandidate, ctx: &ResolveCtx<'_>) -> Resolution {
    match c.ref_kind {
        RefKind::FilePath => resolve_file_path(c, ctx),
        RefKind::FileLine => resolve_file_line(c, ctx),
        RefKind::FileSymbol => resolve_file_symbol(c, ctx),
        RefKind::ModulePath => resolve_module_path_v1(c, ctx),
        RefKind::Link => resolve_link(c, ctx),
    }
}

fn resolve_file_path(c: &RefCandidate, ctx: &ResolveCtx<'_>) -> Resolution {
    if c.raw_ref.starts_with("../") || c.raw_ref.starts_with('/') {
        return Resolution {
            verdict: Verdict::Unknown,
            severity: Severity::Low,
            severity_reason: "policy_default",
            notes: Some("path outside active project; scope=umbrella required".to_string()),
        };
    }
    let path = ctx.repo_root.join(&c.raw_ref);
    if path.exists() {
        return Resolution {
            verdict: Verdict::Resolved,
            severity: Severity::Low,
            severity_reason: "policy_default",
            notes: None,
        };
    }
    // Basename fallback: conversational mentions of files without their full
    // path (e.g. `docling_reader.py` instead of `src/mrv/readers/docling_reader.py`).
    // See `docs/issues/2026-05-17-audit-doc-refs-basename-false-positives.md`.
    if let Some(r) = try_basename_fallback(&c.raw_ref, ctx) {
        return r;
    }
    verdict_with_drops(Verdict::Missing, Path::new(&c.md_file), ctx.memory_globs)
}

/// Look up `raw_ref` in the basename index when it has no `/`. Returns
/// `Some(Resolution)` with `ResolvedBasename` (single hit) or
/// `AmbiguousBasename` (multiple hits); `None` means "no match — caller should
/// fall through to the default missing verdict".
fn try_basename_fallback(raw_ref: &str, ctx: &ResolveCtx<'_>) -> Option<Resolution> {
    if raw_ref.contains('/') {
        return None;
    }
    let matches = ctx.basename_index.get(raw_ref)?;
    match matches.len() {
        0 => None,
        1 => Some(Resolution {
            verdict: Verdict::ResolvedBasename,
            severity: Severity::Low,
            severity_reason: "basename_match",
            notes: Some(format!("resolved by basename to {}", matches[0].display())),
        }),
        n => {
            let preview: Vec<String> = matches
                .iter()
                .take(5)
                .map(|p| p.display().to_string())
                .collect();
            let suffix = if n > 5 {
                format!(", and {} more", n - 5)
            } else {
                String::new()
            };
            Some(Resolution {
                verdict: Verdict::AmbiguousBasename,
                severity: Severity::Med,
                severity_reason: "basename_ambiguous",
                notes: Some(format!(
                    "basename matches {} files: {}{}",
                    n,
                    preview.join(", "),
                    suffix
                )),
            })
        }
    }
}

fn resolve_file_line(c: &RefCandidate, ctx: &ResolveCtx<'_>) -> Resolution {
    let (path_str, line_str) = c.raw_ref.rsplit_once(':').expect("file_line invariant");
    let path = ctx.repo_root.join(path_str);
    if !path.exists() {
        return verdict_with_drops(Verdict::Missing, Path::new(&c.md_file), ctx.memory_globs);
    }
    // Parse `N` (single line) or `N-M` (line range). Range covers two checks:
    // both endpoints in bounds, and start <= end.
    let (start, end): (u32, u32) = if let Some((a, b)) = line_str.split_once('-') {
        (a.parse().unwrap_or(0), b.parse().unwrap_or(0))
    } else {
        let n: u32 = line_str.parse().unwrap_or(0);
        (n, n)
    };
    let total = std::fs::read_to_string(&path)
        .map(|s| s.lines().count() as u32)
        .unwrap_or(0);
    if start == 0 || end == 0 || start > end || end > total {
        verdict_with_drops(Verdict::LineOob, Path::new(&c.md_file), ctx.memory_globs)
    } else {
        Resolution {
            verdict: Verdict::Resolved,
            severity: Severity::Low,
            severity_reason: "policy_default",
            notes: None,
        }
    }
}

fn resolve_link(c: &RefCandidate, ctx: &ResolveCtx<'_>) -> Resolution {
    if c.raw_ref.starts_with("http://") || c.raw_ref.starts_with("https://") {
        return Resolution {
            verdict: Verdict::External,
            severity: Severity::Low,
            severity_reason: "policy_default",
            notes: None,
        };
    }
    if let Some(anchor) = c.raw_ref.strip_prefix('#') {
        let target_md = ctx.repo_root.join(&c.md_file);
        if let Ok(text) = std::fs::read_to_string(&target_md) {
            let slugs: std::collections::HashSet<String> = text
                .lines()
                .filter_map(|l| {
                    let trimmed = l.trim_start();
                    if trimmed.starts_with('#') {
                        Some(slugify(trimmed.trim_start_matches('#').trim()))
                    } else {
                        None
                    }
                })
                .collect();
            if slugs.contains(&slugify(anchor)) {
                return Resolution {
                    verdict: Verdict::Resolved,
                    severity: Severity::Low,
                    severity_reason: "policy_default",
                    notes: None,
                };
            }
        }
        return verdict_with_drops(
            Verdict::AnchorMissing,
            Path::new(&c.md_file),
            ctx.memory_globs,
        );
    }
    // fs-scheme link → resolve per markdown convention.
    //
    // Refs starting with `./` or `../` are *explicitly* relative to the
    // file containing the link. Joining them to repo_root would resolve
    // `docs/agents/foo.md` → `../manual/X.md` against repo_root and miss
    // the intended `docs/manual/X.md`. Anchor to md_file.parent() so the
    // OS's `..` lookup walks from the right base.
    //
    // Refs that don't carry an explicit `./` or `../` prefix stay rooted
    // at repo_root — the project convention in this codebase is to write
    // such refs as repo-root-relative even inside docs that live one
    // subdirectory deep.
    let path = if c.raw_ref.starts_with("./") || c.raw_ref.starts_with("../") {
        let md_dir = ctx
            .repo_root
            .join(&c.md_file)
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| ctx.repo_root.to_path_buf());
        md_dir.join(&c.raw_ref)
    } else {
        ctx.repo_root.join(&c.raw_ref)
    };
    if path.exists() {
        return Resolution {
            verdict: Verdict::Resolved,
            severity: Severity::Low,
            severity_reason: "policy_default",
            notes: None,
        };
    }
    if let Some(r) = try_basename_fallback(&c.raw_ref, ctx) {
        return r;
    }
    verdict_with_drops(Verdict::Missing, Path::new(&c.md_file), ctx.memory_globs)
}

/// v1: module_path candidates are reported as Unknown without consulting LSP.
/// Workspace symbol search for dotted module identifiers is Phase 2.
/// We do NOT push to `degraded_languages` here because no language detection
/// is meaningful for bare dotted identifiers.
fn resolve_module_path_v1(_c: &RefCandidate, _ctx: &ResolveCtx<'_>) -> Resolution {
    Resolution {
        verdict: Verdict::Unknown,
        severity: Severity::Low,
        severity_reason: "policy_default",
        notes: None,
    }
}
fn resolve_file_symbol(c: &RefCandidate, ctx: &ResolveCtx<'_>) -> Resolution {
    // Accept both `path::symbol` (Rust-style) and `path:symbol` (Python-style)
    // separators. Try `::` first so a trailing colon doesn't leak into the
    // path part on Rust refs like `src/foo.rs::extract_surface`.
    let (path_str, name) = c
        .raw_ref
        .rsplit_once("::")
        .or_else(|| c.raw_ref.rsplit_once(':'))
        .expect("file_symbol invariant: raw_ref must contain a `::` or `:` separator");
    let path = ctx.repo_root.join(path_str);
    if !path.exists() {
        return verdict_with_drops(
            Verdict::FileMissing,
            Path::new(&c.md_file),
            ctx.memory_globs,
        );
    }
    let lang = detect_language(path_str);
    let Some(lsp) = ctx.lsp else {
        ctx.degraded_languages.borrow_mut().push(lang.to_string());
        return Resolution {
            verdict: Verdict::Unknown,
            severity: Severity::Low,
            severity_reason: "policy_default",
            notes: None,
        };
    };
    // Call the async LSP on a fresh runtime — the resolver is single-threaded per scan.
    let rt = tokio::runtime::Runtime::new().expect("tokio runtime");
    let lang_id = lang.to_string();
    let result = rt.block_on(async {
        let client = lsp
            .get_or_start(&lang_id, ctx.repo_root, None)
            .await
            .map_err(|e| e.to_string())?;
        let syms = client
            .document_symbols(&path, &lang_id)
            .await
            .map_err(|e| e.to_string())?;
        Ok::<_, String>(syms)
    });
    match result {
        Ok(syms) => {
            if syms.iter().any(|s| s.name == name) {
                Resolution {
                    verdict: Verdict::Resolved,
                    severity: Severity::Low,
                    severity_reason: "policy_default",
                    notes: None,
                }
            } else {
                verdict_with_drops(
                    Verdict::SymbolMissing,
                    Path::new(&c.md_file),
                    ctx.memory_globs,
                )
            }
        }
        Err(_) => {
            ctx.degraded_languages.borrow_mut().push(lang.to_string());
            Resolution {
                verdict: Verdict::Unknown,
                severity: Severity::Low,
                severity_reason: "policy_default",
                notes: None,
            }
        }
    }
}

fn detect_language(path: &str) -> &'static str {
    match path.rsplit_once('.').map(|(_, ext)| ext) {
        Some("rs") => "rust",
        Some("py") => "python",
        Some("ts") => "typescript",
        Some("kt") => "kotlin",
        Some("java") => "java",
        Some("go") => "go",
        _ => "unknown",
    }
}

fn verdict_with_drops(
    verdict: Verdict,
    md_file: &Path,
    memory_globs: &[globset::Glob],
) -> Resolution {
    let base = severity::default_severity(verdict);
    let (sev, reason) = severity::apply_drops(md_file, base, memory_globs);
    Resolution {
        verdict,
        severity: sev,
        severity_reason: reason,
        notes: None,
    }
}
fn slugify(s: &str) -> String {
    s.to_lowercase()
        .chars()
        .filter_map(|c| match c {
            'a'..='z' | '0'..='9' => Some(c),
            ' ' | '-' | '_' => Some('-'),
            _ => None,
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::librarian::tools::audit_doc_refs::{RefKind, RefPosition};
    use tempfile::TempDir;

    fn cand(raw: &str, md: &str, kind: RefKind) -> RefCandidate {
        RefCandidate {
            md_file: md.to_string(),
            md_line: 1,
            raw_ref: raw.to_string(),
            ref_kind: kind,
            position: RefPosition::InlineSpan,
        }
    }

    fn ctx<'a>(root: &'a Path, globs: &'a [globset::Glob]) -> ResolveCtx<'a> {
        ResolveCtx {
            repo_root: root,
            memory_globs: globs,
            lsp: None,
            degraded_languages: Default::default(),
            basename_index: std::collections::HashMap::new(),
        }
    }

    #[test]
    fn resolver_resolved_for_existing_path() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("foo.py"), "x = 1\n").unwrap();
        let r = resolve_ref(
            &cand("foo.py", "docs/spec.md", RefKind::FilePath),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(r.verdict, Verdict::Resolved);
    }

    #[test]
    fn resolver_missing_for_absent_path() {
        let tmp = TempDir::new().unwrap();
        let r = resolve_ref(
            &cand("gone.py", "docs/spec.md", RefKind::FilePath),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(r.verdict, Verdict::Missing);
        assert_eq!(r.severity, Severity::High);
        assert_eq!(r.severity_reason, "policy_default");
    }

    #[test]
    fn resolver_line_oob_for_short_file() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("foo.py"), "a\nb\nc\n").unwrap();
        let r = resolve_ref(
            &cand("foo.py:99", "docs/spec.md", RefKind::FileLine),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(r.verdict, Verdict::LineOob);
        assert_eq!(r.severity, Severity::Med);
    }

    #[test]
    fn resolver_external_for_https_link() {
        let tmp = TempDir::new().unwrap();
        let r = resolve_ref(
            &cand("https://example.com", "docs/spec.md", RefKind::Link),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(r.verdict, Verdict::External);
    }
    #[test]
    fn severity_drops_one_level_in_archive() {
        let tmp = TempDir::new().unwrap();
        let r = resolve_ref(
            &cand("gone.py", "docs/archive/old.md", RefKind::FilePath),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(r.verdict, Verdict::Missing);
        assert_eq!(r.severity, Severity::Med);
        assert_eq!(r.severity_reason, "archive_drop");
    }

    #[test]
    fn severity_drops_two_levels_in_memory() {
        let tmp = TempDir::new().unwrap();
        let globs: Vec<_> = crate::librarian::tools::audit_doc_refs::severity::DEFAULT_MEMORY_GLOBS
            .iter()
            .map(|g| globset::Glob::new(g).unwrap())
            .collect();
        let r = resolve_ref(
            &cand("gone.py", ".buddy/memory/foo.md", RefKind::FilePath),
            &ctx(tmp.path(), &globs),
        );
        assert_eq!(r.severity, Severity::Low);
        assert_eq!(r.severity_reason, "memory_drop");
    }

    #[test]
    fn severity_reason_populated_for_every_finding() {
        let tmp = TempDir::new().unwrap();
        // FilePath: plain path raw ref
        let r = resolve_ref(
            &cand("gone.py", "docs/spec.md", RefKind::FilePath),
            &ctx(tmp.path(), &[]),
        );
        assert!(
            !r.severity_reason.is_empty(),
            "FilePath severity_reason empty"
        );
        // FileLine: must have a colon-separated line number to satisfy the resolver invariant
        let r = resolve_ref(
            &cand("gone.py:1", "docs/spec.md", RefKind::FileLine),
            &ctx(tmp.path(), &[]),
        );
        assert!(
            !r.severity_reason.is_empty(),
            "FileLine severity_reason empty"
        );
        // Link: external URL
        let r = resolve_ref(
            &cand("https://example.com/gone", "docs/spec.md", RefKind::Link),
            &ctx(tmp.path(), &[]),
        );
        assert!(!r.severity_reason.is_empty(), "Link severity_reason empty");
    }

    // ── Task 8: LSP-backed FileSymbol tests ──────────────────────────────────

    #[test]
    fn resolver_symbol_missing_for_renamed_symbol() {
        use crate::lsp::mock::{MockLspClient, MockLspProvider};
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("foo.rs"), "pub fn bar() {}\n").unwrap();
        // MockLspClient::new() returns Ok(vec![]) for any document_symbols call.
        let lsp = MockLspProvider::with_client(MockLspClient::new());
        let c = cand("foo.rs:renamed_baz", "docs/spec.md", RefKind::FileSymbol);
        let r = resolve_ref(
            &c,
            &ResolveCtx {
                repo_root: tmp.path(),
                memory_globs: &[],
                lsp: Some(lsp.as_ref()),
                degraded_languages: Default::default(),
                basename_index: std::collections::HashMap::new(),
            },
        );
        assert_eq!(r.verdict, Verdict::SymbolMissing);
    }

    #[test]
    fn resolver_unknown_when_lsp_offline() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("foo.rs"), "pub fn bar() {}\n").unwrap();
        let c = cand("foo.rs:bar", "docs/spec.md", RefKind::FileSymbol);
        let ctx = ResolveCtx {
            repo_root: tmp.path(),
            memory_globs: &[],
            lsp: None,
            degraded_languages: Default::default(),
            basename_index: std::collections::HashMap::new(),
        };
        let r = resolve_ref(&c, &ctx);
        assert_eq!(r.verdict, Verdict::Unknown);
        assert!(ctx.degraded_languages.borrow().iter().any(|l| l == "rust"));
    }

    #[test]
    fn resolver_prefers_disk_truth_on_lsp_lag() {
        use crate::lsp::mock::{MockLspClient, MockLspProvider};
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("foo.rs"), "pub fn bar() {}\n").unwrap();
        // LSP returns no symbols (simulates lag / stale index) but file exists on disk.
        let lsp = MockLspProvider::with_client(MockLspClient::new());
        let c = cand("foo.rs:bar", "docs/spec.md", RefKind::FileSymbol);
        let r = resolve_ref(
            &c,
            &ResolveCtx {
                repo_root: tmp.path(),
                memory_globs: &[],
                lsp: Some(lsp.as_ref()),
                degraded_languages: Default::default(),
                basename_index: std::collections::HashMap::new(),
            },
        );
        // File exists on disk but LSP returned no symbols → SymbolMissing, NOT Unknown.
        // This encodes the "prefer disk truth" rule: the LSP responded (not offline),
        // so an empty symbol list means the symbol genuinely isn't there.
        assert_eq!(r.verdict, Verdict::SymbolMissing);
    }

    // ── Task 8b: path-outside-project + anchor link resolution ───────────────

    #[test]
    fn resolver_unknown_for_path_outside_project() {
        let tmp = TempDir::new().unwrap();
        let r = resolve_ref(
            &cand(
                "../other-repo/src/foo.py",
                "docs/spec.md",
                RefKind::FilePath,
            ),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(r.verdict, Verdict::Unknown);
        assert!(r
            .notes
            .as_deref()
            .unwrap_or("")
            .contains("outside active project"));
    }

    #[test]
    fn resolver_anchor_resolved_when_heading_present() {
        let tmp = TempDir::new().unwrap();
        let docs = tmp.path().join("docs");
        std::fs::create_dir_all(&docs).unwrap();
        std::fs::write(docs.join("spec.md"), "# Top\n\n## Auth\n\nbody\n").unwrap();
        let r = resolve_ref(
            &cand("#auth", "docs/spec.md", RefKind::Link),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(r.verdict, Verdict::Resolved);
    }

    #[test]
    fn resolver_anchor_missing_when_heading_absent() {
        let tmp = TempDir::new().unwrap();
        let docs = tmp.path().join("docs");
        std::fs::create_dir_all(&docs).unwrap();
        std::fs::write(docs.join("spec.md"), "# Top\n\n## Auth\n\nbody\n").unwrap();
        let r = resolve_ref(
            &cand("#missing-section", "docs/spec.md", RefKind::Link),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(r.verdict, Verdict::AnchorMissing);
        assert_eq!(r.severity, Severity::Med);
    }

    /// Basename fallback: bare basename (no `/`) that exists as exactly one
    /// file in the workspace resolves with `ResolvedBasename` + severity Low.
    /// Closes the false-positive class called out in
    /// `docs/issues/2026-05-17-audit-doc-refs-basename-false-positives.md`.
    #[test]
    fn resolver_resolves_by_basename_when_unique() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join("src/mrv/readers")).unwrap();
        std::fs::write(
            tmp.path().join("src/mrv/readers/docling_reader.py"),
            "# stub\n",
        )
        .unwrap();

        let mut index = std::collections::HashMap::new();
        index.insert(
            "docling_reader.py".to_string(),
            vec![std::path::PathBuf::from(
                "src/mrv/readers/docling_reader.py",
            )],
        );
        let ctx = ResolveCtx {
            repo_root: tmp.path(),
            memory_globs: &[],
            lsp: None,
            degraded_languages: Default::default(),
            basename_index: index,
        };
        let r = resolve_ref(
            &cand("docling_reader.py", "docs/adr/0006.md", RefKind::FilePath),
            &ctx,
        );
        assert_eq!(r.verdict, Verdict::ResolvedBasename);
        assert_eq!(r.severity, Severity::Low);
        assert_eq!(r.severity_reason, "basename_match");
        assert!(
            r.notes
                .as_ref()
                .is_some_and(|n| n.contains("src/mrv/readers/docling_reader.py")),
            "notes should cite the resolved path: {:?}",
            r.notes
        );
    }

    #[test]
    fn resolver_ambiguous_when_basename_matches_multiple_files() {
        let tmp = TempDir::new().unwrap();
        let mut index = std::collections::HashMap::new();
        index.insert(
            "__init__.py".to_string(),
            vec![
                std::path::PathBuf::from("src/foo/__init__.py"),
                std::path::PathBuf::from("src/bar/__init__.py"),
                std::path::PathBuf::from("src/baz/__init__.py"),
            ],
        );
        let ctx = ResolveCtx {
            repo_root: tmp.path(),
            memory_globs: &[],
            lsp: None,
            degraded_languages: Default::default(),
            basename_index: index,
        };
        let r = resolve_ref(
            &cand("__init__.py", "docs/spec.md", RefKind::FilePath),
            &ctx,
        );
        assert_eq!(r.verdict, Verdict::AmbiguousBasename);
        assert_eq!(r.severity, Severity::Med);
        assert_eq!(r.severity_reason, "basename_ambiguous");
        assert!(
            r.notes.as_ref().is_some_and(|n| n.contains("3 files")),
            "notes should report match count: {:?}",
            r.notes
        );
    }

    #[test]
    fn resolver_still_missing_when_basename_not_in_index() {
        let tmp = TempDir::new().unwrap();
        let ctx = ResolveCtx {
            repo_root: tmp.path(),
            memory_globs: &[],
            lsp: None,
            degraded_languages: Default::default(),
            basename_index: std::collections::HashMap::new(),
        };
        let r = resolve_ref(
            &cand("nonexistent.py", "docs/spec.md", RefKind::FilePath),
            &ctx,
        );
        assert_eq!(r.verdict, Verdict::Missing);
        assert_eq!(r.severity, Severity::High);
    }

    #[test]
    fn resolver_skips_basename_fallback_when_ref_contains_slash() {
        // Path-prefixed ref (`src/foo/bar.py`) that doesn't exist on disk
        // must remain Missing — even if `bar.py` is in the basename index,
        // we don't second-guess an explicit path.
        let tmp = TempDir::new().unwrap();
        let mut index = std::collections::HashMap::new();
        index.insert(
            "bar.py".to_string(),
            vec![std::path::PathBuf::from("other/place/bar.py")],
        );
        let ctx = ResolveCtx {
            repo_root: tmp.path(),
            memory_globs: &[],
            lsp: None,
            degraded_languages: Default::default(),
            basename_index: index,
        };
        let r = resolve_ref(
            &cand("src/foo/bar.py", "docs/spec.md", RefKind::FilePath),
            &ctx,
        );
        assert_eq!(r.verdict, Verdict::Missing);
        assert_eq!(r.severity, Severity::High);
    }

    #[test]
    fn resolver_resolved_for_in_bounds_line_range() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("foo.rs"), "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n").unwrap();
        let r = resolve_ref(
            &cand("foo.rs:3-7", "docs/spec.md", RefKind::FileLine),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(r.verdict, Verdict::Resolved);
    }

    #[test]
    fn resolver_line_oob_for_range_past_eof() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("foo.rs"), "1\n2\n3\n").unwrap();
        let r = resolve_ref(
            &cand("foo.rs:50-60", "docs/spec.md", RefKind::FileLine),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(r.verdict, Verdict::LineOob);
    }

    #[test]
    fn resolver_line_oob_for_inverted_range() {
        // start > end should be LineOob, not silently accepted.
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("foo.rs"), "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n").unwrap();
        let r = resolve_ref(
            &cand("foo.rs:7-3", "docs/spec.md", RefKind::FileLine),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(r.verdict, Verdict::LineOob);
    }

    #[test]
    fn resolver_link_with_dot_dot_resolves_relative_to_md_file_parent() {
        // Markdown convention: `[text](../path)` is relative to the file
        // containing the link, not to the project root. Pre-fix the resolver
        // joined repo_root + raw_ref unconditionally, so `../manual/X.md` from
        // `docs/agents/foo.md` looked for `<repo>/../manual/X.md` (outside the
        // repo) instead of `<repo>/docs/manual/X.md` — the file the doc
        // author actually meant.
        let tmp = TempDir::new().unwrap();
        // The md_file's parent dir must exist so the OS can traverse `..`
        // segments during `Path::exists`. In real audits this is guaranteed
        // (we're auditing a file that exists). Mirror that here.
        let agents_dir = tmp.path().join("docs/agents");
        std::fs::create_dir_all(&agents_dir).unwrap();
        std::fs::write(agents_dir.join("claude-code.md"), "# agents\n").unwrap();
        let target_dir = tmp.path().join("docs/manual/src/concepts");
        std::fs::create_dir_all(&target_dir).unwrap();
        std::fs::write(target_dir.join("superpowers.md"), "# Superpowers\n").unwrap();

        let r = resolve_ref(
            &cand(
                "../manual/src/concepts/superpowers.md",
                "docs/agents/claude-code.md",
                RefKind::Link,
            ),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(
            r.verdict,
            Verdict::Resolved,
            "../-relative link should resolve against md_file's parent; got {:?}",
            r
        );
    }

    #[test]
    fn resolver_link_with_dot_slash_resolves_relative_to_md_file_parent() {
        // Same convention applies to explicit `./` links — relative to the
        // md_file's parent directory.
        let tmp = TempDir::new().unwrap();
        let docs = tmp.path().join("docs/agents");
        std::fs::create_dir_all(&docs).unwrap();
        std::fs::write(docs.join("sibling.md"), "# Sibling\n").unwrap();

        let r = resolve_ref(
            &cand("./sibling.md", "docs/agents/claude-code.md", RefKind::Link),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(r.verdict, Verdict::Resolved);
    }

    #[test]
    fn resolver_link_without_explicit_relative_prefix_still_repo_root_rooted() {
        // Regression guard: refs that do NOT start with `./` or `../` continue
        // to resolve against repo_root, matching the existing project
        // convention of writing repo-root-relative paths inside docs that
        // live one subdir deep.
        let tmp = TempDir::new().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(src.join("lib.rs"), "fn main() {}\n").unwrap();

        let r = resolve_ref(
            &cand("src/lib.rs", "docs/agents/claude-code.md", RefKind::Link),
            &ctx(tmp.path(), &[]),
        );
        assert_eq!(
            r.verdict,
            Verdict::Resolved,
            "repo-root-relative link should keep resolving against repo_root; got {:?}",
            r
        );
    }
}