Skip to main content

symforge/sidecar/
handlers.rs

1//! HTTP endpoint handlers for the symforge sidecar.
2//!
3//! All handlers follow this contract:
4//!  - Accept `State(state): State<SidecarState>` plus optional `Query(params)`.
5//!  - Acquire `state.index.read()`, extract owned data, drop the guard, then return text or Json.
6//!  - Never hold a `RwLockReadGuard` across an `.await` point.
7//!  - On file not found: return `StatusCode::NOT_FOUND`.
8
9use axum::{
10    Json,
11    extract::{Query, State},
12    http::StatusCode,
13};
14use serde::{Deserialize, Serialize};
15
16use crate::domain::{LanguageId, ReferenceKind};
17use crate::sidecar::{SidecarState, SymbolSnapshot, build_with_budget};
18use crate::{protocol::edit, watcher};
19
20// ---------------------------------------------------------------------------
21// Request parameter structs
22// ---------------------------------------------------------------------------
23
24#[derive(Clone, Deserialize, Serialize)]
25pub struct OutlineParams {
26    pub path: String,
27    /// Optional token budget override. Default: 200 tokens (800 bytes).
28    pub max_tokens: Option<u64>,
29    /// Optional list of sections to include: "outline", "imports", "consumers", "references", "git".
30    /// When `None`, all sections are included.
31    #[serde(default)]
32    pub sections: Option<Vec<String>>,
33}
34
35#[derive(Clone, Deserialize, Serialize)]
36pub struct ImpactParams {
37    pub path: String,
38    /// If `true`, treat this as a new-file indexing request (HOOK-06).
39    pub new_file: Option<bool>,
40}
41
42#[derive(Clone, Deserialize, Serialize)]
43pub struct SymbolContextParams {
44    pub name: String,
45    /// Optional: restrict search to a specific file.
46    pub file: Option<String>,
47    /// Optional exact-selector path from `search_symbols`.
48    pub path: Option<String>,
49    /// Optional selected symbol kind such as `fn`, `class`, or `struct`.
50    pub symbol_kind: Option<String>,
51    /// Optional selected symbol line from `search_symbols`.
52    pub symbol_line: Option<u32>,
53}
54
55#[derive(Clone, Deserialize, Serialize)]
56pub struct PromptContextParams {
57    pub text: String,
58}
59
60struct PromptFileHint {
61    path: String,
62    line_hint_alias: Option<String>,
63    match_kind: PromptHintMatchKind,
64}
65
66struct PromptQualifiedSymbolHint {
67    file_hint: PromptFileHint,
68    symbol_name: String,
69}
70
71#[derive(Clone, Copy)]
72enum PromptHintMatchKind {
73    ExactPath,
74    ModuleAlias,
75    QualifiedPathAlias,
76    Basename,
77    StemLineAlias,
78    QualifiedSymbolAlias,
79}
80
81#[derive(Clone, Copy)]
82enum ContextSourceAuthority {
83    DiskRefreshed,
84    CurrentIndex,
85}
86
87#[derive(Serialize)]
88pub struct HealthResponse {
89    pub file_count: usize,
90    pub symbol_count: usize,
91    pub index_state: String,
92    pub uptime_secs: u64,
93}
94
95#[derive(Clone, Copy)]
96struct RenderOptions {
97    include_savings_footer: bool,
98    record_stats: bool,
99}
100
101const HOOK_RENDER_OPTIONS: RenderOptions = RenderOptions {
102    include_savings_footer: true,
103    record_stats: true,
104};
105
106const TOOL_RENDER_OPTIONS: RenderOptions = RenderOptions {
107    include_savings_footer: false,
108    record_stats: true,
109};
110
111fn format_prompt_context_signal(level: &str, evidence: impl Into<String>, body: String) -> String {
112    format!(
113        "Prompt-context signal: {level}\nEvidence: {}\n\n{body}",
114        evidence.into()
115    )
116}
117
118fn no_high_confidence_prompt_context_message() -> String {
119    "Prompt-context signal: no high-confidence hint\n\
120Evidence: no exact file, symbol, or repo-map cue matched the prompt\n\n\
121Suggested next step: use `search_symbols(...)` for likely names or `search_text(...)` for code/content search."
122        .to_string()
123}
124
125fn context_source_authority_label(authority: ContextSourceAuthority) -> &'static str {
126    match authority {
127        ContextSourceAuthority::DiskRefreshed => "disk-refreshed",
128        ContextSourceAuthority::CurrentIndex => "current index",
129    }
130}
131
132fn parse_state_label(status: &crate::live_index::store::ParseStatus) -> &'static str {
133    match status {
134        crate::live_index::store::ParseStatus::Parsed => "parsed",
135        crate::live_index::store::ParseStatus::PartialParse { .. } => "partial",
136        crate::live_index::store::ParseStatus::Failed { .. } => "degraded",
137    }
138}
139
140fn aggregate_parse_state_label<'a>(
141    statuses: impl IntoIterator<Item = &'a crate::live_index::store::ParseStatus>,
142    published: &crate::live_index::store::PublishedIndexState,
143) -> &'static str {
144    let mut saw_partial = false;
145    for status in statuses {
146        match status {
147            crate::live_index::store::ParseStatus::Parsed => {}
148            crate::live_index::store::ParseStatus::PartialParse { .. } => saw_partial = true,
149            crate::live_index::store::ParseStatus::Failed { .. } => return "degraded",
150        }
151    }
152    if saw_partial {
153        "partial"
154    } else if matches!(
155        published.status,
156        crate::live_index::store::PublishedIndexStatus::Degraded
157    ) {
158        "degraded"
159    } else {
160        "parsed"
161    }
162}
163
164fn format_context_envelope(
165    match_type: &str,
166    source_authority: ContextSourceAuthority,
167    parse_state: &str,
168    completeness: &str,
169    scope: impl Into<String>,
170    evidence: impl Into<String>,
171) -> String {
172    format!(
173        "Match type: {match_type}\nSource authority: {}\nParse state: {parse_state}\nCompleteness: {completeness}\nScope: {}\nEvidence: {}",
174        context_source_authority_label(source_authority),
175        scope.into(),
176        evidence.into()
177    )
178}
179
180fn freshen_sidecar_path_if_stale(
181    state: &SidecarState,
182    relative_path: &str,
183) -> ContextSourceAuthority {
184    let expected_gen = state.index.current_project_generation();
185    freshen_sidecar_path_if_stale_at_generation(state, relative_path, expected_gen)
186}
187
188fn safe_sidecar_path_for_freshen(
189    repo_root: &std::path::Path,
190    relative_path: &str,
191) -> Result<std::path::PathBuf, String> {
192    let relative = std::path::Path::new(relative_path);
193    if relative.is_absolute()
194        || relative
195            .components()
196            .any(|component| matches!(component, std::path::Component::ParentDir))
197    {
198        return Err(format!("path '{relative_path}' is outside the repository"));
199    }
200
201    match edit::safe_repo_path(repo_root, relative_path) {
202        Ok(path) => Ok(path),
203        Err(_) => {
204            let canon_root = repo_root
205                .canonicalize()
206                .map_err(|e| format!("cannot resolve repo root: {e}"))?;
207            Ok(canon_root.join(relative))
208        }
209    }
210}
211
212fn freshen_sidecar_path_if_stale_at_generation(
213    state: &SidecarState,
214    relative_path: &str,
215    expected_gen: u64,
216) -> ContextSourceAuthority {
217    let Some(repo_root) = &state.repo_root else {
218        return ContextSourceAuthority::CurrentIndex;
219    };
220    let Ok(abs_path) = safe_sidecar_path_for_freshen(repo_root, relative_path) else {
221        return ContextSourceAuthority::CurrentIndex;
222    };
223    match watcher::freshen_file_if_stale(relative_path, &abs_path, &state.index, expected_gen) {
224        watcher::FreshenResult::Fresh => ContextSourceAuthority::CurrentIndex,
225        watcher::FreshenResult::StaleReindexed => ContextSourceAuthority::DiskRefreshed,
226        watcher::FreshenResult::StaleRemoved => ContextSourceAuthority::DiskRefreshed,
227        watcher::FreshenResult::GenerationMismatch => ContextSourceAuthority::CurrentIndex,
228    }
229}
230
231fn describe_file_hint(file_hint: &PromptFileHint) -> (&'static str, String) {
232    match file_hint.match_kind {
233        PromptHintMatchKind::ExactPath => (
234            "high-confidence",
235            format!("exact path `{}` matched in the prompt", file_hint.path),
236        ),
237        PromptHintMatchKind::ModuleAlias => (
238            "medium-confidence",
239            format!(
240                "module alias `{}` resolved to `{}`",
241                file_hint.line_hint_alias.as_deref().unwrap_or("<unknown>"),
242                file_hint.path
243            ),
244        ),
245        PromptHintMatchKind::QualifiedPathAlias => (
246            "medium-confidence",
247            format!(
248                "path alias `{}` resolved to `{}`",
249                file_hint.line_hint_alias.as_deref().unwrap_or("<unknown>"),
250                file_hint.path
251            ),
252        ),
253        PromptHintMatchKind::Basename => (
254            "heuristic",
255            format!(
256                "basename `{}` matched `{}`",
257                file_hint.line_hint_alias.as_deref().unwrap_or("<unknown>"),
258                file_hint.path
259            ),
260        ),
261        PromptHintMatchKind::StemLineAlias => (
262            "heuristic",
263            format!(
264                "stem+line alias `{}` matched `{}`",
265                file_hint.line_hint_alias.as_deref().unwrap_or("<unknown>"),
266                file_hint.path
267            ),
268        ),
269        PromptHintMatchKind::QualifiedSymbolAlias => (
270            "high-confidence",
271            format!(
272                "qualified symbol alias `{}` resolved within `{}`",
273                file_hint.line_hint_alias.as_deref().unwrap_or("<unknown>"),
274                file_hint.path
275            ),
276        ),
277    }
278}
279
280fn resolve_repo_root(state: &SidecarState) -> Result<std::path::PathBuf, StatusCode> {
281    match &state.repo_root {
282        Some(root) => Ok(root.clone()),
283        None => std::env::current_dir().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR),
284    }
285}
286
287// ---------------------------------------------------------------------------
288// Handlers
289// ---------------------------------------------------------------------------
290
291/// `GET /health` — index state, file count, symbol count, uptime.
292pub async fn health_handler(
293    State(state): State<SidecarState>,
294) -> Result<Json<HealthResponse>, StatusCode> {
295    let published = state.index.published_state();
296
297    let uptime_secs = published
298        .loaded_at_system
299        .elapsed()
300        .unwrap_or_default()
301        .as_secs();
302
303    Ok(Json(HealthResponse {
304        file_count: published.file_count,
305        symbol_count: published.symbol_count,
306        index_state: published.status_label().to_string(),
307        uptime_secs,
308    }))
309}
310
311/// `GET /outline?path=<relative>[&max_tokens=N]` — symbol outline for a single file.
312///
313/// Returns formatted plain text with:
314/// - Symbol outline lines (compact, ripgrep-like)
315/// - "Key references" section showing top 3-5 most-called symbols with up to 3 callers each
316/// - "[~N tokens saved]" footer
317///
318/// Budget: 200 tokens (800 bytes) by default.
319pub async fn outline_handler(
320    State(state): State<SidecarState>,
321    Query(params): Query<OutlineParams>,
322) -> Result<String, StatusCode> {
323    outline_hook_text(&state, &params)
324}
325
326/// Workflow adapter for source-code reads/orientation.
327///
328/// This remains a thin alias over the canonical outline hook behavior so the
329/// sidecar exposes an explicit workflow surface without duplicating logic.
330pub async fn workflow_source_read_handler(
331    State(state): State<SidecarState>,
332    Query(params): Query<OutlineParams>,
333) -> Result<String, StatusCode> {
334    outline_handler(State(state), Query(params)).await
335}
336
337pub(crate) fn outline_tool_text(
338    state: &SidecarState,
339    params: &OutlineParams,
340) -> Result<String, StatusCode> {
341    outline_text(state, params, TOOL_RENDER_OPTIONS)
342}
343
344fn outline_hook_text(state: &SidecarState, params: &OutlineParams) -> Result<String, StatusCode> {
345    outline_text(state, params, HOOK_RENDER_OPTIONS)
346}
347
348fn append_parse_status_lines(
349    lines: &mut Vec<String>,
350    file: &crate::live_index::store::IndexedFile,
351) {
352    match &file.parse_status {
353        crate::live_index::store::ParseStatus::Parsed => {}
354        crate::live_index::store::ParseStatus::PartialParse { warning } => {
355            lines.push("Parse status: partial".to_string());
356            if let Some(diagnostic) = &file.parse_diagnostic {
357                lines.push(format!("Diagnostic: {}", diagnostic.summary()));
358                if let Some((start, end)) = diagnostic.byte_span {
359                    lines.push(format!("Byte span: {start}..{end}"));
360                }
361            } else {
362                lines.push(format!("Diagnostic: {warning}"));
363            }
364        }
365        crate::live_index::store::ParseStatus::Failed { error } => {
366            lines.push("Parse status: failed".to_string());
367            if let Some(diagnostic) = &file.parse_diagnostic {
368                lines.push(format!("Diagnostic: {}", diagnostic.summary()));
369                if let Some((start, end)) = diagnostic.byte_span {
370                    lines.push(format!("Byte span: {start}..{end}"));
371                }
372            } else {
373                lines.push(format!("Diagnostic: {error}"));
374            }
375        }
376    }
377}
378
379fn outline_text(
380    state: &SidecarState,
381    params: &OutlineParams,
382    options: RenderOptions,
383) -> Result<String, StatusCode> {
384    let source_authority = freshen_sidecar_path_if_stale(state, &params.path);
385    let guard = state.index.read();
386
387    // Return 404 for non-indexed files.
388    let file = guard.get_file(&params.path).ok_or(StatusCode::NOT_FOUND)?;
389
390    let file_bytes = file.byte_len;
391    let language = format!("{:?}", file.language);
392    let parse_state = parse_state_label(&file.parse_status);
393
394    let include_section = |name: &str| -> bool {
395        match &params.sections {
396            None => true,
397            Some(list) => list.iter().any(|s| s.eq_ignore_ascii_case(name)),
398        }
399    };
400
401    // Build symbol outline lines.
402    let mut body_lines: Vec<String> = Vec::new();
403    body_lines.push(format!(
404        "── {} ({} symbols, {}) ──",
405        params.path,
406        file.symbols.len(),
407        language
408    ));
409    append_parse_status_lines(&mut body_lines, file);
410
411    // Surface section validation warnings in the output.
412    if let Some(ref section_list) = params.sections {
413        let valid = ["outline", "imports", "consumers", "references", "git"];
414        let unknown: Vec<&str> = section_list
415            .iter()
416            .filter(|s| !valid.iter().any(|v| s.eq_ignore_ascii_case(v)))
417            .map(|s| s.as_str())
418            .collect();
419        if !unknown.is_empty() {
420            body_lines.push(format!(
421                "Warning: unknown section(s): {}. Valid: {}.",
422                unknown.join(", "),
423                valid.join(", ")
424            ));
425        }
426    }
427
428    if include_section("outline") {
429        for sym in &file.symbols {
430            let indent = "  ".repeat(sym.depth as usize);
431            let kind_str = sym.kind.to_string();
432            // Strip redundant kind prefix from name (e.g., impl blocks named "impl Foo").
433            let display_name = if sym.name.starts_with(&format!("{} ", kind_str)) {
434                &sym.name[kind_str.len() + 1..]
435            } else {
436                &sym.name[..]
437            };
438            body_lines.push(format!(
439                "{}  {:<10} {}  L{}-{}",
440                indent,
441                kind_str,
442                display_name,
443                sym.line_range.0 + 1,
444                sym.line_range.1 + 1,
445            ));
446        }
447    }
448
449    // Build "Imports from" section.
450    // Group import references by source (qualified_name or name), count per source.
451    if include_section("imports") {
452        let mut import_sources: std::collections::HashMap<&str, usize> =
453            std::collections::HashMap::new();
454        for reference in &file.references {
455            if reference.kind == ReferenceKind::Import {
456                let source = reference
457                    .qualified_name
458                    .as_deref()
459                    .unwrap_or(&reference.name);
460                *import_sources.entry(source).or_insert(0) += 1;
461            }
462        }
463        if !import_sources.is_empty() {
464            let mut sorted: Vec<_> = import_sources.into_iter().collect();
465            sorted.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
466            body_lines.push(String::new());
467            body_lines.push(format!("Imports from ({} sources):", sorted.len()));
468            for (source, count) in sorted.iter().take(10) {
469                body_lines.push(format!("  {} ({} symbols)", source, count));
470            }
471            if sorted.len() > 10 {
472                body_lines.push(format!("  ...and {} more", sorted.len() - 10));
473            }
474        }
475    }
476
477    // Build "Used by" section.
478    // Group dependents by consuming file, count references per consumer.
479    let attributed_dependents = guard.find_dependents_for_file(&params.path);
480    if include_section("consumers") {
481        let mut consumers: std::collections::HashMap<&str, usize> =
482            std::collections::HashMap::new();
483        for (file_path, _) in &attributed_dependents {
484            *consumers.entry(*file_path).or_insert(0) += 1;
485        }
486        if !consumers.is_empty() {
487            let mut sorted: Vec<_> = consumers.into_iter().collect();
488            sorted.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
489            body_lines.push(String::new());
490            body_lines.push(format!("Used by ({} files):", sorted.len()));
491            for (consumer, count) in sorted.iter().take(10) {
492                body_lines.push(format!("  {} ({} refs)", consumer, count));
493            }
494            if sorted.len() > 10 {
495                body_lines.push(format!("  ...and {} more", sorted.len() - 10));
496            }
497        }
498    }
499
500    // Build "Key references" section.
501    // Rank symbols by caller count descending, take top 5, show up to 3 callers each.
502    if include_section("references") {
503        let mut symbol_callers: Vec<(String, Vec<(String, u32)>)> = Vec::new();
504
505        for sym in &file.symbols {
506            let external_callers: Vec<(String, u32)> = attributed_dependents
507                .iter()
508                .filter(|(_, reference)| {
509                    reference.kind != ReferenceKind::Import && reference.name == sym.name
510                })
511                .map(|(fp, r)| (fp.to_string(), r.line_range.0 + 1))
512                .take(3)
513                .collect();
514
515            if !external_callers.is_empty() {
516                symbol_callers.push((sym.name.clone(), external_callers));
517            }
518        }
519
520        // Sort by caller count descending, take top 5.
521        symbol_callers.sort_by(|a, b| b.1.len().cmp(&a.1.len()));
522        symbol_callers.truncate(5);
523
524        if !symbol_callers.is_empty() {
525            body_lines.push(String::new());
526            body_lines.push("Key references:".to_string());
527            for (sym_name, callers) in &symbol_callers {
528                body_lines.push(format!("  {}()", sym_name));
529                for (caller_file, caller_line) in callers {
530                    body_lines.push(format!("    {}  line {}", caller_file, caller_line));
531                }
532            }
533        }
534    }
535
536    drop(guard);
537
538    // Build "Git activity" section from temporal intelligence.
539    if include_section("git") {
540        use crate::live_index::git_temporal::{
541            GitTemporalState, churn_bar, churn_label, relative_time,
542        };
543        let temporal = state.index.git_temporal();
544        if temporal.state == GitTemporalState::Ready
545            && let Some(history) = temporal.files.get(&params.path)
546        {
547            body_lines.push(String::new());
548            body_lines.push(format!(
549                "Git activity:  {} {:.2} ({})    {} commits, last {}",
550                churn_bar(history.churn_score),
551                history.churn_score,
552                churn_label(history.churn_score),
553                history.commit_count,
554                relative_time(history.last_commit.days_ago),
555            ));
556            body_lines.push(format!(
557                "  Last:  {} \"{}\" ({}, {})",
558                history.last_commit.hash,
559                history.last_commit.message_head,
560                history.last_commit.author,
561                history.last_commit.timestamp,
562            ));
563            if !history.contributors.is_empty() {
564                let owners: Vec<String> = history
565                    .contributors
566                    .iter()
567                    .map(|c| format!("{} {:.0}%", c.author, c.percentage))
568                    .collect();
569                body_lines.push(format!("  Owners: {}", owners.join(", ")));
570            }
571            if !history.co_changes.is_empty() {
572                body_lines.push("  Co-changes:".to_string());
573                for entry in &history.co_changes {
574                    body_lines.push(format!(
575                        "    {}  ({:.2} coupling, {} shared commits)",
576                        entry.path, entry.coupling_score, entry.shared_commits,
577                    ));
578                }
579            }
580        }
581    }
582
583    // Apply budget enforcement.
584    // Hook path: default 200 tokens (800 bytes) for compact hook output.
585    // Tool path: no cap unless explicitly requested — section filtering
586    // must be visible, not masked by a tiny default budget.
587    let max_bytes = match params.max_tokens {
588        Some(n) => n * 4,
589        None if options.include_savings_footer => 200 * 4, // hook path: compact
590        None => 0,                                         // tool path: unlimited (0 = no cap)
591    };
592    let (body_text, remaining) = build_with_budget(&body_lines, max_bytes);
593    let completeness = if remaining > 0 {
594        "budget-limited"
595    } else {
596        "full"
597    };
598    let scope = match &params.sections {
599        Some(sections) if !sections.is_empty() => {
600            format!("path `{}`; sections {}", params.path, sections.join(", "))
601        }
602        _ => format!("path `{}`; all sections", params.path),
603    };
604    let envelope = format_context_envelope(
605        "exact",
606        source_authority,
607        parse_state,
608        completeness,
609        scope,
610        format!("file anchor `{}`", params.path),
611    );
612    let mut text = format!("{envelope}\n\n{body_text}");
613
614    let output_bytes = text.len() as u64;
615    if options.include_savings_footer {
616        let saved_tokens = file_bytes.saturating_sub(output_bytes) / 4;
617        text.push_str(&format!("\n[~{} tokens saved]", saved_tokens));
618    }
619
620    if options.record_stats {
621        state.token_stats.record_read(file_bytes, output_bytes);
622    }
623
624    Ok(text)
625}
626
627/// `GET /impact?path=<relative>[&new_file=true]` — symbol diff after edit, or index confirmation.
628///
629/// **new_file=true (HOOK-06):** Reads file from disk, parses it, indexes it.
630/// Returns: language, symbol kind breakdown, `[Indexed, 0 callers yet]`.
631///
632/// **default (HOOK-05 edit):** Re-indexes the file from disk, computes pre/post symbol diff.
633/// Shows Added/Changed/Removed symbols plus callers for Changed+Removed symbols.
634///
635/// Budget: 150 tokens (600 bytes).
636pub async fn impact_handler(
637    State(state): State<SidecarState>,
638    Query(params): Query<ImpactParams>,
639) -> Result<String, StatusCode> {
640    impact_hook_text(state, &params).await
641}
642
643/// Workflow adapter for post-edit impact summaries.
644pub async fn workflow_post_edit_impact_handler(
645    State(state): State<SidecarState>,
646    Query(params): Query<ImpactParams>,
647) -> Result<String, StatusCode> {
648    impact_handler(State(state), Query(params)).await
649}
650
651pub(crate) async fn impact_tool_text(
652    state: SidecarState,
653    params: &ImpactParams,
654) -> Result<String, StatusCode> {
655    impact_text(state, params, TOOL_RENDER_OPTIONS).await
656}
657
658async fn impact_hook_text(
659    state: SidecarState,
660    params: &ImpactParams,
661) -> Result<String, StatusCode> {
662    impact_text(state, params, HOOK_RENDER_OPTIONS).await
663}
664
665async fn impact_text(
666    state: SidecarState,
667    params: &ImpactParams,
668    options: RenderOptions,
669) -> Result<String, StatusCode> {
670    let is_new_file = params.new_file.unwrap_or(false);
671
672    if is_new_file {
673        // HOOK-06: Index a new file from disk.
674        return handle_new_file_impact(state, &params.path, options).await;
675    }
676
677    let should_auto_index_new_file = {
678        let extension = std::path::Path::new(&params.path)
679            .extension()
680            .and_then(|e| e.to_str())
681            .unwrap_or("");
682        let is_supported = crate::domain::LanguageId::from_extension(extension).is_some();
683        let indexed = {
684            let guard = state.index.read();
685            guard.get_file(&params.path).is_some()
686        };
687        is_supported
688            && !indexed
689            && resolve_repo_root(&state)
690                .map(|root| root.join(&params.path).is_file())
691                .unwrap_or(false)
692    };
693
694    if should_auto_index_new_file {
695        return handle_new_file_impact(state, &params.path, options).await;
696    }
697
698    // HOOK-05: Re-index existing file and compute symbol diff.
699    handle_edit_impact(state, &params.path, options).await
700}
701
702async fn handle_new_file_impact(
703    state: SidecarState,
704    path: &str,
705    options: RenderOptions,
706) -> Result<String, StatusCode> {
707    use crate::domain::LanguageId;
708
709    // Determine language from file extension.
710    let extension = std::path::Path::new(path)
711        .extension()
712        .and_then(|e| e.to_str())
713        .unwrap_or("");
714
715    let language = LanguageId::from_extension(extension).ok_or(StatusCode::NOT_FOUND)?;
716
717    // Read file from disk. The sidecar doesn't know the project root, so
718    // we look up the root from the existing index as a heuristic.
719    // For new files, we try to find them relative to cwd.
720    let abs_path = resolve_repo_root(&state)?.join(path);
721    let path_owned = path.to_string();
722    let lang_clone = language.clone();
723    let (bytes, result, mtime_secs) =
724        tokio::task::spawn_blocking(move || -> Result<_, StatusCode> {
725            // Read mtime BEFORE content to avoid TOCTOU: if the file changes
726            // between reads, the recorded mtime will be older than the content,
727            // ensuring the watcher re-indexes on the next pass.
728            let mtime_secs = std::fs::metadata(&abs_path)
729                .and_then(|m| m.modified())
730                .ok()
731                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
732                .map(|d| d.as_secs())
733                .unwrap_or(0);
734            let bytes = std::fs::read(&abs_path).map_err(|_| StatusCode::NOT_FOUND)?;
735            let result = crate::parsing::process_file(&path_owned, &bytes, lang_clone);
736            Ok((bytes, result, mtime_secs))
737        })
738        .await
739        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)??;
740
741    // Build symbol kind breakdown.
742    let mut kind_counts: std::collections::HashMap<String, usize> =
743        std::collections::HashMap::new();
744    for sym in &result.symbols {
745        *kind_counts.entry(sym.kind.to_string()).or_insert(0) += 1;
746    }
747
748    let mut kind_parts: Vec<String> = kind_counts
749        .iter()
750        .map(|(k, v)| format!("{} {}", v, k))
751        .collect();
752    kind_parts.sort();
753    let kinds_str = if kind_parts.is_empty() {
754        "0 symbols".to_string()
755    } else {
756        kind_parts.join(", ")
757    };
758
759    // Index the file.
760    let indexed = crate::live_index::store::IndexedFile::from_parse_result(result, bytes)
761        .with_mtime(mtime_secs);
762    state.index.update_file(path.to_string(), indexed);
763
764    // Update symbol cache with empty pre-edit snapshot (it's new, no pre-state).
765    {
766        let mut cache = state.symbol_cache.write();
767        cache.insert(path.to_string(), Vec::new());
768    }
769
770    if options.record_stats {
771        state.token_stats.record_write();
772    }
773
774    let text = format!(
775        "Language: {:?}\nSymbols: {}\n[Indexed, 0 callers yet]",
776        language, kinds_str,
777    );
778
779    Ok(text)
780}
781
782/// Locate the SymbolRecord in an indexed file that corresponds to a
783/// pre-recorded SymbolSnapshot.
784///
785/// Used by analyze_file_impact so it can walk the symbol's parent impl
786/// block and type-scope the "Callers to review" list. Matches on the
787/// triple (name, kind, byte_range) — overloaded names are common, so
788/// name alone is insufficient.
789fn find_record_matching_snapshot<'a>(
790    file: &'a crate::live_index::store::IndexedFile,
791    sym: &SymbolSnapshot,
792) -> Option<&'a crate::domain::SymbolRecord> {
793    file.symbols.iter().find(|s| {
794        s.name == sym.name && s.kind.to_string() == sym.kind && s.byte_range == sym.byte_range
795    })
796}
797async fn handle_edit_impact(
798    state: SidecarState,
799    path: &str,
800    options: RenderOptions,
801) -> Result<String, StatusCode> {
802    use crate::domain::LanguageId;
803
804    // Get pre-edit symbols: sidecar cache → index pre-update snapshot → current index.
805    //
806    // The index pre-update snapshot (`take_pre_update_symbols`) fixes a race
807    // where the watcher re-indexes the file before this hook fires, causing the
808    // current index to already contain post-edit symbols and yielding a false
809    // "no symbol changes detected" result.
810    let pre_symbols: Vec<SymbolSnapshot> = {
811        let cache = state.symbol_cache.read();
812        if let Some(cached) = cache.get(path) {
813            cached.clone()
814        } else {
815            drop(cache);
816            // Try the index-level pre-update snapshot first (survives watcher race).
817            if let Some(pre) = state.index.take_pre_update_symbols(path) {
818                pre.into_iter()
819                    .map(|s| SymbolSnapshot {
820                        name: s.name,
821                        kind: s.kind,
822                        line_range: s.line_range,
823                        byte_range: s.byte_range,
824                    })
825                    .collect()
826            } else {
827                // No pre-update snapshot — populate from current index.
828                let guard = state.index.read();
829                if let Some(file) = guard.get_file(path) {
830                    file.symbols
831                        .iter()
832                        .map(|s| SymbolSnapshot {
833                            name: s.name.clone(),
834                            kind: s.kind.to_string(),
835                            line_range: s.line_range,
836                            byte_range: s.byte_range,
837                        })
838                        .collect()
839                } else {
840                    Vec::new()
841                }
842            }
843        }
844    };
845
846    // Get file byte_len from index before re-indexing.
847    let file_bytes_pre: u64 = {
848        let guard = state.index.read();
849        guard.get_file(path).map(|f| f.byte_len).unwrap_or(0)
850    };
851
852    // Determine language.
853    let extension = std::path::Path::new(path)
854        .extension()
855        .and_then(|e| e.to_str())
856        .unwrap_or("");
857
858    let language =
859        LanguageId::from_extension(extension).ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;
860
861    // Read file from disk and re-index.
862    let abs_path = resolve_repo_root(&state)?.join(path);
863    let path_owned = path.to_string();
864
865    enum ReadOutcome {
866        Ok {
867            bytes: Vec<u8>,
868            result: Box<crate::domain::FileProcessingResult>,
869            mtime_secs: u64,
870        },
871        NotFound,
872    }
873
874    let outcome = tokio::task::spawn_blocking(move || {
875        // Read mtime BEFORE content to avoid TOCTOU: if the file changes
876        // between reads, the recorded mtime will be older than the content,
877        // ensuring the watcher re-indexes on the next pass.
878        let mtime_secs = std::fs::metadata(&abs_path)
879            .and_then(|m| m.modified())
880            .ok()
881            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
882            .map(|d| d.as_secs())
883            .unwrap_or(0);
884        match std::fs::read(&abs_path) {
885            Ok(bytes) => {
886                let result = crate::parsing::process_file(&path_owned, &bytes, language);
887                ReadOutcome::Ok {
888                    bytes,
889                    result: Box::new(result),
890                    mtime_secs,
891                }
892            }
893            Err(_) => ReadOutcome::NotFound,
894        }
895    })
896    .await
897    .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
898
899    let (bytes, result, mtime_secs) = match outcome {
900        ReadOutcome::NotFound => {
901            // File not on disk — remove it from the index so stale data is purged.
902            let prev_symbol_count = {
903                let guard = state.index.read();
904                guard.get_file(path).map(|f| f.symbols.len()).unwrap_or(0)
905            };
906            state.index.remove_file(path);
907            // Also clear the symbol cache entry.
908            {
909                let mut cache = state.symbol_cache.write();
910                cache.remove(path);
911            }
912            let text = if prev_symbol_count > 0 {
913                format!(
914                    "── Impact: {} ──\nStatus: not found on disk — removed from index\nPreviously had {} symbols.",
915                    path, prev_symbol_count
916                )
917            } else {
918                // The file-watcher may have already purged the index entry
919                // between the on-disk delete and this call; in that case we
920                // have no pre-count to report, so say so plainly instead of
921                // printing a misleading `Previously had 0 symbols.`.
922                format!(
923                    "── Impact: {} ──\nStatus: not found on disk — no index record remains (may have been removed by watcher).",
924                    path
925                )
926            };
927            return Ok(text);
928        }
929        ReadOutcome::Ok {
930            bytes,
931            result,
932            mtime_secs,
933        } => (bytes, result, mtime_secs),
934    };
935
936    let file_bytes: u64 = (bytes.len() as u64).max(file_bytes_pre);
937
938    let post_symbols: Vec<SymbolSnapshot> = result
939        .symbols
940        .iter()
941        .map(|s| SymbolSnapshot {
942            name: s.name.clone(),
943            kind: s.kind.to_string(),
944            line_range: s.line_range,
945            byte_range: s.byte_range,
946        })
947        .collect();
948
949    let indexed = crate::live_index::store::IndexedFile::from_parse_result(*result, bytes)
950        .with_mtime(mtime_secs);
951    state.index.update_file(path.to_string(), indexed);
952
953    // Compute symbol diff using positional proximity for duplicate name+kind pairs.
954    let mut matched_pre = vec![false; pre_symbols.len()];
955    let mut matched_post = vec![false; post_symbols.len()];
956    let mut changed_post: Vec<usize> = Vec::new();
957
958    for (pi, ps) in post_symbols.iter().enumerate() {
959        // Find the closest unmatched pre-symbol with the same name+kind.
960        let best = pre_symbols
961            .iter()
962            .enumerate()
963            .filter(|(i, pr)| !matched_pre[*i] && pr.name == ps.name && pr.kind == ps.kind)
964            .min_by_key(|(_, pr)| (pr.line_range.0 as i64 - ps.line_range.0 as i64).unsigned_abs());
965        if let Some((pri, pr)) = best {
966            matched_pre[pri] = true;
967            matched_post[pi] = true;
968            if pr.line_range != ps.line_range || pr.byte_range != ps.byte_range {
969                changed_post.push(pi);
970            }
971        }
972    }
973
974    let added: Vec<&SymbolSnapshot> = post_symbols
975        .iter()
976        .enumerate()
977        .filter(|(i, _)| !matched_post[*i])
978        .map(|(_, s)| s)
979        .collect();
980
981    let removed: Vec<&SymbolSnapshot> = pre_symbols
982        .iter()
983        .enumerate()
984        .filter(|(i, _)| !matched_pre[*i])
985        .map(|(_, s)| s)
986        .collect();
987
988    let changed: Vec<&SymbolSnapshot> = changed_post.iter().map(|&i| &post_symbols[i]).collect();
989
990    // Update cache with post-edit snapshot.
991    {
992        let mut cache = state.symbol_cache.write();
993        cache.insert(path.to_string(), post_symbols.clone());
994    }
995
996    // Build response lines.
997    let mut lines: Vec<String> = Vec::new();
998    lines.push(format!("── Impact: {} ──", path));
999
1000    if added.is_empty() && changed.is_empty() && removed.is_empty() {
1001        lines.push(format!(
1002            "Status: indexed and unchanged\nSymbols: {}\nTip: Use what_changed to see recent modifications.",
1003            post_symbols.len()
1004        ));
1005    } else {
1006        lines.push("Status: changed on disk since last index".to_string());
1007        for sym in &added {
1008            lines.push(format!("  [Added]   {} {}", sym.kind, sym.name));
1009        }
1010        for sym in &changed {
1011            lines.push(format!("  [Changed] {} {}", sym.kind, sym.name));
1012        }
1013        for sym in &removed {
1014            lines.push(format!("  [Removed] {} {}", sym.kind, sym.name));
1015        }
1016
1017        // Show callers for Changed + Removed symbols.
1018        //
1019        // For CHANGED symbols that live inside an `impl` block, scope the
1020        // caller list to files that also reference the parent type —
1021        // prevents `MathMachine::new` from flagging every unrelated `new()`
1022        // call. Mirrors the filter in protocol::edit::detect_stale_references.
1023        //
1024        // REMOVED symbols cannot be type-scoped here: the post-edit file no
1025        // longer contains the SymbolRecord, so `find_record_matching_snapshot`
1026        // returns None and the filter short-circuits to name-only matching.
1027        // Acceptable trade-off: removing a same-named method from one of many
1028        // types is rare, and carrying parent_type through SymbolSnapshot would
1029        // widen the schema for a corner case. Revisit if the false positive
1030        // surfaces in real usage.
1031        let impacted: Vec<&SymbolSnapshot> =
1032            changed.iter().chain(removed.iter()).copied().collect();
1033        if !impacted.is_empty() {
1034            let guard = state.index.read();
1035            let post_file = guard.get_file(path);
1036            let mut callers_lines: Vec<String> = Vec::new();
1037            for sym in &impacted {
1038                // Derive the parent impl/class type for this symbol, if any.
1039                // Look the symbol up in the POST-edit file by name+byte_range so
1040                // overloaded names do not confuse the walker.
1041                let parent_type: Option<String> = post_file.as_ref().and_then(|file| {
1042                    find_record_matching_snapshot(file, sym).and_then(|record| {
1043                        crate::protocol::edit::find_parent_impl_type(file, record)
1044                    })
1045                });
1046
1047                // When we know the parent type, collect the set of files that
1048                // reference it. Only those files could plausibly call
1049                // `ParentType::method_name()`.
1050                let type_files: Option<std::collections::HashSet<String>> =
1051                    parent_type.as_ref().map(|tn| {
1052                        guard
1053                            .find_references_for_name(tn, None, false)
1054                            .into_iter()
1055                            .map(|(fp, _)| fp.to_string())
1056                            .collect()
1057                    });
1058
1059                let callers = guard.find_references_for_name(&sym.name, None, false);
1060                let external: Vec<_> = callers
1061                    .iter()
1062                    .filter(|(fp, _)| *fp != path)
1063                    .filter(|(fp, _)| match &type_files {
1064                        Some(tf) => tf.contains(*fp),
1065                        None => true,
1066                    })
1067                    .take(5)
1068                    .collect();
1069                if !external.is_empty() {
1070                    callers_lines.push(format!("  Callers of {}():", sym.name));
1071                    for (caller_file, r) in &external {
1072                        callers_lines.push(format!(
1073                            "    {}  line {}",
1074                            caller_file,
1075                            r.line_range.0 + 1
1076                        ));
1077                    }
1078                }
1079            }
1080            drop(guard);
1081            if !callers_lines.is_empty() {
1082                lines.push(String::new());
1083                lines.push("Callers to review:".to_string());
1084                lines.extend(callers_lines);
1085            }
1086        }
1087    }
1088
1089    // Apply budget (150 tokens = 600 bytes).
1090    let (mut text, _) = build_with_budget(&lines, 600);
1091
1092    let output_bytes = text.len() as u64;
1093    if options.include_savings_footer {
1094        let saved_tokens = file_bytes.saturating_sub(output_bytes) / 4;
1095        text.push_str(&format!("\n[~{} tokens saved]", saved_tokens));
1096    }
1097
1098    if options.record_stats {
1099        state.token_stats.record_edit(file_bytes, output_bytes);
1100    }
1101
1102    Ok(text)
1103}
1104
1105/// `GET /symbol-context?name=<name>[&file=<path>]` — all references to a named symbol.
1106///
1107/// Returns formatted plain text with enclosing-symbol annotations, grouped by file.
1108/// Caps at 10 annotated matches.
1109///
1110/// Budget: 100 tokens (400 bytes).
1111pub async fn symbol_context_handler(
1112    State(state): State<SidecarState>,
1113    Query(params): Query<SymbolContextParams>,
1114) -> Result<String, StatusCode> {
1115    symbol_context_hook_text(&state, &params)
1116}
1117
1118/// Workflow adapter for search-hit expansion and quick caller/context reads.
1119pub async fn workflow_search_hit_expansion_handler(
1120    State(state): State<SidecarState>,
1121    Query(params): Query<SymbolContextParams>,
1122) -> Result<String, StatusCode> {
1123    symbol_context_handler(State(state), Query(params)).await
1124}
1125
1126pub(crate) fn symbol_context_tool_text(
1127    state: &SidecarState,
1128    params: &SymbolContextParams,
1129) -> Result<String, StatusCode> {
1130    symbol_context_text(state, params, TOOL_RENDER_OPTIONS)
1131}
1132
1133fn symbol_context_hook_text(
1134    state: &SidecarState,
1135    params: &SymbolContextParams,
1136) -> Result<String, StatusCode> {
1137    symbol_context_text(state, params, HOOK_RENDER_OPTIONS)
1138}
1139
1140fn symbol_context_text(
1141    state: &SidecarState,
1142    params: &SymbolContextParams,
1143    options: RenderOptions,
1144) -> Result<String, StatusCode> {
1145    let source_authority = if let Some(path) = params.path.as_deref() {
1146        freshen_sidecar_path_if_stale(state, path)
1147    } else if let Some(file) = params.file.as_deref() {
1148        freshen_sidecar_path_if_stale(state, file)
1149    } else {
1150        ContextSourceAuthority::CurrentIndex
1151    };
1152    let guard = state.index.read();
1153    let published = state.index.published_state();
1154
1155    let references = if let Some(path) = params.path.as_deref() {
1156        match guard.find_exact_references_for_symbol(
1157            path,
1158            &params.name,
1159            params.symbol_kind.as_deref(),
1160            params.symbol_line,
1161            None,
1162        ) {
1163            Ok(refs) => refs,
1164            Err(error) => return Ok(error),
1165        }
1166    } else {
1167        guard.find_references_for_name(&params.name, None, false)
1168    };
1169
1170    // Group by file, applying optional file filter, capping at 10 total matches.
1171    let mut map: std::collections::HashMap<String, Vec<(u32, String, Option<String>)>> =
1172        std::collections::HashMap::new();
1173
1174    let mut total = 0usize;
1175    let mut grand_total = 0usize;
1176
1177    for (file_path, reference) in &references {
1178        grand_total += 1;
1179        if let Some(ref filter_file) = params.file
1180            && *file_path != filter_file.as_str()
1181        {
1182            continue;
1183        }
1184        if total >= 10 {
1185            continue; // count beyond 10 but don't include
1186        }
1187
1188        let enclosing = reference.enclosing_symbol_index.and_then(|idx| {
1189            guard
1190                .get_file(file_path)
1191                .and_then(|f| f.symbols.get(idx as usize))
1192                .map(|s| s.name.clone())
1193        });
1194
1195        map.entry(file_path.to_string()).or_default().push((
1196            reference.line_range.0,
1197            format!("{}", reference.kind),
1198            enclosing,
1199        ));
1200        total += 1;
1201    }
1202
1203    // Compute total bytes for savings (sum of content of all matched files).
1204    let total_bytes: u64 = map
1205        .keys()
1206        .filter_map(|fp| guard.get_file(fp))
1207        .map(|f| f.byte_len)
1208        .sum();
1209
1210    let parse_state = if let Some(path) = params.path.as_deref() {
1211        guard
1212            .get_file(path)
1213            .map(|file| parse_state_label(&file.parse_status))
1214            .unwrap_or_else(|| aggregate_parse_state_label(std::iter::empty(), &published))
1215    } else if let Some(file) = params.file.as_deref() {
1216        guard
1217            .get_file(file)
1218            .map(|indexed| parse_state_label(&indexed.parse_status))
1219            .unwrap_or_else(|| aggregate_parse_state_label(std::iter::empty(), &published))
1220    } else {
1221        aggregate_parse_state_label(
1222            map.keys()
1223                .filter_map(|file_path| guard.get_file(file_path))
1224                .map(|file| &file.parse_status),
1225            &published,
1226        )
1227    };
1228
1229    drop(guard);
1230
1231    // Sort files for deterministic output.
1232    let mut files: Vec<String> = map.keys().cloned().collect();
1233    files.sort();
1234
1235    let mut evidence_anchors: Vec<String> = Vec::new();
1236    for file in &files {
1237        // safe: `files` is built from `map.keys()` immediately above; lookup cannot miss.
1238        let refs = map.get(file).unwrap();
1239        let mut sorted_refs = refs.clone();
1240        sorted_refs.sort_by_key(|(line, _, _)| *line);
1241        for (line, _, _) in &sorted_refs {
1242            if evidence_anchors.len() >= 3 {
1243                break;
1244            }
1245            evidence_anchors.push(format!("{file}:{line}"));
1246        }
1247        if evidence_anchors.len() >= 3 {
1248            break;
1249        }
1250    }
1251
1252    let mut body_lines: Vec<String> = Vec::new();
1253
1254    for file in &files {
1255        body_lines.push(format!("── {} ──", file));
1256        // safe: `files` is built from `map.keys()` above; lookup cannot miss.
1257        let refs = map.get(file).unwrap();
1258        let mut sorted_refs = refs.clone();
1259        sorted_refs.sort_by_key(|(line, _, _)| *line);
1260        for (line, _kind, enclosing) in &sorted_refs {
1261            if let Some(sym_name) = enclosing {
1262                body_lines.push(format!("  line {}  in fn {}", line, sym_name));
1263            } else {
1264                body_lines.push(format!("  line {}  (module level)", line));
1265            }
1266        }
1267    }
1268
1269    if body_lines.is_empty() {
1270        body_lines.push("No references found in the index.".to_string());
1271        body_lines.push(
1272            "Tip: this symbol may only be used via dynamic dispatch, reflection, or external entry points.".to_string(),
1273        );
1274    }
1275
1276    if total < grand_total {
1277        if params.file.is_some() {
1278            body_lines.push(format!(
1279                "... (showing {} of {} matches — use `path` to narrow further)",
1280                total, grand_total
1281            ));
1282        } else {
1283            body_lines.push(format!(
1284                "... (showing {} of {} matches — use `path` or `file` to narrow)",
1285                total, grand_total
1286            ));
1287        }
1288    }
1289
1290    // Apply budget (100 tokens = 400 bytes).
1291    let (body_text, remaining) = build_with_budget(&body_lines, 400);
1292    let completeness = if total < grand_total {
1293        "truncated"
1294    } else if remaining > 0 {
1295        "budget-limited"
1296    } else {
1297        "full"
1298    };
1299    let match_type = if params.path.is_some() && params.symbol_line.is_some() {
1300        "exact"
1301    } else if params.path.is_some() || params.file.is_some() {
1302        "constrained"
1303    } else {
1304        "heuristic"
1305    };
1306    let evidence = if let Some(path) = params.path.as_deref() {
1307        match params.symbol_line {
1308            Some(line) => format!(
1309                "exact selector `{path}:{line}` for symbol `{}`",
1310                params.name
1311            ),
1312            None => format!("path-constrained symbol `{}` in `{path}`", params.name),
1313        }
1314    } else if let Some(file) = params.file.as_deref() {
1315        format!("file filter `{file}` for symbol `{}`", params.name)
1316    } else if evidence_anchors.is_empty() {
1317        format!(
1318            "symbol token `{}` with no indexed reference anchors",
1319            params.name
1320        )
1321    } else {
1322        format!(
1323            "symbol token `{}` anchored at {}",
1324            params.name,
1325            evidence_anchors.join(", ")
1326        )
1327    };
1328    let scope = if let Some(path) = params.path.as_deref() {
1329        match params.symbol_line {
1330            Some(line) => format!("path `{path}`; exact selector line {line}"),
1331            None => format!("path `{path}`; symbol-scoped references"),
1332        }
1333    } else if let Some(file) = params.file.as_deref() {
1334        format!("file filter `{file}`; symbol token `{}`", params.name)
1335    } else {
1336        format!("repo-wide symbol token `{}`", params.name)
1337    };
1338    let envelope = format_context_envelope(
1339        match_type,
1340        source_authority,
1341        parse_state,
1342        completeness,
1343        scope,
1344        evidence,
1345    );
1346    let mut text = format!("{envelope}\n\n{body_text}");
1347
1348    let output_bytes = text.len() as u64;
1349    if options.include_savings_footer {
1350        let saved_tokens = total_bytes.saturating_sub(output_bytes) / 4;
1351        text.push_str(&format!("\n[~{} tokens saved]", saved_tokens));
1352    }
1353
1354    if options.record_stats {
1355        state.token_stats.record_grep(total_bytes, output_bytes);
1356    }
1357
1358    Ok(text)
1359}
1360
1361/// `GET /repo-map` — formatted directory tree with symbol counts.
1362///
1363/// Returns 2-level directory tree with file counts and symbol counts per directory,
1364/// plus a language breakdown header.
1365///
1366/// Budget: 500 tokens (2000 bytes). No token savings recorded (additive, not replacement).
1367pub async fn repo_map_handler(State(state): State<SidecarState>) -> Result<String, StatusCode> {
1368    repo_map_text(&state)
1369}
1370
1371/// Workflow adapter for repo-start quick maps.
1372pub async fn workflow_repo_start_handler(
1373    State(state): State<SidecarState>,
1374) -> Result<String, StatusCode> {
1375    repo_map_handler(State(state)).await
1376}
1377
1378/// Heuristic: whether an indexed path looks like it belongs to the
1379/// active workspace.
1380///
1381/// Rejects any path containing `:` (Windows drive letter — `C:\…`) or
1382/// starting with `/` (POSIX absolute). Kept loose on purpose: a legit
1383/// file literally named `src/a:b.rs` on POSIX would also be filtered,
1384/// but we accept that edge case in exchange for matching the pre-existing
1385/// guard at the header-stats loop exactly and blocking the octogent-style
1386/// cross-workspace leak that motivated Unit 1.
1387fn is_intra_workspace_path(path: &str) -> bool {
1388    !(path.contains(':') || path.starts_with('/'))
1389}
1390pub(crate) fn repo_map_text(state: &SidecarState) -> Result<String, StatusCode> {
1391    // Single lock acquisition covers both the directory stats and key-types passes.
1392    let guard = state.index.read();
1393
1394    let total_files = guard.file_count();
1395    let total_symbols = guard.symbol_count();
1396
1397    // Collect language breakdown.
1398    let mut lang_counts: std::collections::HashMap<String, usize> =
1399        std::collections::HashMap::new();
1400    // Collect per-directory stats (2-level max).
1401    let mut dir_file_counts: std::collections::HashMap<String, usize> =
1402        std::collections::HashMap::new();
1403    let mut dir_symbol_counts: std::collections::HashMap<String, usize> =
1404        std::collections::HashMap::new();
1405
1406    for (path, file) in guard.all_files() {
1407        // Skip files with absolute paths (outside project root, e.g., Windows memory files).
1408        if !is_intra_workspace_path(path) {
1409            continue;
1410        }
1411
1412        // Language breakdown.
1413        let lang = format!("{:?}", file.language);
1414        *lang_counts.entry(lang).or_insert(0) += 1;
1415
1416        // Directory (up to 2 levels).
1417        let dir = get_dir_2level(path);
1418        *dir_file_counts.entry(dir.clone()).or_insert(0) += 1;
1419        *dir_symbol_counts.entry(dir).or_insert(0) += file.symbols.len();
1420    }
1421
1422    // Build header.
1423    let mut lang_parts: Vec<String> = lang_counts
1424        .iter()
1425        .map(|(k, v)| format!("{}: {}", k, v))
1426        .collect();
1427    lang_parts.sort();
1428
1429    let mut lines: Vec<String> = Vec::new();
1430    lines.push(format!(
1431        "Index: {} files, {} symbols  [{}]",
1432        total_files,
1433        total_symbols,
1434        lang_parts.join(", ")
1435    ));
1436    lines.push(String::new());
1437
1438    // Sort directories and emit tree.
1439    let mut dirs: Vec<String> = dir_file_counts.keys().cloned().collect();
1440    dirs.sort();
1441
1442    for dir in &dirs {
1443        let file_count = dir_file_counts[dir];
1444        let sym_count = dir_symbol_counts[dir];
1445        lines.push(format!(
1446            "  {:<35}  {:>3} files   {:>5} symbols",
1447            dir, file_count, sym_count
1448        ));
1449    }
1450
1451    // Key entry points: top-level structs/traits/interfaces/enums in src/ (depth 0, limit 10).
1452    {
1453        let mut entry_points: Vec<(String, String, String)> = Vec::new(); // (kind, name, path)
1454        for (path, file) in guard.all_files() {
1455            // Exclude paths from other indexed workspaces — same guard as the
1456            // directory-stats loop above; without it the key-types section
1457            // leaks symbols from unrelated projects.
1458            if !is_intra_workspace_path(path) {
1459                continue;
1460            }
1461            // Only source code, skip docs/tests/vendor
1462            let pl = path.to_ascii_lowercase();
1463            if pl.ends_with(".md")
1464                || pl.contains("/docs/")
1465                || pl.contains("vendor/")
1466                || pl.contains("node_modules/")
1467            {
1468                continue;
1469            }
1470            for sym in &file.symbols {
1471                if sym.depth == 0 {
1472                    match sym.kind {
1473                        crate::domain::SymbolKind::Struct
1474                        | crate::domain::SymbolKind::Trait
1475                        | crate::domain::SymbolKind::Interface
1476                        | crate::domain::SymbolKind::Enum
1477                        | crate::domain::SymbolKind::Class => {
1478                            entry_points.push((
1479                                sym.kind.to_string(),
1480                                sym.name.clone(),
1481                                path.to_string(),
1482                            ));
1483                        }
1484                        _ => {}
1485                    }
1486                }
1487            }
1488        }
1489        if !entry_points.is_empty() {
1490            entry_points.sort_by(|a, b| a.2.cmp(&b.2).then(a.1.cmp(&b.1)));
1491            entry_points.truncate(15);
1492            lines.push(String::new());
1493            lines.push("Key types:".to_string());
1494            for (kind, name, path) in &entry_points {
1495                lines.push(format!("  {kind} {name}  ({path})"));
1496            }
1497            if entry_points.len() == 15 {
1498                lines.push("  ...".to_string());
1499            }
1500        }
1501    }
1502
1503    drop(guard);
1504
1505    // Apply budget (1000 tokens = 4000 bytes).
1506    // Medium repos (up to ~70 directories) fit without truncation.
1507    let (text, _) = build_with_budget(&lines, 4000);
1508
1509    Ok(text)
1510}
1511
1512/// `GET /prompt-context?text=<prompt>` — derive compact context from a user prompt.
1513///
1514/// Heuristics:
1515/// - explicit file hint in the prompt => outline for that file
1516/// - explicit symbol hint in the prompt => symbol context for that symbol
1517/// - repo-map intent keywords => repo map
1518/// - otherwise => explicit low-confidence guidance with next-step suggestions
1519pub async fn prompt_context_handler(
1520    State(state): State<SidecarState>,
1521    Query(params): Query<PromptContextParams>,
1522) -> Result<String, StatusCode> {
1523    prompt_context_hook_text(&state, &params).await
1524}
1525
1526/// Workflow adapter for prompt-context narrowing.
1527pub async fn workflow_prompt_narrowing_handler(
1528    State(state): State<SidecarState>,
1529    Query(params): Query<PromptContextParams>,
1530) -> Result<String, StatusCode> {
1531    prompt_context_handler(State(state), Query(params)).await
1532}
1533
1534async fn prompt_context_hook_text(
1535    state: &SidecarState,
1536    params: &PromptContextParams,
1537) -> Result<String, StatusCode> {
1538    prompt_context_text(state, params, HOOK_RENDER_OPTIONS).await
1539}
1540
1541async fn prompt_context_text(
1542    state: &SidecarState,
1543    params: &PromptContextParams,
1544    options: RenderOptions,
1545) -> Result<String, StatusCode> {
1546    let prompt = params.text.trim();
1547    if prompt.is_empty() {
1548        return Ok(String::new());
1549    }
1550
1551    if let Some(symbol_hint) = find_prompt_qualified_symbol_hint(state, prompt)? {
1552        let line_hint = find_prompt_line_hint(prompt, Some(&symbol_hint.file_hint));
1553        let body = symbol_context_text(
1554            state,
1555            &SymbolContextParams {
1556                name: symbol_hint.symbol_name,
1557                file: None,
1558                path: Some(symbol_hint.file_hint.path.clone()),
1559                symbol_kind: None,
1560                symbol_line: line_hint,
1561            },
1562            options,
1563        )?;
1564        let (level, evidence) = describe_file_hint(&symbol_hint.file_hint);
1565        return Ok(format_prompt_context_signal(level, evidence, body));
1566    }
1567
1568    let file_hint = find_prompt_file_hint(state, prompt)?;
1569    let symbol_hint = find_prompt_symbol_hint(state, prompt)?;
1570    let line_hint = find_prompt_line_hint(prompt, file_hint.as_ref());
1571
1572    match (file_hint, symbol_hint) {
1573        (Some(file_hint), Some(name)) => {
1574            let body = symbol_context_text(
1575                state,
1576                &SymbolContextParams {
1577                    name: name.clone(),
1578                    file: None,
1579                    path: Some(file_hint.path.clone()),
1580                    symbol_kind: None,
1581                    symbol_line: line_hint,
1582                },
1583                options,
1584            )?;
1585            let (level, file_evidence) = describe_file_hint(&file_hint);
1586            return Ok(format_prompt_context_signal(
1587                level,
1588                format!("{file_evidence}; symbol token `{name}` found in the index"),
1589                body,
1590            ));
1591        }
1592        (Some(file_hint), None) => {
1593            let body = outline_text(
1594                state,
1595                &OutlineParams {
1596                    path: file_hint.path.clone(),
1597                    max_tokens: Some(160),
1598                    sections: None,
1599                },
1600                options,
1601            )?;
1602            let (level, evidence) = describe_file_hint(&file_hint);
1603            return Ok(format_prompt_context_signal(level, evidence, body));
1604        }
1605        (None, Some(name)) => {
1606            let body = symbol_context_text(
1607                state,
1608                &SymbolContextParams {
1609                    name: name.clone(),
1610                    file: None,
1611                    path: None,
1612                    symbol_kind: None,
1613                    symbol_line: None,
1614                },
1615                options,
1616            )?;
1617            return Ok(format_prompt_context_signal(
1618                "heuristic",
1619                format!("symbol token `{name}` matched somewhere in the index"),
1620                body,
1621            ));
1622        }
1623        (None, None) => {}
1624    }
1625
1626    if prompt_requests_repo_map(prompt) {
1627        let body = repo_map_text(state)?;
1628        return Ok(format_prompt_context_signal(
1629            "high-confidence",
1630            "repo-map request phrase matched in the prompt",
1631            body,
1632        ));
1633    }
1634
1635    Ok(no_high_confidence_prompt_context_message())
1636}
1637
1638/// `GET /stats` — return token savings snapshot as JSON.
1639pub async fn stats_handler(
1640    State(state): State<SidecarState>,
1641) -> Json<crate::sidecar::StatsSnapshot> {
1642    Json(state.token_stats.summary())
1643}
1644
1645// ---------------------------------------------------------------------------
1646// Helper: extract up to 2-level directory from a relative path
1647// ---------------------------------------------------------------------------
1648
1649fn get_dir_2level(path: &str) -> String {
1650    let p = std::path::Path::new(path);
1651    let components: Vec<_> = p.components().collect();
1652
1653    if components.len() <= 1 {
1654        // Root-level file.
1655        return "(root)".to_string();
1656    }
1657
1658    // Take at most 2 directory components (exclude the file name).
1659    let dir_components: Vec<_> = components[..components.len() - 1].iter().take(2).collect();
1660    dir_components
1661        .iter()
1662        .map(|c| c.as_os_str().to_string_lossy().to_string())
1663        .collect::<Vec<_>>()
1664        .join("/")
1665}
1666
1667fn find_prompt_file_hint(
1668    state: &SidecarState,
1669    prompt: &str,
1670) -> Result<Option<PromptFileHint>, StatusCode> {
1671    let guard = state.index.read();
1672    let prompt_lower = prompt.to_ascii_lowercase();
1673    let mut module_match: Option<PromptFileHint> = None;
1674    let mut module_ambiguous = false;
1675    let mut qualified_path_match: Option<PromptFileHint> = None;
1676    let mut qualified_path_ambiguous = false;
1677    let mut basename_match: Option<PromptFileHint> = None;
1678    let mut basename_ambiguous = false;
1679    let mut stem_match: Option<PromptFileHint> = None;
1680    let mut stem_ambiguous = false;
1681
1682    for (path, file) in guard.all_files() {
1683        if prompt.contains(path) || prompt_lower.contains(&path.to_ascii_lowercase()) {
1684            return Ok(Some(PromptFileHint {
1685                path: path.to_string(),
1686                line_hint_alias: None,
1687                match_kind: PromptHintMatchKind::ExactPath,
1688            }));
1689        }
1690
1691        if let Some(module_alias) = prompt_file_module_alias(path, &file.language)
1692            && prompt_contains_exact_alias(prompt, &module_alias)
1693        {
1694            if let Some(existing) = &module_match {
1695                if existing.path != path.as_str() {
1696                    module_ambiguous = true;
1697                }
1698            } else {
1699                module_match = Some(PromptFileHint {
1700                    path: path.to_string(),
1701                    line_hint_alias: Some(module_alias),
1702                    match_kind: PromptHintMatchKind::ModuleAlias,
1703                });
1704            }
1705        }
1706
1707        if let Some(path_without_extension) = prompt_path_without_extension(path)
1708            && find_prompt_path_line_hint(prompt, &path_without_extension).is_some()
1709        {
1710            if let Some(existing) = &qualified_path_match {
1711                if existing.path != path.as_str() {
1712                    qualified_path_ambiguous = true;
1713                }
1714            } else {
1715                qualified_path_match = Some(PromptFileHint {
1716                    path: path.to_string(),
1717                    line_hint_alias: Some(path_without_extension),
1718                    match_kind: PromptHintMatchKind::QualifiedPathAlias,
1719                });
1720            }
1721        }
1722
1723        let Some(file_name) = std::path::Path::new(path)
1724            .file_name()
1725            .and_then(|name| name.to_str())
1726        else {
1727            continue;
1728        };
1729        if prompt_lower.contains(&file_name.to_ascii_lowercase()) {
1730            if let Some(existing) = &basename_match {
1731                if existing.path != path.as_str() {
1732                    basename_ambiguous = true;
1733                }
1734            } else {
1735                basename_match = Some(PromptFileHint {
1736                    path: path.to_string(),
1737                    line_hint_alias: Some(file_name.to_string()),
1738                    match_kind: PromptHintMatchKind::Basename,
1739                });
1740            }
1741        }
1742
1743        let Some(file_stem) = std::path::Path::new(path)
1744            .file_stem()
1745            .and_then(|name| name.to_str())
1746        else {
1747            continue;
1748        };
1749
1750        if find_prompt_path_line_hint(prompt, file_stem).is_none() {
1751            continue;
1752        }
1753
1754        if let Some(existing) = &stem_match {
1755            if existing.path != path.as_str() {
1756                stem_ambiguous = true;
1757            }
1758        } else {
1759            stem_match = Some(PromptFileHint {
1760                path: path.to_string(),
1761                line_hint_alias: Some(file_stem.to_string()),
1762                match_kind: PromptHintMatchKind::StemLineAlias,
1763            });
1764        }
1765    }
1766
1767    if !module_ambiguous && module_match.is_some() {
1768        return Ok(module_match);
1769    }
1770
1771    if !qualified_path_ambiguous && qualified_path_match.is_some() {
1772        return Ok(qualified_path_match);
1773    }
1774
1775    if !basename_ambiguous && basename_match.is_some() {
1776        return Ok(basename_match);
1777    }
1778
1779    if stem_ambiguous {
1780        Ok(None)
1781    } else {
1782        Ok(stem_match)
1783    }
1784}
1785
1786fn find_prompt_qualified_symbol_hint(
1787    state: &SidecarState,
1788    prompt: &str,
1789) -> Result<Option<PromptQualifiedSymbolHint>, StatusCode> {
1790    let guard = state.index.read();
1791    let mut qualified_symbol_match: Option<PromptQualifiedSymbolHint> = None;
1792    let mut qualified_symbol_ambiguous = false;
1793
1794    for (path, file) in guard.all_files() {
1795        let Some(module_alias) = prompt_symbol_module_alias(path, &file.language) else {
1796            continue;
1797        };
1798
1799        for symbol in &file.symbols {
1800            let Some(alias) = prompt_qualified_symbol_alias(&module_alias, &symbol.name) else {
1801                continue;
1802            };
1803            if !prompt_contains_exact_alias(prompt, &alias) {
1804                continue;
1805            }
1806
1807            if let Some(existing) = &qualified_symbol_match {
1808                if existing.file_hint.path != path.as_str() || existing.symbol_name != symbol.name {
1809                    qualified_symbol_ambiguous = true;
1810                }
1811            } else {
1812                qualified_symbol_match = Some(PromptQualifiedSymbolHint {
1813                    file_hint: PromptFileHint {
1814                        path: path.to_string(),
1815                        line_hint_alias: Some(alias),
1816                        match_kind: PromptHintMatchKind::QualifiedSymbolAlias,
1817                    },
1818                    symbol_name: symbol.name.clone(),
1819                });
1820            }
1821        }
1822    }
1823
1824    if qualified_symbol_ambiguous {
1825        Ok(None)
1826    } else {
1827        Ok(qualified_symbol_match)
1828    }
1829}
1830
1831fn find_prompt_symbol_hint(
1832    state: &SidecarState,
1833    prompt: &str,
1834) -> Result<Option<String>, StatusCode> {
1835    let guard = state.index.read();
1836    for token in prompt_tokens(prompt) {
1837        if token.len() < 3 || token.contains('/') || token.contains('.') {
1838            continue;
1839        }
1840
1841        let has_match = guard
1842            .all_files()
1843            .any(|(_, file)| file.symbols.iter().any(|symbol| symbol.name == token));
1844        if has_match {
1845            return Ok(Some(token));
1846        }
1847    }
1848
1849    Ok(None)
1850}
1851
1852fn find_prompt_line_hint(prompt: &str, file_hint: Option<&PromptFileHint>) -> Option<u32> {
1853    if let Some(file_hint) = file_hint {
1854        if let Some(line) = find_prompt_path_line_hint(prompt, &file_hint.path) {
1855            return Some(line);
1856        }
1857        if let Some(alias) = &file_hint.line_hint_alias
1858            && let Some(line) = find_prompt_path_line_hint(prompt, alias)
1859        {
1860            return Some(line);
1861        }
1862    }
1863
1864    let tokens = prompt_tokens(prompt);
1865    for window in tokens.windows(2) {
1866        if !window[0].eq_ignore_ascii_case("line") {
1867            continue;
1868        }
1869        if let Ok(line) = window[1].parse::<u32>()
1870            && line > 0
1871        {
1872            return Some(line);
1873        }
1874    }
1875
1876    None
1877}
1878
1879fn find_prompt_path_line_hint(prompt: &str, path: &str) -> Option<u32> {
1880    let prompt_lower = prompt.to_ascii_lowercase();
1881    let needle = format!("{}:", path.to_ascii_lowercase());
1882    let mut search_start = 0;
1883
1884    while let Some(offset) = prompt_lower[search_start..].find(&needle) {
1885        let value_start = search_start + offset + needle.len();
1886        let digits: String = prompt[value_start..]
1887            .chars()
1888            .take_while(|ch| ch.is_ascii_digit())
1889            .collect();
1890        if let Ok(line) = digits.parse::<u32>()
1891            && line > 0
1892        {
1893            return Some(line);
1894        }
1895
1896        search_start = value_start;
1897    }
1898
1899    None
1900}
1901
1902fn prompt_path_without_extension(path: &str) -> Option<String> {
1903    let file_name = std::path::Path::new(path).file_name()?.to_str()?;
1904    let file_stem = std::path::Path::new(path).file_stem()?.to_str()?;
1905    if let Some((parent, _)) = path.rsplit_once('/') {
1906        Some(format!("{parent}/{file_stem}"))
1907    } else if file_name != file_stem {
1908        Some(file_stem.to_string())
1909    } else {
1910        None
1911    }
1912}
1913
1914fn prompt_module_alias(path: &str, language: &LanguageId) -> Option<String> {
1915    let alias = match language {
1916        LanguageId::Rust => {
1917            let stripped = std::path::Path::new(path).strip_prefix("src").ok()?;
1918            let mut components: Vec<String> = stripped
1919                .components()
1920                .filter_map(|component| component.as_os_str().to_str().map(String::from))
1921                .collect();
1922
1923            if let Some(last) = components.last_mut()
1924                && let Some(stem) = std::path::Path::new(last.as_str())
1925                    .file_stem()
1926                    .and_then(|value| value.to_str())
1927            {
1928                *last = stem.to_string();
1929            }
1930
1931            if matches!(
1932                components.last().map(|value| value.as_str()),
1933                Some("lib" | "main" | "mod")
1934            ) {
1935                components.pop();
1936            }
1937
1938            if components.is_empty() {
1939                Some("crate".to_string())
1940            } else {
1941                Some(format!("crate::{}", components.join("::")))
1942            }
1943        }
1944        LanguageId::Python => {
1945            let mut components: Vec<String> = std::path::Path::new(path)
1946                .components()
1947                .filter_map(|component| component.as_os_str().to_str().map(String::from))
1948                .collect();
1949
1950            if let Some(last) = components.last_mut()
1951                && let Some(stem) = std::path::Path::new(last.as_str())
1952                    .file_stem()
1953                    .and_then(|value| value.to_str())
1954            {
1955                *last = stem.to_string();
1956            }
1957
1958            if matches!(
1959                components.last().map(|value| value.as_str()),
1960                Some("__init__")
1961            ) {
1962                components.pop();
1963            }
1964
1965            if components.is_empty() {
1966                None
1967            } else {
1968                Some(components.join("."))
1969            }
1970        }
1971        _ => None,
1972    }?;
1973
1974    if alias.contains("::") || alias.contains('.') {
1975        Some(alias)
1976    } else {
1977        None
1978    }
1979}
1980
1981fn prompt_file_module_alias(path: &str, language: &LanguageId) -> Option<String> {
1982    if let Some(alias) = prompt_module_alias(path, language) {
1983        return Some(alias);
1984    }
1985
1986    let alias = match language {
1987        LanguageId::JavaScript | LanguageId::TypeScript => {
1988            let mut components: Vec<String> = std::path::Path::new(path)
1989                .components()
1990                .filter_map(|component| component.as_os_str().to_str().map(String::from))
1991                .collect();
1992
1993            if let Some(last) = components.last_mut()
1994                && let Some(stem) = std::path::Path::new(last.as_str())
1995                    .file_stem()
1996                    .and_then(|value| value.to_str())
1997            {
1998                *last = stem.to_string();
1999            }
2000
2001            if matches!(components.last().map(|value| value.as_str()), Some("index")) {
2002                components.pop();
2003            }
2004
2005            if components.is_empty() {
2006                None
2007            } else {
2008                Some(components.join("/"))
2009            }
2010        }
2011        _ => None,
2012    }?;
2013
2014    if alias.contains('/') {
2015        Some(alias)
2016    } else {
2017        None
2018    }
2019}
2020
2021fn prompt_symbol_module_alias(path: &str, language: &LanguageId) -> Option<String> {
2022    prompt_file_module_alias(path, language)
2023}
2024
2025fn prompt_qualified_symbol_alias(module_alias: &str, symbol_name: &str) -> Option<String> {
2026    let separator = if module_alias.contains("::") {
2027        "::"
2028    } else if module_alias.contains('.') {
2029        "."
2030    } else if module_alias.contains('/') {
2031        "/"
2032    } else {
2033        return None;
2034    };
2035
2036    Some(format!("{module_alias}{separator}{symbol_name}"))
2037}
2038
2039fn prompt_contains_exact_alias(prompt: &str, alias: &str) -> bool {
2040    let prompt_lower = prompt.to_ascii_lowercase();
2041    let alias_lower = alias.to_ascii_lowercase();
2042    let prompt_bytes = prompt_lower.as_bytes();
2043    let alias_bytes = alias_lower.as_bytes();
2044    let mut search_start = 0;
2045
2046    while let Some(offset) = prompt_lower[search_start..].find(&alias_lower) {
2047        let start = search_start + offset;
2048        let end = start + alias_bytes.len();
2049
2050        let prev_ok =
2051            start == 0 || !matches!(prompt_bytes[start - 1], b'a'..=b'z' | b'0'..=b'9' | b'_');
2052
2053        let next_ok = if end >= prompt_bytes.len() {
2054            true
2055        } else {
2056            match prompt_bytes[end] {
2057                b':' => prompt_bytes
2058                    .get(end + 1)
2059                    .map(|byte| byte.is_ascii_digit())
2060                    .unwrap_or(false),
2061                b'.' | b'/' => false,
2062                byte => !matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_'),
2063            }
2064        };
2065
2066        if prev_ok && next_ok {
2067            return true;
2068        }
2069
2070        search_start = start + 1;
2071    }
2072
2073    false
2074}
2075
2076fn prompt_tokens(prompt: &str) -> Vec<String> {
2077    prompt
2078        .split(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_' || ch == '/' || ch == '.'))
2079        .filter(|token| !token.is_empty())
2080        .map(ToString::to_string)
2081        .collect()
2082}
2083
2084fn prompt_requests_repo_map(prompt: &str) -> bool {
2085    let lower = prompt.to_ascii_lowercase();
2086    [
2087        "architecture",
2088        "codebase",
2089        "map",
2090        "overview",
2091        "repo",
2092        "repository",
2093        "structure",
2094    ]
2095    .iter()
2096    .any(|term| lower.contains(term))
2097}
2098
2099// ---------------------------------------------------------------------------
2100// Unit tests
2101// ---------------------------------------------------------------------------
2102
2103#[cfg(test)]
2104mod tests {
2105    use super::*;
2106    use std::collections::HashMap;
2107    use std::sync::Arc;
2108    use std::time::{Duration, Instant, SystemTime};
2109
2110    use parking_lot::RwLock;
2111
2112    use crate::domain::{LanguageId, ReferenceKind, ReferenceRecord, SymbolKind, SymbolRecord};
2113    use crate::live_index::store::{CircuitBreakerState, IndexedFile, LiveIndex, ParseStatus};
2114    use crate::sidecar::{SidecarState, SymbolSnapshot, TokenStats};
2115
2116    // -----------------------------------------------------------------------
2117    // Test helper: minimal LiveIndex with known contents
2118    // -----------------------------------------------------------------------
2119
2120    fn make_symbol(name: &str, kind: SymbolKind, start: u32, end: u32) -> SymbolRecord {
2121        let byte_range = (0, 10);
2122        SymbolRecord {
2123            name: name.to_string(),
2124            kind,
2125            depth: 0,
2126            sort_order: 0,
2127            byte_range,
2128            item_byte_range: Some(byte_range),
2129            line_range: (start, end),
2130            doc_byte_range: None,
2131        }
2132    }
2133
2134    fn make_reference(name: &str, kind: ReferenceKind, line: u32) -> ReferenceRecord {
2135        ReferenceRecord {
2136            name: name.to_string(),
2137            qualified_name: None,
2138            kind,
2139            byte_range: (100, 110),
2140            line_range: (line, line),
2141            enclosing_symbol_index: None,
2142        }
2143    }
2144
2145    fn make_indexed_file(
2146        path: &str,
2147        symbols: Vec<SymbolRecord>,
2148        references: Vec<ReferenceRecord>,
2149        status: ParseStatus,
2150    ) -> IndexedFile {
2151        IndexedFile {
2152            relative_path: path.to_string(),
2153            language: LanguageId::Rust,
2154            classification: crate::domain::FileClassification::for_code_path(path),
2155            content: b"fn test() {}".to_vec(),
2156            symbols,
2157            parse_status: status,
2158            parse_diagnostic: None,
2159            byte_len: 12,
2160            content_hash: "abc".to_string(),
2161            references,
2162            alias_map: HashMap::new(),
2163            mtime_secs: 0,
2164        }
2165    }
2166
2167    fn build_shared_index(
2168        files: Vec<(&str, IndexedFile)>,
2169    ) -> crate::live_index::store::SharedIndex {
2170        use crate::live_index::trigram::TrigramIndex;
2171        let files_map: HashMap<String, std::sync::Arc<IndexedFile>> = files
2172            .into_iter()
2173            .map(|(p, f)| (p.to_string(), std::sync::Arc::new(f)))
2174            .collect();
2175        let trigram_index = TrigramIndex::build_from_files(&files_map);
2176        let mut index = LiveIndex {
2177            files: files_map,
2178            loaded_at: Instant::now(),
2179            loaded_at_system: SystemTime::now(),
2180            load_duration: Duration::from_millis(10),
2181            cb_state: CircuitBreakerState::new(0.20),
2182            is_empty: false,
2183            load_source: crate::live_index::store::IndexLoadSource::FreshLoad,
2184            snapshot_verify_state: crate::live_index::store::SnapshotVerifyState::NotNeeded,
2185            reverse_index: HashMap::new(),
2186            files_by_basename: HashMap::new(),
2187            files_by_dir_component: HashMap::new(),
2188            trigram_index,
2189            gitignore: None,
2190            skipped_files: Vec::new(),
2191            local_empty_reason: std::sync::Arc::new(parking_lot::RwLock::new(None)),
2192        };
2193        index.rebuild_reverse_index();
2194        index.rebuild_path_indices();
2195        crate::live_index::SharedIndexHandle::shared(index)
2196    }
2197
2198    /// Build a SidecarState wrapping a SharedIndex for use in tests.
2199    fn make_state(files: Vec<(&str, IndexedFile)>) -> SidecarState {
2200        SidecarState {
2201            index: build_shared_index(files),
2202            token_stats: TokenStats::new(),
2203            repo_root: None,
2204            symbol_cache: Arc::new(RwLock::new(HashMap::new())),
2205        }
2206    }
2207
2208    fn make_state_with_root(
2209        files: Vec<(&str, IndexedFile)>,
2210        repo_root: std::path::PathBuf,
2211    ) -> SidecarState {
2212        SidecarState {
2213            index: build_shared_index(files),
2214            token_stats: TokenStats::new(),
2215            repo_root: Some(repo_root),
2216            symbol_cache: Arc::new(RwLock::new(HashMap::new())),
2217        }
2218    }
2219
2220    #[test]
2221    fn freshen_sidecar_path_if_stale_generation_mismatch_preserves_valid_file() {
2222        let project_a = tempfile::tempdir().unwrap();
2223        let project_b = tempfile::tempdir().unwrap();
2224        std::fs::create_dir_all(project_a.path().join("src")).unwrap();
2225        std::fs::create_dir_all(project_b.path().join("src")).unwrap();
2226        std::fs::write(project_a.path().join("src/a.rs"), "pub fn a() {}\n").unwrap();
2227        std::fs::write(project_b.path().join("src/b.rs"), "pub fn b() {}\n").unwrap();
2228
2229        let index = LiveIndex::load(project_a.path()).unwrap();
2230        let stale_gen = index.current_project_generation();
2231        index.reload(project_b.path()).unwrap();
2232        let state = SidecarState {
2233            index,
2234            token_stats: TokenStats::new(),
2235            repo_root: Some(project_a.path().to_path_buf()),
2236            symbol_cache: Arc::new(RwLock::new(HashMap::new())),
2237        };
2238
2239        let source_authority =
2240            freshen_sidecar_path_if_stale_at_generation(&state, "src/b.rs", stale_gen);
2241
2242        assert!(matches!(
2243            source_authority,
2244            ContextSourceAuthority::CurrentIndex
2245        ));
2246        assert!(state.index.read().get_file("src/b.rs").is_some());
2247    }
2248
2249    // -----------------------------------------------------------------------
2250    // health_handler
2251    // -----------------------------------------------------------------------
2252
2253    #[tokio::test]
2254    async fn test_health_handler_returns_counts() {
2255        let f1 = make_indexed_file(
2256            "src/main.rs",
2257            vec![make_symbol("main", SymbolKind::Function, 1, 10)],
2258            vec![],
2259            ParseStatus::Parsed,
2260        );
2261        let f2 = make_indexed_file(
2262            "src/lib.rs",
2263            vec![
2264                make_symbol("foo", SymbolKind::Function, 1, 5),
2265                make_symbol("bar", SymbolKind::Function, 7, 12),
2266            ],
2267            vec![],
2268            ParseStatus::Parsed,
2269        );
2270        let state = make_state(vec![("src/main.rs", f1), ("src/lib.rs", f2)]);
2271
2272        let result = health_handler(State(state)).await.unwrap();
2273        let body = result.0;
2274        assert_eq!(body.file_count, 2, "health should report 2 files");
2275        assert_eq!(body.symbol_count, 3, "health should report 3 symbols");
2276        assert!(
2277            body.index_state.contains("Ready"),
2278            "index_state should include Ready"
2279        );
2280    }
2281
2282    #[tokio::test]
2283    async fn test_health_handler_empty_index() {
2284        let state = make_state(vec![]);
2285        let result = health_handler(State(state)).await.unwrap();
2286        let body = result.0;
2287        assert_eq!(body.file_count, 0);
2288        assert_eq!(body.symbol_count, 0);
2289    }
2290
2291    // -----------------------------------------------------------------------
2292    // outline_handler
2293    // -----------------------------------------------------------------------
2294
2295    #[tokio::test]
2296    async fn test_outline_handler_returns_formatted_text() {
2297        let file = make_indexed_file(
2298            "src/foo.rs",
2299            vec![
2300                make_symbol("alpha", SymbolKind::Function, 1, 5),
2301                make_symbol("Beta", SymbolKind::Struct, 7, 10),
2302            ],
2303            vec![],
2304            ParseStatus::Parsed,
2305        );
2306        let state = make_state(vec![("src/foo.rs", file)]);
2307
2308        let params = OutlineParams {
2309            path: "src/foo.rs".to_string(),
2310            max_tokens: None,
2311            sections: None,
2312        };
2313        let result = outline_handler(State(state), Query(params)).await.unwrap();
2314        assert!(
2315            result.contains("alpha"),
2316            "outline should contain symbol name 'alpha'"
2317        );
2318        assert!(
2319            result.contains("Beta"),
2320            "outline should contain symbol name 'Beta'"
2321        );
2322        assert!(
2323            result.contains("src/foo.rs"),
2324            "outline should contain file path"
2325        );
2326        assert!(
2327            result.contains("tokens saved"),
2328            "outline should have token savings footer"
2329        );
2330        assert!(result.contains("Match type: exact"), "got: {result}");
2331        assert!(
2332            result.contains("Source authority: current index"),
2333            "got: {result}"
2334        );
2335        assert!(result.contains("Parse state: parsed"), "got: {result}");
2336        assert!(result.contains("Completeness: full"), "got: {result}");
2337        assert!(
2338            result.contains("Scope: path `src/foo.rs`; all sections"),
2339            "got: {result}"
2340        );
2341        assert!(
2342            result.contains("Evidence: file anchor `src/foo.rs`"),
2343            "got: {result}"
2344        );
2345    }
2346
2347    #[tokio::test]
2348    async fn test_outline_handler_not_found_for_missing_file() {
2349        let state = make_state(vec![]);
2350        let params = OutlineParams {
2351            path: "nonexistent.rs".to_string(),
2352            max_tokens: None,
2353            sections: None,
2354        };
2355        let err = outline_handler(State(state), Query(params))
2356            .await
2357            .unwrap_err();
2358        assert_eq!(err, StatusCode::NOT_FOUND);
2359    }
2360
2361    #[tokio::test]
2362    async fn test_outline_handler_budget_enforced() {
2363        // Create a file with many symbols to trigger truncation.
2364        let symbols: Vec<SymbolRecord> = (0..50)
2365            .map(|i| {
2366                make_symbol(
2367                    &format!("symbol_{:04}", i),
2368                    SymbolKind::Function,
2369                    i * 2,
2370                    i * 2 + 1,
2371                )
2372            })
2373            .collect();
2374        let file = make_indexed_file("src/big.rs", symbols, vec![], ParseStatus::Parsed);
2375        let state = make_state(vec![("src/big.rs", file)]);
2376
2377        let params = OutlineParams {
2378            path: "src/big.rs".to_string(),
2379            max_tokens: Some(10), // tiny budget to force truncation
2380            sections: None,
2381        };
2382        let result = outline_handler(State(state), Query(params)).await.unwrap();
2383        // With 10-token (40 byte) budget, only the header fits. Truncation suffix should appear.
2384        assert!(
2385            result.contains("truncated") || result.len() < 500,
2386            "result should be truncated or short: {}",
2387            result.len()
2388        );
2389        assert!(
2390            result.contains("Completeness: budget-limited"),
2391            "got: {result}"
2392        );
2393    }
2394
2395    #[tokio::test]
2396    async fn test_outline_handler_reports_disk_refreshed_authority_for_stale_exact_path() {
2397        let tmp = tempfile::TempDir::new().unwrap();
2398        let src_dir = tmp.path().join("src");
2399        std::fs::create_dir_all(&src_dir).unwrap();
2400        let file_path = src_dir.join("main.rs");
2401        std::fs::write(&file_path, "fn refreshed() {}\n").unwrap();
2402
2403        let stale_file = make_indexed_file(
2404            "src/main.rs",
2405            vec![make_symbol("stale", SymbolKind::Function, 1, 1)],
2406            vec![],
2407            ParseStatus::Parsed,
2408        );
2409        let state =
2410            make_state_with_root(vec![("src/main.rs", stale_file)], tmp.path().to_path_buf());
2411
2412        let params = OutlineParams {
2413            path: "src/main.rs".to_string(),
2414            max_tokens: None,
2415            sections: None,
2416        };
2417        let result = outline_handler(State(state), Query(params)).await.unwrap();
2418
2419        assert!(
2420            result.contains("Source authority: disk-refreshed"),
2421            "got: {result}"
2422        );
2423        assert!(result.contains("refreshed"), "got: {result}");
2424    }
2425
2426    #[tokio::test]
2427    async fn test_outline_handler_records_token_stats() {
2428        let file = make_indexed_file(
2429            "src/foo.rs",
2430            vec![make_symbol("alpha", SymbolKind::Function, 1, 5)],
2431            vec![],
2432            ParseStatus::Parsed,
2433        );
2434        let state = make_state(vec![("src/foo.rs", file)]);
2435        let stats = Arc::clone(&state.token_stats);
2436
2437        let params = OutlineParams {
2438            path: "src/foo.rs".to_string(),
2439            max_tokens: None,
2440            sections: None,
2441        };
2442        let _ = outline_handler(State(state), Query(params)).await.unwrap();
2443        assert_eq!(
2444            stats.summary().read_fires,
2445            1,
2446            "read fires should be incremented"
2447        );
2448    }
2449
2450    // -----------------------------------------------------------------------
2451    // impact_handler — new_file path
2452    // -----------------------------------------------------------------------
2453
2454    #[tokio::test]
2455    async fn test_impact_handler_new_file_returns_language_and_symbols() {
2456        use std::io::Write;
2457        use tempfile::TempDir;
2458
2459        let tmp = TempDir::new().unwrap();
2460        let rs_path = tmp.path().join("new_file.rs");
2461        let mut f = std::fs::File::create(&rs_path).unwrap();
2462        writeln!(f, "fn greet() {{}}").unwrap();
2463        writeln!(f, "struct Config {{}}").unwrap();
2464        drop(f);
2465
2466        // Change cwd to tmp dir so the handler can find the file.
2467        let state = make_state(vec![]);
2468
2469        // We'll call the handler with a relative path that exists when cwd = tmp.
2470        // Use absolute path directly to sidestep cwd issues.
2471        let abs_path_str = rs_path.to_string_lossy().to_string();
2472        let params = ImpactParams {
2473            path: abs_path_str.clone(),
2474            new_file: Some(true),
2475        };
2476
2477        // The handler uses cwd.join(path), so with abs path it resolves correctly.
2478        let result = impact_handler(State(state), Query(params)).await;
2479        // It may fail if the extension detection doesn't work for absolute paths, but
2480        // the basic test is that it doesn't panic.
2481        // The result depends on file system state.
2482        let _ = result; // just verify no panic
2483    }
2484
2485    // -----------------------------------------------------------------------
2486    // impact_handler — edit path
2487    // -----------------------------------------------------------------------
2488
2489    #[tokio::test]
2490    async fn test_impact_handler_edit_returns_formatted_text() {
2491        let file = make_indexed_file(
2492            "src/db.rs",
2493            vec![make_symbol("connect", SymbolKind::Function, 1, 10)],
2494            vec![],
2495            ParseStatus::Parsed,
2496        );
2497        let state = make_state(vec![("src/db.rs", file)]);
2498
2499        // Seed the symbol cache with pre-edit state.
2500        {
2501            let mut cache = state.symbol_cache.write();
2502            cache.insert(
2503                "src/db.rs".to_string(),
2504                vec![SymbolSnapshot {
2505                    name: "connect".to_string(),
2506                    kind: "function".to_string(),
2507                    line_range: (1, 5), // different range = "Changed"
2508                    byte_range: (0, 50),
2509                }],
2510            );
2511        }
2512
2513        let params = ImpactParams {
2514            path: "src/db.rs".to_string(),
2515            new_file: None,
2516        };
2517
2518        // The handler will try to read src/db.rs from disk (cwd). Since the file
2519        // doesn't exist on disk in this test, the handler should return Ok with a
2520        // "not readable" message and preserve the index instead of destroying it.
2521        let result = impact_handler(State(state), Query(params)).await;
2522        assert!(
2523            result.is_ok(),
2524            "impact_handler should return Ok even if file missing from disk"
2525        );
2526        let text = result.unwrap();
2527        assert!(
2528            text.contains("removed from index") || text.contains("not found on disk"),
2529            "should indicate file was removed from index; got: {text}"
2530        );
2531    }
2532
2533    /// When the watcher purges the index entry before analyze_file_impact
2534    /// runs, there is no pre-count to report. The response must not claim
2535    /// `Previously had 0 symbols` as if zero were a measured pre-state.
2536    #[tokio::test]
2537    async fn test_impact_handler_edit_honest_wording_when_index_already_purged() {
2538        // Index is empty; the caller asks about a path the watcher already
2539        // removed (or which never existed). The handler should acknowledge
2540        // the absence of a prior record rather than report "0 symbols".
2541        let state = make_state(vec![]);
2542
2543        let params = ImpactParams {
2544            path: "src/ghost.rs".to_string(),
2545            new_file: None,
2546        };
2547        let result = impact_handler(State(state), Query(params)).await;
2548        assert!(result.is_ok(), "handler must tolerate the watcher race");
2549        let text = result.unwrap();
2550        assert!(
2551            text.contains("no index record remains"),
2552            "should flag the purged-index case explicitly; got: {text}"
2553        );
2554        assert!(
2555            !text.contains("Previously had 0 symbols"),
2556            "must not claim a pre-count that was never observed; got: {text}"
2557        );
2558    }
2559
2560    /// Helper: SymbolRecord with explicit depth and byte_range, needed for
2561    /// parent-impl-type tests that the simpler `make_symbol` can't express.
2562    fn make_symbol_with_range(
2563        name: &str,
2564        kind: SymbolKind,
2565        depth: u32,
2566        line_range: (u32, u32),
2567        byte_range: (u32, u32),
2568    ) -> SymbolRecord {
2569        SymbolRecord {
2570            name: name.to_string(),
2571            kind,
2572            depth,
2573            sort_order: 0,
2574            byte_range,
2575            item_byte_range: Some(byte_range),
2576            line_range,
2577            doc_byte_range: None,
2578        }
2579    }
2580
2581    #[test]
2582    fn test_find_record_matching_snapshot_matches_on_name_kind_and_byte_range() {
2583        let impl_record = make_symbol_with_range("impl Foo", SymbolKind::Impl, 0, (1, 5), (0, 200));
2584        let new_method = make_symbol_with_range("new", SymbolKind::Function, 1, (2, 3), (50, 80));
2585        let file = make_indexed_file(
2586            "src/foo.rs",
2587            vec![impl_record, new_method.clone()],
2588            vec![],
2589            ParseStatus::Parsed,
2590        );
2591
2592        // Matching snapshot: all three fields agree → Some(record).
2593        let snap = SymbolSnapshot {
2594            name: "new".to_string(),
2595            kind: new_method.kind.to_string(),
2596            line_range: new_method.line_range,
2597            byte_range: new_method.byte_range,
2598        };
2599        let hit = find_record_matching_snapshot(&file, &snap);
2600        assert!(hit.is_some(), "exact match must resolve");
2601
2602        // Name-only collision: different byte_range → None. This is what
2603        // prevents `MathMachine::new` from matching `Foo::new` elsewhere.
2604        let wrong_range = SymbolSnapshot {
2605            name: "new".to_string(),
2606            kind: new_method.kind.to_string(),
2607            line_range: new_method.line_range,
2608            byte_range: (999, 1000),
2609        };
2610        assert!(
2611            find_record_matching_snapshot(&file, &wrong_range).is_none(),
2612            "byte_range mismatch must not resolve"
2613        );
2614
2615        // Name + range match but wrong kind → None.
2616        let wrong_kind = SymbolSnapshot {
2617            name: "new".to_string(),
2618            kind: SymbolKind::Struct.to_string(),
2619            line_range: new_method.line_range,
2620            byte_range: new_method.byte_range,
2621        };
2622        assert!(
2623            find_record_matching_snapshot(&file, &wrong_kind).is_none(),
2624            "kind mismatch must not resolve"
2625        );
2626    }
2627
2628    /// End-to-end: when analyze_file_impact reports callers of a changed
2629    /// method inside `impl Foo`, it must exclude files that only reference
2630    /// an unrelated same-named method (e.g. `Bar::new`). The fix type-scopes
2631    /// the caller list using find_parent_impl_type + file-presence filter.
2632    #[tokio::test]
2633    async fn test_impact_handler_type_scopes_caller_review() {
2634        use std::io::Write;
2635        use tempfile::TempDir;
2636
2637        let tmp = TempDir::new().unwrap();
2638        let src_dir = tmp.path().join("src");
2639        std::fs::create_dir_all(&src_dir).unwrap();
2640
2641        // Write the post-edit file content. The parser must produce an
2642        // Impl symbol and a nested `new` method so find_parent_impl_type
2643        // returns Some("Foo").
2644        let foo_path = src_dir.join("foo.rs");
2645        let mut f = std::fs::File::create(&foo_path).unwrap();
2646        writeln!(f, "pub struct Foo;").unwrap();
2647        writeln!(f, "impl Foo {{").unwrap();
2648        writeln!(f, "    pub fn new() -> Self {{ Self }}").unwrap();
2649        writeln!(f, "}}").unwrap();
2650        drop(f);
2651
2652        // Pre-edit snapshot: `new` existed at a different byte_range so the
2653        // diff flags it as Changed rather than unchanged.
2654        let pre_impl = make_symbol_with_range("impl Foo", SymbolKind::Impl, 0, (1, 1), (0, 5));
2655        let pre_new = make_symbol_with_range("new", SymbolKind::Function, 1, (1, 1), (10, 20));
2656        let pre_file = make_indexed_file(
2657            "src/foo.rs",
2658            vec![pre_impl, pre_new],
2659            vec![],
2660            ParseStatus::Parsed,
2661        );
2662
2663        // A file that references `Foo` AND `new` — legitimate caller.
2664        let uses_foo = make_indexed_file(
2665            "src/uses_foo.rs",
2666            vec![],
2667            vec![
2668                make_reference("Foo", ReferenceKind::TypeUsage, 1),
2669                make_reference("new", ReferenceKind::Call, 2),
2670            ],
2671            ParseStatus::Parsed,
2672        );
2673
2674        // A file that references `new` but NOT `Foo` — must be filtered out.
2675        // Simulates the `MathMachine::new` vs other-type `::new` false positive.
2676        let uses_other = make_indexed_file(
2677            "src/uses_bar.rs",
2678            vec![],
2679            vec![
2680                make_reference("Bar", ReferenceKind::TypeUsage, 1),
2681                make_reference("new", ReferenceKind::Call, 5),
2682            ],
2683            ParseStatus::Parsed,
2684        );
2685
2686        let state = make_state_with_root(
2687            vec![
2688                ("src/foo.rs", pre_file),
2689                ("src/uses_foo.rs", uses_foo),
2690                ("src/uses_bar.rs", uses_other),
2691            ],
2692            tmp.path().to_path_buf(),
2693        );
2694
2695        let params = ImpactParams {
2696            path: "src/foo.rs".to_string(),
2697            new_file: None,
2698        };
2699        let result = impact_handler(State(state), Query(params))
2700            .await
2701            .expect("handler returns Ok");
2702
2703        // Sanity: `new` is reported as Changed (or Added — parse may shift
2704        // byte ranges enough to confuse the diff, which is fine for this
2705        // test — what matters is that the caller-review block renders and
2706        // is type-scoped).
2707        assert!(
2708            result.contains("Callers of new()") || !result.contains("Callers to review:"),
2709            "when caller review renders, the symbol name header must appear; got:\n{result}"
2710        );
2711
2712        if result.contains("Callers to review:") {
2713            assert!(
2714                result.contains("src/uses_foo.rs"),
2715                "caller in a file that references the parent type must be kept; got:\n{result}"
2716            );
2717            assert!(
2718                !result.contains("src/uses_bar.rs"),
2719                "caller in a file that does NOT reference the parent type must be filtered out; got:\n{result}"
2720            );
2721        }
2722    }
2723
2724    /// Proves that analyze_file_impact removes the file from the index when
2725    /// it cannot be read from disk (deleted externally).
2726    #[tokio::test]
2727    async fn test_impact_handler_edit_preserves_index_when_file_unreadable() {
2728        let file = make_indexed_file(
2729            "src/db.rs",
2730            vec![make_symbol("connect", SymbolKind::Function, 1, 10)],
2731            vec![],
2732            ParseStatus::Parsed,
2733        );
2734        let state = make_state(vec![("src/db.rs", file)]);
2735
2736        let params = ImpactParams {
2737            path: "src/db.rs".to_string(),
2738            new_file: None,
2739        };
2740
2741        // File doesn't exist on disk — impact should remove it from the index.
2742        let result = impact_handler(State(state.clone()), Query(params)).await;
2743        assert!(result.is_ok(), "should return Ok, got: {result:?}");
2744
2745        // Verify the file was removed from the index.
2746        let guard = state.index.read();
2747        assert!(
2748            guard.get_file("src/db.rs").is_none(),
2749            "deleted file should be removed from index"
2750        );
2751    }
2752
2753    // -----------------------------------------------------------------------
2754    // symbol_context_handler
2755    // -----------------------------------------------------------------------
2756
2757    #[tokio::test]
2758    async fn test_symbol_context_handler_returns_formatted_text() {
2759        let f = make_indexed_file(
2760            "src/main.rs",
2761            vec![],
2762            vec![make_reference("process", ReferenceKind::Call, 5)],
2763            ParseStatus::Parsed,
2764        );
2765        let state = make_state(vec![("src/main.rs", f)]);
2766
2767        let params = SymbolContextParams {
2768            name: "process".to_string(),
2769            file: None,
2770            path: None,
2771            symbol_kind: None,
2772            symbol_line: None,
2773        };
2774        let result = symbol_context_handler(State(state), Query(params))
2775            .await
2776            .unwrap();
2777        assert!(result.contains("src/main.rs"), "should contain the file");
2778        assert!(result.contains("line 5"), "should show line number");
2779        assert!(result.contains("tokens saved"), "should have footer");
2780        assert!(result.contains("Match type: heuristic"), "got: {result}");
2781        assert!(
2782            result.contains("Source authority: current index"),
2783            "got: {result}"
2784        );
2785        assert!(result.contains("Parse state: parsed"), "got: {result}");
2786        assert!(result.contains("Completeness: full"), "got: {result}");
2787        assert!(
2788            result.contains("Scope: repo-wide symbol token `process`"),
2789            "got: {result}"
2790        );
2791        assert!(
2792            result.contains("Evidence: symbol token `process` anchored at src/main.rs:5"),
2793            "got: {result}"
2794        );
2795    }
2796
2797    #[tokio::test]
2798    async fn test_symbol_context_handler_caps_at_10() {
2799        // Create 20 files each with one reference to "target".
2800        let files: Vec<(&str, IndexedFile)> = (0..20usize)
2801            .map(|i| {
2802                let path = Box::leak(format!("src/f{i}.rs").into_boxed_str()) as &'static str;
2803                let file = make_indexed_file(
2804                    path,
2805                    vec![],
2806                    vec![make_reference("target", ReferenceKind::Call, 1)],
2807                    ParseStatus::Parsed,
2808                );
2809                (path, file)
2810            })
2811            .collect();
2812        let state = make_state(files);
2813
2814        let params = SymbolContextParams {
2815            name: "target".to_string(),
2816            file: None,
2817            path: None,
2818            symbol_kind: None,
2819            symbol_line: None,
2820        };
2821        let result = symbol_context_handler(State(state), Query(params))
2822            .await
2823            .unwrap();
2824        // Should show at most 10 matches (either via our cap-at-10 note, or via budget truncation).
2825        // Count the number of "line 1" occurrences to verify we don't show more than 10.
2826        let match_count = result.matches("line 1").count();
2827        assert!(
2828            match_count <= 10,
2829            "should show at most 10 matches, got {}: {}",
2830            match_count,
2831            result
2832        );
2833        // Should indicate there are more matches (via "showing" or "truncated").
2834        assert!(
2835            result.contains("showing") || result.contains("truncated"),
2836            "should indicate truncation: {}",
2837            result
2838        );
2839        assert!(result.contains("Completeness: truncated"), "got: {result}");
2840    }
2841
2842    #[tokio::test]
2843    async fn test_symbol_context_handler_exact_selector_excludes_unrelated_same_name_hits() {
2844        let target = make_indexed_file(
2845            "src/db.rs",
2846            vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
2847            vec![],
2848            ParseStatus::Parsed,
2849        );
2850        let dependent = IndexedFile {
2851            relative_path: "src/service.rs".to_string(),
2852            language: LanguageId::Rust,
2853            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
2854            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
2855            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
2856            parse_status: ParseStatus::Parsed,
2857            parse_diagnostic: None,
2858            byte_len: 46,
2859            content_hash: "abc".to_string(),
2860            references: vec![
2861                ReferenceRecord {
2862                    name: "db".to_string(),
2863                    qualified_name: Some("crate::db".to_string()),
2864                    kind: ReferenceKind::Import,
2865                    byte_range: (0, 6),
2866                    line_range: (0, 0),
2867                    enclosing_symbol_index: Some(0),
2868                },
2869                ReferenceRecord {
2870                    name: "connect".to_string(),
2871                    qualified_name: Some("crate::db::connect".to_string()),
2872                    kind: ReferenceKind::Call,
2873                    byte_range: (10, 16),
2874                    line_range: (1, 1),
2875                    enclosing_symbol_index: Some(0),
2876                },
2877            ],
2878            alias_map: HashMap::new(),
2879            mtime_secs: 0,
2880        };
2881        let unrelated = make_indexed_file(
2882            "src/other.rs",
2883            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
2884            vec![make_reference("connect", ReferenceKind::Call, 1)],
2885            ParseStatus::Parsed,
2886        );
2887        let state = make_state(vec![
2888            ("src/db.rs", target),
2889            ("src/service.rs", dependent),
2890            ("src/other.rs", unrelated),
2891        ]);
2892
2893        let params = SymbolContextParams {
2894            name: "connect".to_string(),
2895            file: None,
2896            path: Some("src/db.rs".to_string()),
2897            symbol_kind: Some("fn".to_string()),
2898            symbol_line: Some(2),
2899        };
2900        let result = symbol_context_handler(State(state), Query(params))
2901            .await
2902            .unwrap();
2903
2904        assert!(result.contains("src/service.rs"), "got: {result}");
2905        assert!(!result.contains("src/other.rs"), "got: {result}");
2906    }
2907
2908    #[tokio::test]
2909    async fn test_symbol_context_handler_exact_selector_requires_line_for_ambiguous_symbol() {
2910        let target = make_indexed_file(
2911            "src/db.rs",
2912            vec![
2913                make_symbol("connect", SymbolKind::Function, 1, 1),
2914                make_symbol("connect", SymbolKind::Function, 2, 2),
2915            ],
2916            vec![],
2917            ParseStatus::Parsed,
2918        );
2919        let state = make_state(vec![("src/db.rs", target)]);
2920
2921        let params = SymbolContextParams {
2922            name: "connect".to_string(),
2923            file: None,
2924            path: Some("src/db.rs".to_string()),
2925            symbol_kind: Some("fn".to_string()),
2926            symbol_line: None,
2927        };
2928        let result = symbol_context_handler(State(state), Query(params))
2929            .await
2930            .unwrap();
2931
2932        assert!(
2933            result.contains("Ambiguous symbol selector"),
2934            "got: {result}"
2935        );
2936        assert!(result.contains("1"), "got: {result}");
2937        assert!(result.contains("2"), "got: {result}");
2938    }
2939
2940    // -----------------------------------------------------------------------
2941    // repo_map_handler
2942    // -----------------------------------------------------------------------
2943
2944    #[tokio::test]
2945    async fn test_repo_map_handler_returns_formatted_tree() {
2946        let f1 = make_indexed_file(
2947            "src/main.rs",
2948            vec![make_symbol("x", SymbolKind::Function, 1, 3)],
2949            vec![],
2950            ParseStatus::Parsed,
2951        );
2952        let f2 = make_indexed_file(
2953            "src/lib.rs",
2954            vec![],
2955            vec![],
2956            ParseStatus::Failed {
2957                error: "oops".to_string(),
2958            },
2959        );
2960        let state = make_state(vec![("src/main.rs", f1), ("src/lib.rs", f2)]);
2961
2962        let result = repo_map_handler(State(state)).await.unwrap();
2963        assert!(result.contains("files"), "should mention file count");
2964        assert!(result.contains("symbols"), "should mention symbol count");
2965        assert!(result.contains("src"), "should show directory");
2966    }
2967
2968    #[tokio::test]
2969    async fn test_repo_map_handler_empty_index() {
2970        let state = make_state(vec![]);
2971        let result = repo_map_handler(State(state)).await.unwrap();
2972        assert!(
2973            result.contains("0 files"),
2974            "empty index should show 0 files"
2975        );
2976    }
2977
2978    #[test]
2979    fn test_is_intra_workspace_path_rejects_absolute_paths() {
2980        assert!(is_intra_workspace_path("src/main.rs"));
2981        assert!(is_intra_workspace_path("tests/fixtures/foo.rs"));
2982        // Windows drive-letter paths from other indexed repos.
2983        assert!(!is_intra_workspace_path(
2984            "C:\\AI_STUFF\\PROGRAMMING\\octogent\\apps\\api\\tests\\hookDrivenBootstrap.test.ts"
2985        ));
2986        // POSIX absolute paths.
2987        assert!(!is_intra_workspace_path("/usr/local/project/src/main.rs"));
2988    }
2989
2990    #[tokio::test]
2991    async fn test_repo_map_excludes_foreign_workspace_paths_from_key_types() {
2992        let local = make_indexed_file(
2993            "src/local_type.rs",
2994            vec![make_symbol("LocalThing", SymbolKind::Struct, 1, 5)],
2995            vec![],
2996            ParseStatus::Parsed,
2997        );
2998        let foreign_windows = make_indexed_file(
2999            "C:\\AI_STUFF\\PROGRAMMING\\otherrepo\\src\\ForeignType.ts",
3000            vec![make_symbol("ForeignWindows", SymbolKind::Class, 1, 5)],
3001            vec![],
3002            ParseStatus::Parsed,
3003        );
3004        let foreign_posix = make_indexed_file(
3005            "/home/someone/otherrepo/src/foreign.rs",
3006            vec![make_symbol("ForeignPosix", SymbolKind::Struct, 1, 5)],
3007            vec![],
3008            ParseStatus::Parsed,
3009        );
3010        let state = make_state(vec![
3011            ("src/local_type.rs", local),
3012            (
3013                "C:\\AI_STUFF\\PROGRAMMING\\otherrepo\\src\\ForeignType.ts",
3014                foreign_windows,
3015            ),
3016            ("/home/someone/otherrepo/src/foreign.rs", foreign_posix),
3017        ]);
3018
3019        let result = repo_map_handler(State(state)).await.unwrap();
3020        assert!(
3021            result.contains("LocalThing"),
3022            "key types should include the local symbol; got:\n{result}"
3023        );
3024        assert!(
3025            !result.contains("ForeignWindows"),
3026            "key types must not leak Windows drive-letter paths from other workspaces; got:\n{result}"
3027        );
3028        assert!(
3029            !result.contains("ForeignPosix"),
3030            "key types must not leak POSIX absolute paths from other workspaces; got:\n{result}"
3031        );
3032    }
3033
3034    #[tokio::test]
3035    async fn test_prompt_context_handler_prefers_file_hint() {
3036        let file = make_indexed_file(
3037            "src/main.rs",
3038            vec![make_symbol("serve", SymbolKind::Function, 1, 3)],
3039            vec![],
3040            ParseStatus::Parsed,
3041        );
3042        let state = make_state(vec![("src/main.rs", file)]);
3043
3044        let result = prompt_context_handler(
3045            State(state),
3046            Query(PromptContextParams {
3047                text: "please inspect src/main.rs".to_string(),
3048            }),
3049        )
3050        .await
3051        .unwrap();
3052
3053        assert!(
3054            result.contains("src/main.rs"),
3055            "prompt context should target the hinted file"
3056        );
3057        assert!(
3058            result.contains("serve"),
3059            "prompt context should surface the file outline"
3060        );
3061        assert!(
3062            result.contains("Prompt-context signal: high-confidence"),
3063            "exact file hints should surface calibrated confidence: {result}"
3064        );
3065        assert!(
3066            result.contains("exact path `src/main.rs` matched in the prompt"),
3067            "exact file hints should expose the evidence source: {result}"
3068        );
3069    }
3070
3071    #[tokio::test]
3072    async fn test_prompt_context_handler_symbol_hint_uses_name_only_symbol_context() {
3073        let target = make_indexed_file(
3074            "src/db.rs",
3075            vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
3076            vec![],
3077            ParseStatus::Parsed,
3078        );
3079        let dependent = IndexedFile {
3080            relative_path: "src/service.rs".to_string(),
3081            language: LanguageId::Rust,
3082            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
3083            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
3084            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
3085            parse_status: ParseStatus::Parsed,
3086            parse_diagnostic: None,
3087            byte_len: 46,
3088            content_hash: "abc".to_string(),
3089            references: vec![
3090                ReferenceRecord {
3091                    name: "db".to_string(),
3092                    qualified_name: Some("crate::db".to_string()),
3093                    kind: ReferenceKind::Import,
3094                    byte_range: (0, 6),
3095                    line_range: (0, 0),
3096                    enclosing_symbol_index: Some(0),
3097                },
3098                ReferenceRecord {
3099                    name: "connect".to_string(),
3100                    qualified_name: Some("crate::db::connect".to_string()),
3101                    kind: ReferenceKind::Call,
3102                    byte_range: (10, 16),
3103                    line_range: (1, 1),
3104                    enclosing_symbol_index: Some(0),
3105                },
3106            ],
3107            alias_map: HashMap::new(),
3108            mtime_secs: 0,
3109        };
3110        let unrelated = make_indexed_file(
3111            "src/other.rs",
3112            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
3113            vec![make_reference("connect", ReferenceKind::Call, 1)],
3114            ParseStatus::Parsed,
3115        );
3116        let state = make_state(vec![
3117            ("src/db.rs", target),
3118            ("src/service.rs", dependent),
3119            ("src/other.rs", unrelated),
3120        ]);
3121
3122        let result = prompt_context_handler(
3123            State(state),
3124            Query(PromptContextParams {
3125                text: "where is connect used".to_string(),
3126            }),
3127        )
3128        .await
3129        .unwrap();
3130
3131        assert!(
3132            result.contains("src/service.rs"),
3133            "symbol-only prompt should use symbol context: {result}"
3134        );
3135        assert!(
3136            result.contains("src/other.rs"),
3137            "name-only symbol context should keep global same-name hits: {result}"
3138        );
3139        assert!(
3140            result.contains("Prompt-context signal: heuristic"),
3141            "symbol-only hints should be labeled heuristic: {result}"
3142        );
3143        assert!(
3144            result.contains("symbol token `connect` matched somewhere in the index"),
3145            "symbol-only hints should expose their evidence source: {result}"
3146        );
3147    }
3148
3149    #[tokio::test]
3150    async fn test_prompt_context_handler_without_hint_reports_no_high_confidence_signal() {
3151        let target = make_indexed_file(
3152            "src/db.rs",
3153            vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
3154            vec![],
3155            ParseStatus::Parsed,
3156        );
3157        let state = make_state(vec![("src/db.rs", target)]);
3158
3159        let result = prompt_context_handler(
3160            State(state),
3161            Query(PromptContextParams {
3162                text: "please help with the database thing".to_string(),
3163            }),
3164        )
3165        .await
3166        .unwrap();
3167
3168        assert!(
3169            result.contains("Prompt-context signal: no high-confidence hint"),
3170            "unmatched prompts should explicitly report low confidence: {result}"
3171        );
3172        assert!(
3173            result.contains("search_symbols(...)"),
3174            "unmatched prompts should suggest the next narrowing step: {result}"
3175        );
3176    }
3177
3178    #[tokio::test]
3179    async fn test_prompt_context_handler_combined_file_and_symbol_hint_uses_exact_selector() {
3180        let target = make_indexed_file(
3181            "src/db.rs",
3182            vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
3183            vec![],
3184            ParseStatus::Parsed,
3185        );
3186        let dependent = IndexedFile {
3187            relative_path: "src/service.rs".to_string(),
3188            language: LanguageId::Rust,
3189            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
3190            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
3191            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
3192            parse_status: ParseStatus::Parsed,
3193            parse_diagnostic: None,
3194            byte_len: 46,
3195            content_hash: "abc".to_string(),
3196            references: vec![
3197                ReferenceRecord {
3198                    name: "db".to_string(),
3199                    qualified_name: Some("crate::db".to_string()),
3200                    kind: ReferenceKind::Import,
3201                    byte_range: (0, 6),
3202                    line_range: (0, 0),
3203                    enclosing_symbol_index: Some(0),
3204                },
3205                ReferenceRecord {
3206                    name: "connect".to_string(),
3207                    qualified_name: Some("crate::db::connect".to_string()),
3208                    kind: ReferenceKind::Call,
3209                    byte_range: (10, 16),
3210                    line_range: (1, 1),
3211                    enclosing_symbol_index: Some(0),
3212                },
3213            ],
3214            alias_map: HashMap::new(),
3215            mtime_secs: 0,
3216        };
3217        let unrelated = make_indexed_file(
3218            "src/other.rs",
3219            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
3220            vec![make_reference("connect", ReferenceKind::Call, 1)],
3221            ParseStatus::Parsed,
3222        );
3223        let state = make_state(vec![
3224            ("src/db.rs", target),
3225            ("src/service.rs", dependent),
3226            ("src/other.rs", unrelated),
3227        ]);
3228
3229        let result = prompt_context_handler(
3230            State(state),
3231            Query(PromptContextParams {
3232                text: "inspect src/db.rs connect".to_string(),
3233            }),
3234        )
3235        .await
3236        .unwrap();
3237
3238        assert!(
3239            result.contains("src/service.rs"),
3240            "combined prompt should use exact selector symbol context: {result}"
3241        );
3242        assert!(
3243            !result.contains("src/other.rs"),
3244            "exact selector should exclude unrelated same-name hits: {result}"
3245        );
3246    }
3247
3248    #[tokio::test]
3249    async fn test_prompt_context_handler_combined_hint_reports_exact_selector_ambiguity() {
3250        let target = make_indexed_file(
3251            "src/db.rs",
3252            vec![
3253                make_symbol("connect", SymbolKind::Function, 1, 1),
3254                make_symbol("connect", SymbolKind::Function, 2, 2),
3255            ],
3256            vec![],
3257            ParseStatus::Parsed,
3258        );
3259        let state = make_state(vec![("src/db.rs", target)]);
3260
3261        let result = prompt_context_handler(
3262            State(state),
3263            Query(PromptContextParams {
3264                text: "inspect src/db.rs connect".to_string(),
3265            }),
3266        )
3267        .await
3268        .unwrap();
3269
3270        assert!(
3271            result.contains("Ambiguous symbol selector"),
3272            "combined prompt should surface exact-selector ambiguity: {result}"
3273        );
3274        assert!(result.contains("1"), "got: {result}");
3275        assert!(result.contains("2"), "got: {result}");
3276    }
3277
3278    #[tokio::test]
3279    async fn test_prompt_context_handler_combined_hint_line_hint_disambiguates_selector() {
3280        let target = make_indexed_file(
3281            "src/db.rs",
3282            vec![
3283                make_symbol("connect", SymbolKind::Function, 1, 1),
3284                make_symbol("connect", SymbolKind::Function, 2, 2),
3285            ],
3286            vec![],
3287            ParseStatus::Parsed,
3288        );
3289        let dependent = IndexedFile {
3290            relative_path: "src/service.rs".to_string(),
3291            language: LanguageId::Rust,
3292            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
3293            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
3294            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
3295            parse_status: ParseStatus::Parsed,
3296            parse_diagnostic: None,
3297            byte_len: 46,
3298            content_hash: "abc".to_string(),
3299            references: vec![
3300                ReferenceRecord {
3301                    name: "db".to_string(),
3302                    qualified_name: Some("crate::db".to_string()),
3303                    kind: ReferenceKind::Import,
3304                    byte_range: (0, 6),
3305                    line_range: (0, 0),
3306                    enclosing_symbol_index: Some(0),
3307                },
3308                ReferenceRecord {
3309                    name: "connect".to_string(),
3310                    qualified_name: Some("crate::db::connect".to_string()),
3311                    kind: ReferenceKind::Call,
3312                    byte_range: (10, 16),
3313                    line_range: (1, 1),
3314                    enclosing_symbol_index: Some(0),
3315                },
3316            ],
3317            alias_map: HashMap::new(),
3318            mtime_secs: 0,
3319        };
3320        let state = make_state(vec![("src/db.rs", target), ("src/service.rs", dependent)]);
3321
3322        let result = prompt_context_handler(
3323            State(state),
3324            Query(PromptContextParams {
3325                text: "inspect src/db.rs connect line 2".to_string(),
3326            }),
3327        )
3328        .await
3329        .unwrap();
3330
3331        assert!(
3332            !result.contains("Ambiguous symbol selector"),
3333            "line hint should disambiguate the exact selector: {result}"
3334        );
3335        assert!(
3336            result.contains("src/service.rs"),
3337            "line hint should still return symbol context results: {result}"
3338        );
3339    }
3340
3341    #[tokio::test]
3342    async fn test_prompt_context_handler_ignores_unlabeled_numbers_for_line_hint() {
3343        let target = make_indexed_file(
3344            "src/db.rs",
3345            vec![
3346                make_symbol("connect", SymbolKind::Function, 1, 1),
3347                make_symbol("connect", SymbolKind::Function, 2, 2),
3348            ],
3349            vec![],
3350            ParseStatus::Parsed,
3351        );
3352        let state = make_state(vec![("src/db.rs", target)]);
3353
3354        let result = prompt_context_handler(
3355            State(state),
3356            Query(PromptContextParams {
3357                text: "inspect src/db.rs connect 2".to_string(),
3358            }),
3359        )
3360        .await
3361        .unwrap();
3362
3363        assert!(
3364            result.contains("Ambiguous symbol selector"),
3365            "unlabeled numbers should not count as line hints: {result}"
3366        );
3367    }
3368
3369    #[tokio::test]
3370    async fn test_prompt_context_handler_path_line_hint_disambiguates_selector() {
3371        let target = make_indexed_file(
3372            "src/db.rs",
3373            vec![
3374                make_symbol("connect", SymbolKind::Function, 1, 1),
3375                make_symbol("connect", SymbolKind::Function, 2, 2),
3376            ],
3377            vec![],
3378            ParseStatus::Parsed,
3379        );
3380        let dependent = IndexedFile {
3381            relative_path: "src/service.rs".to_string(),
3382            language: LanguageId::Rust,
3383            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
3384            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
3385            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
3386            parse_status: ParseStatus::Parsed,
3387            parse_diagnostic: None,
3388            byte_len: 46,
3389            content_hash: "abc".to_string(),
3390            references: vec![
3391                ReferenceRecord {
3392                    name: "db".to_string(),
3393                    qualified_name: Some("crate::db".to_string()),
3394                    kind: ReferenceKind::Import,
3395                    byte_range: (0, 6),
3396                    line_range: (0, 0),
3397                    enclosing_symbol_index: Some(0),
3398                },
3399                ReferenceRecord {
3400                    name: "connect".to_string(),
3401                    qualified_name: Some("crate::db::connect".to_string()),
3402                    kind: ReferenceKind::Call,
3403                    byte_range: (10, 16),
3404                    line_range: (1, 1),
3405                    enclosing_symbol_index: Some(0),
3406                },
3407            ],
3408            alias_map: HashMap::new(),
3409            mtime_secs: 0,
3410        };
3411        let state = make_state(vec![("src/db.rs", target), ("src/service.rs", dependent)]);
3412
3413        let result = prompt_context_handler(
3414            State(state),
3415            Query(PromptContextParams {
3416                text: "inspect src/db.rs:2 connect".to_string(),
3417            }),
3418        )
3419        .await
3420        .unwrap();
3421
3422        assert!(
3423            !result.contains("Ambiguous symbol selector"),
3424            "path:line hint should disambiguate the exact selector: {result}"
3425        );
3426        assert!(
3427            result.contains("src/service.rs"),
3428            "path:line hint should still return symbol context results: {result}"
3429        );
3430    }
3431
3432    #[tokio::test]
3433    async fn test_prompt_context_handler_basename_line_hint_disambiguates_selector() {
3434        let target = make_indexed_file(
3435            "src/db.rs",
3436            vec![
3437                make_symbol("connect", SymbolKind::Function, 1, 1),
3438                make_symbol("connect", SymbolKind::Function, 2, 2),
3439            ],
3440            vec![],
3441            ParseStatus::Parsed,
3442        );
3443        let dependent = IndexedFile {
3444            relative_path: "src/service.rs".to_string(),
3445            language: LanguageId::Rust,
3446            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
3447            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
3448            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
3449            parse_status: ParseStatus::Parsed,
3450            parse_diagnostic: None,
3451            byte_len: 46,
3452            content_hash: "abc".to_string(),
3453            references: vec![
3454                ReferenceRecord {
3455                    name: "db".to_string(),
3456                    qualified_name: Some("crate::db".to_string()),
3457                    kind: ReferenceKind::Import,
3458                    byte_range: (0, 6),
3459                    line_range: (0, 0),
3460                    enclosing_symbol_index: Some(0),
3461                },
3462                ReferenceRecord {
3463                    name: "connect".to_string(),
3464                    qualified_name: Some("crate::db::connect".to_string()),
3465                    kind: ReferenceKind::Call,
3466                    byte_range: (10, 16),
3467                    line_range: (1, 1),
3468                    enclosing_symbol_index: Some(0),
3469                },
3470            ],
3471            alias_map: HashMap::new(),
3472            mtime_secs: 0,
3473        };
3474        let state = make_state(vec![("src/db.rs", target), ("src/service.rs", dependent)]);
3475
3476        let result = prompt_context_handler(
3477            State(state),
3478            Query(PromptContextParams {
3479                text: "inspect db.rs:2 connect".to_string(),
3480            }),
3481        )
3482        .await
3483        .unwrap();
3484
3485        assert!(
3486            !result.contains("Ambiguous symbol selector"),
3487            "basename:line hint should disambiguate the exact selector: {result}"
3488        );
3489        assert!(
3490            result.contains("src/service.rs"),
3491            "basename:line hint should still return symbol context results: {result}"
3492        );
3493    }
3494
3495    #[tokio::test]
3496    async fn test_prompt_context_handler_extensionless_alias_line_hint_disambiguates_selector() {
3497        let target = make_indexed_file(
3498            "src/db.rs",
3499            vec![
3500                make_symbol("connect", SymbolKind::Function, 1, 1),
3501                make_symbol("connect", SymbolKind::Function, 2, 2),
3502            ],
3503            vec![],
3504            ParseStatus::Parsed,
3505        );
3506        let dependent = IndexedFile {
3507            relative_path: "src/service.rs".to_string(),
3508            language: LanguageId::Rust,
3509            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
3510            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
3511            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
3512            parse_status: ParseStatus::Parsed,
3513            parse_diagnostic: None,
3514            byte_len: 46,
3515            content_hash: "abc".to_string(),
3516            references: vec![
3517                ReferenceRecord {
3518                    name: "db".to_string(),
3519                    qualified_name: Some("crate::db".to_string()),
3520                    kind: ReferenceKind::Import,
3521                    byte_range: (0, 6),
3522                    line_range: (0, 0),
3523                    enclosing_symbol_index: Some(0),
3524                },
3525                ReferenceRecord {
3526                    name: "connect".to_string(),
3527                    qualified_name: Some("crate::db::connect".to_string()),
3528                    kind: ReferenceKind::Call,
3529                    byte_range: (10, 16),
3530                    line_range: (1, 1),
3531                    enclosing_symbol_index: Some(0),
3532                },
3533            ],
3534            alias_map: HashMap::new(),
3535            mtime_secs: 0,
3536        };
3537        let unrelated = make_indexed_file(
3538            "src/other.rs",
3539            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
3540            vec![make_reference("connect", ReferenceKind::Call, 1)],
3541            ParseStatus::Parsed,
3542        );
3543        let state = make_state(vec![
3544            ("src/db.rs", target),
3545            ("src/service.rs", dependent),
3546            ("src/other.rs", unrelated),
3547        ]);
3548
3549        let result = prompt_context_handler(
3550            State(state),
3551            Query(PromptContextParams {
3552                text: "inspect db:2 connect".to_string(),
3553            }),
3554        )
3555        .await
3556        .unwrap();
3557
3558        assert!(
3559            !result.contains("Ambiguous symbol selector"),
3560            "extensionless alias should disambiguate the exact selector: {result}"
3561        );
3562        assert!(
3563            result.contains("src/service.rs"),
3564            "extensionless alias should still return symbol context results: {result}"
3565        );
3566        assert!(
3567            !result.contains("src/other.rs"),
3568            "extensionless alias should exclude unrelated same-name hits: {result}"
3569        );
3570    }
3571
3572    #[tokio::test]
3573    async fn test_prompt_context_handler_extensionless_path_line_hint_disambiguates_selector() {
3574        let src_target = make_indexed_file(
3575            "src/db.rs",
3576            vec![
3577                make_symbol("connect", SymbolKind::Function, 1, 1),
3578                make_symbol("connect", SymbolKind::Function, 2, 2),
3579            ],
3580            vec![],
3581            ParseStatus::Parsed,
3582        );
3583        let test_target = make_indexed_file(
3584            "tests/db.py",
3585            vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
3586            vec![],
3587            ParseStatus::Parsed,
3588        );
3589        let src_dependent = IndexedFile {
3590            relative_path: "src/service.rs".to_string(),
3591            language: LanguageId::Rust,
3592            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
3593            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
3594            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
3595            parse_status: ParseStatus::Parsed,
3596            parse_diagnostic: None,
3597            byte_len: 46,
3598            content_hash: "abc".to_string(),
3599            references: vec![
3600                ReferenceRecord {
3601                    name: "db".to_string(),
3602                    qualified_name: Some("crate::db".to_string()),
3603                    kind: ReferenceKind::Import,
3604                    byte_range: (0, 6),
3605                    line_range: (0, 0),
3606                    enclosing_symbol_index: Some(0),
3607                },
3608                ReferenceRecord {
3609                    name: "connect".to_string(),
3610                    qualified_name: Some("crate::db::connect".to_string()),
3611                    kind: ReferenceKind::Call,
3612                    byte_range: (10, 16),
3613                    line_range: (1, 1),
3614                    enclosing_symbol_index: Some(0),
3615                },
3616            ],
3617            alias_map: HashMap::new(),
3618            mtime_secs: 0,
3619        };
3620        let unrelated = make_indexed_file(
3621            "src/other.rs",
3622            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
3623            vec![make_reference("connect", ReferenceKind::Call, 1)],
3624            ParseStatus::Parsed,
3625        );
3626        let state = make_state(vec![
3627            ("src/db.rs", src_target),
3628            ("tests/db.py", test_target),
3629            ("src/service.rs", src_dependent),
3630            ("src/other.rs", unrelated),
3631        ]);
3632
3633        let result = prompt_context_handler(
3634            State(state),
3635            Query(PromptContextParams {
3636                text: "inspect src/db:2 connect".to_string(),
3637            }),
3638        )
3639        .await
3640        .unwrap();
3641
3642        assert!(
3643            !result.contains("Ambiguous symbol selector"),
3644            "extensionless path alias should disambiguate the exact selector: {result}"
3645        );
3646        assert!(
3647            result.contains("src/service.rs"),
3648            "extensionless path alias should still return symbol context results: {result}"
3649        );
3650        assert!(
3651            !result.contains("src/other.rs"),
3652            "extensionless path alias should exclude unrelated same-name hits: {result}"
3653        );
3654    }
3655
3656    #[tokio::test]
3657    async fn test_prompt_context_handler_module_alias_line_hint_disambiguates_selector() {
3658        let src_target = make_indexed_file(
3659            "src/db.rs",
3660            vec![
3661                make_symbol("connect", SymbolKind::Function, 1, 1),
3662                make_symbol("connect", SymbolKind::Function, 2, 2),
3663            ],
3664            vec![],
3665            ParseStatus::Parsed,
3666        );
3667        let test_target = make_indexed_file(
3668            "tests/db.py",
3669            vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
3670            vec![],
3671            ParseStatus::Parsed,
3672        );
3673        let src_dependent = IndexedFile {
3674            relative_path: "src/service.rs".to_string(),
3675            language: LanguageId::Rust,
3676            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
3677            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
3678            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
3679            parse_status: ParseStatus::Parsed,
3680            parse_diagnostic: None,
3681            byte_len: 46,
3682            content_hash: "abc".to_string(),
3683            references: vec![
3684                ReferenceRecord {
3685                    name: "db".to_string(),
3686                    qualified_name: Some("crate::db".to_string()),
3687                    kind: ReferenceKind::Import,
3688                    byte_range: (0, 6),
3689                    line_range: (0, 0),
3690                    enclosing_symbol_index: Some(0),
3691                },
3692                ReferenceRecord {
3693                    name: "connect".to_string(),
3694                    qualified_name: Some("crate::db::connect".to_string()),
3695                    kind: ReferenceKind::Call,
3696                    byte_range: (10, 16),
3697                    line_range: (1, 1),
3698                    enclosing_symbol_index: Some(0),
3699                },
3700            ],
3701            alias_map: HashMap::new(),
3702            mtime_secs: 0,
3703        };
3704        let unrelated = make_indexed_file(
3705            "src/other.rs",
3706            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
3707            vec![make_reference("connect", ReferenceKind::Call, 1)],
3708            ParseStatus::Parsed,
3709        );
3710        let state = make_state(vec![
3711            ("src/db.rs", src_target),
3712            ("tests/db.py", test_target),
3713            ("src/service.rs", src_dependent),
3714            ("src/other.rs", unrelated),
3715        ]);
3716
3717        let result = prompt_context_handler(
3718            State(state),
3719            Query(PromptContextParams {
3720                text: "inspect crate::db:2 connect".to_string(),
3721            }),
3722        )
3723        .await
3724        .unwrap();
3725
3726        assert!(
3727            !result.contains("Ambiguous symbol selector"),
3728            "module alias should disambiguate the exact selector: {result}"
3729        );
3730        assert!(
3731            result.contains("src/service.rs"),
3732            "module alias should still return symbol context results: {result}"
3733        );
3734        assert!(
3735            !result.contains("src/other.rs"),
3736            "module alias should exclude unrelated same-name hits: {result}"
3737        );
3738    }
3739
3740    #[tokio::test]
3741    async fn test_prompt_context_handler_module_alias_without_line_prefers_exact_file_hint() {
3742        let src_target = make_indexed_file(
3743            "src/db.rs",
3744            vec![make_symbol("connect", SymbolKind::Function, 2, 2)],
3745            vec![],
3746            ParseStatus::Parsed,
3747        );
3748        let test_target = make_indexed_file(
3749            "tests/db.py",
3750            vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
3751            vec![],
3752            ParseStatus::Parsed,
3753        );
3754        let src_dependent = IndexedFile {
3755            relative_path: "src/service.rs".to_string(),
3756            language: LanguageId::Rust,
3757            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
3758            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
3759            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
3760            parse_status: ParseStatus::Parsed,
3761            parse_diagnostic: None,
3762            byte_len: 46,
3763            content_hash: "abc".to_string(),
3764            references: vec![
3765                ReferenceRecord {
3766                    name: "db".to_string(),
3767                    qualified_name: Some("crate::db".to_string()),
3768                    kind: ReferenceKind::Import,
3769                    byte_range: (0, 6),
3770                    line_range: (0, 0),
3771                    enclosing_symbol_index: Some(0),
3772                },
3773                ReferenceRecord {
3774                    name: "connect".to_string(),
3775                    qualified_name: Some("crate::db::connect".to_string()),
3776                    kind: ReferenceKind::Call,
3777                    byte_range: (10, 16),
3778                    line_range: (1, 1),
3779                    enclosing_symbol_index: Some(0),
3780                },
3781            ],
3782            alias_map: HashMap::new(),
3783            mtime_secs: 0,
3784        };
3785        let unrelated = make_indexed_file(
3786            "src/other.rs",
3787            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
3788            vec![make_reference("connect", ReferenceKind::Call, 1)],
3789            ParseStatus::Parsed,
3790        );
3791        let state = make_state(vec![
3792            ("src/db.rs", src_target),
3793            ("tests/db.py", test_target),
3794            ("src/service.rs", src_dependent),
3795            ("src/other.rs", unrelated),
3796        ]);
3797
3798        let result = prompt_context_handler(
3799            State(state),
3800            Query(PromptContextParams {
3801                text: "inspect crate::db connect".to_string(),
3802            }),
3803        )
3804        .await
3805        .unwrap();
3806
3807        assert!(
3808            !result.contains("Ambiguous symbol selector"),
3809            "module alias without line should still resolve the exact file hint: {result}"
3810        );
3811        assert!(
3812            result.contains("src/service.rs"),
3813            "module alias without line should still return symbol context results: {result}"
3814        );
3815        assert!(
3816            !result.contains("src/other.rs"),
3817            "module alias without line should exclude unrelated same-name hits: {result}"
3818        );
3819    }
3820
3821    #[tokio::test]
3822    async fn test_prompt_context_handler_slash_module_alias_without_line_prefers_exact_file_hint() {
3823        let target = IndexedFile {
3824            relative_path: "src/utils/index.ts".to_string(),
3825            language: LanguageId::TypeScript,
3826            classification: crate::domain::FileClassification::for_code_path("src/utils/index.ts"),
3827            content: b"export function connect() {}\n".to_vec(),
3828            symbols: vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
3829            parse_status: ParseStatus::Parsed,
3830            parse_diagnostic: None,
3831            byte_len: 28,
3832            content_hash: "utils-ts".to_string(),
3833            references: vec![],
3834            alias_map: HashMap::new(),
3835            mtime_secs: 0,
3836        };
3837        let dependent = IndexedFile {
3838            relative_path: "src/app.ts".to_string(),
3839            language: LanguageId::TypeScript,
3840            classification: crate::domain::FileClassification::for_code_path("src/app.ts"),
3841            content: b"import { connect } from 'src/utils';\nconnect();\n".to_vec(),
3842            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
3843            parse_status: ParseStatus::Parsed,
3844            parse_diagnostic: None,
3845            byte_len: 49,
3846            content_hash: "app-ts".to_string(),
3847            references: vec![
3848                ReferenceRecord {
3849                    name: "utils".to_string(),
3850                    qualified_name: Some("src/utils".to_string()),
3851                    kind: ReferenceKind::Import,
3852                    byte_range: (24, 33),
3853                    line_range: (0, 0),
3854                    enclosing_symbol_index: None,
3855                },
3856                ReferenceRecord {
3857                    name: "connect".to_string(),
3858                    qualified_name: Some("src/utils/connect".to_string()),
3859                    kind: ReferenceKind::Call,
3860                    byte_range: (36, 42),
3861                    line_range: (1, 1),
3862                    enclosing_symbol_index: Some(0),
3863                },
3864            ],
3865            alias_map: HashMap::new(),
3866            mtime_secs: 0,
3867        };
3868        let unrelated = make_indexed_file(
3869            "src/other.ts",
3870            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
3871            vec![make_reference("connect", ReferenceKind::Call, 1)],
3872            ParseStatus::Parsed,
3873        );
3874        let state = make_state(vec![
3875            ("src/utils/index.ts", target),
3876            ("src/app.ts", dependent),
3877            ("src/other.ts", unrelated),
3878        ]);
3879
3880        let result = prompt_context_handler(
3881            State(state),
3882            Query(PromptContextParams {
3883                text: "inspect src/utils connect".to_string(),
3884            }),
3885        )
3886        .await
3887        .unwrap();
3888
3889        assert!(
3890            !result.contains("Ambiguous symbol selector"),
3891            "slash module aliases without line should still resolve the exact file hint: {result}"
3892        );
3893        assert!(
3894            result.contains("src/app.ts"),
3895            "slash module aliases without line should still return symbol context results: {result}"
3896        );
3897        assert!(
3898            !result.contains("src/other.ts"),
3899            "slash module aliases without line should exclude unrelated same-name hits: {result}"
3900        );
3901    }
3902
3903    #[tokio::test]
3904    async fn test_prompt_context_handler_slash_module_alias_line_hint_disambiguates_selector() {
3905        let target = IndexedFile {
3906            relative_path: "src/utils/index.ts".to_string(),
3907            language: LanguageId::TypeScript,
3908            classification: crate::domain::FileClassification::for_code_path("src/utils/index.ts"),
3909            content: b"export function connect() {}\n\nexport function connect() {}\n".to_vec(),
3910            symbols: vec![
3911                make_symbol("connect", SymbolKind::Function, 1, 1),
3912                make_symbol("connect", SymbolKind::Function, 3, 3),
3913            ],
3914            parse_status: ParseStatus::Parsed,
3915            parse_diagnostic: None,
3916            byte_len: 57,
3917            content_hash: "utils-ts-lines".to_string(),
3918            references: vec![],
3919            alias_map: HashMap::new(),
3920            mtime_secs: 0,
3921        };
3922        let dependent = IndexedFile {
3923            relative_path: "src/app.ts".to_string(),
3924            language: LanguageId::TypeScript,
3925            classification: crate::domain::FileClassification::for_code_path("src/app.ts"),
3926            content: b"import { connect } from 'src/utils';\nconnect();\n".to_vec(),
3927            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
3928            parse_status: ParseStatus::Parsed,
3929            parse_diagnostic: None,
3930            byte_len: 49,
3931            content_hash: "app-ts".to_string(),
3932            references: vec![
3933                ReferenceRecord {
3934                    name: "utils".to_string(),
3935                    qualified_name: Some("src/utils".to_string()),
3936                    kind: ReferenceKind::Import,
3937                    byte_range: (24, 33),
3938                    line_range: (0, 0),
3939                    enclosing_symbol_index: None,
3940                },
3941                ReferenceRecord {
3942                    name: "connect".to_string(),
3943                    qualified_name: Some("src/utils/connect".to_string()),
3944                    kind: ReferenceKind::Call,
3945                    byte_range: (36, 42),
3946                    line_range: (1, 1),
3947                    enclosing_symbol_index: Some(0),
3948                },
3949            ],
3950            alias_map: HashMap::new(),
3951            mtime_secs: 0,
3952        };
3953        let unrelated = make_indexed_file(
3954            "src/other.ts",
3955            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
3956            vec![make_reference("connect", ReferenceKind::Call, 1)],
3957            ParseStatus::Parsed,
3958        );
3959        let state = make_state(vec![
3960            ("src/utils/index.ts", target),
3961            ("src/app.ts", dependent),
3962            ("src/other.ts", unrelated),
3963        ]);
3964
3965        let result = prompt_context_handler(
3966            State(state),
3967            Query(PromptContextParams {
3968                text: "inspect src/utils:4 connect".to_string(),
3969            }),
3970        )
3971        .await
3972        .unwrap();
3973
3974        assert!(
3975            !result.contains("Ambiguous symbol selector"),
3976            "slash module aliases should allow direct line-hint disambiguation: {result}"
3977        );
3978        assert!(
3979            result.contains("src/app.ts"),
3980            "slash module aliases with line hints should keep exact-selector matches: {result}"
3981        );
3982        assert!(
3983            !result.contains("src/other.ts"),
3984            "slash module aliases with line hints should drop unrelated same-name hits: {result}"
3985        );
3986    }
3987
3988    #[tokio::test]
3989    async fn test_prompt_context_handler_slash_module_alias_file_only_prefers_exact_outline() {
3990        let target = IndexedFile {
3991            relative_path: "src/utils/index.ts".to_string(),
3992            language: LanguageId::TypeScript,
3993            classification: crate::domain::FileClassification::for_code_path("src/utils/index.ts"),
3994            content: b"export function connect() {}\n".to_vec(),
3995            symbols: vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
3996            parse_status: ParseStatus::Parsed,
3997            parse_diagnostic: None,
3998            byte_len: 28,
3999            content_hash: "utils-ts".to_string(),
4000            references: vec![],
4001            alias_map: HashMap::new(),
4002            mtime_secs: 0,
4003        };
4004        let unrelated = make_indexed_file(
4005            "src/other.ts",
4006            vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
4007            vec![],
4008            ParseStatus::Parsed,
4009        );
4010        let state = make_state(vec![
4011            ("src/utils/index.ts", target),
4012            ("src/other.ts", unrelated),
4013        ]);
4014
4015        let result = prompt_context_handler(
4016            State(state),
4017            Query(PromptContextParams {
4018                text: "inspect src/utils".to_string(),
4019            }),
4020        )
4021        .await
4022        .unwrap();
4023
4024        assert!(
4025            result.contains("src/utils/index.ts"),
4026            "slash module aliases should resolve file-only prompts to the exact outline: {result}"
4027        );
4028        assert!(
4029            !result.contains("src/other.ts"),
4030            "slash module aliases should not outline unrelated files: {result}"
4031        );
4032    }
4033
4034    #[tokio::test]
4035    async fn test_prompt_context_handler_partial_slash_module_alias_without_line_does_not_activate()
4036    {
4037        let target = IndexedFile {
4038            relative_path: "src/utils/index.ts".to_string(),
4039            language: LanguageId::TypeScript,
4040            classification: crate::domain::FileClassification::for_code_path("src/utils/index.ts"),
4041            content: b"export function connect() {}\n".to_vec(),
4042            symbols: vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
4043            parse_status: ParseStatus::Parsed,
4044            parse_diagnostic: None,
4045            byte_len: 28,
4046            content_hash: "utils-ts".to_string(),
4047            references: vec![],
4048            alias_map: HashMap::new(),
4049            mtime_secs: 0,
4050        };
4051        let dependent = IndexedFile {
4052            relative_path: "src/app.ts".to_string(),
4053            language: LanguageId::TypeScript,
4054            classification: crate::domain::FileClassification::for_code_path("src/app.ts"),
4055            content: b"import { connect } from 'src/utils';\nconnect();\n".to_vec(),
4056            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
4057            parse_status: ParseStatus::Parsed,
4058            parse_diagnostic: None,
4059            byte_len: 49,
4060            content_hash: "app-ts".to_string(),
4061            references: vec![
4062                ReferenceRecord {
4063                    name: "utils".to_string(),
4064                    qualified_name: Some("src/utils".to_string()),
4065                    kind: ReferenceKind::Import,
4066                    byte_range: (24, 33),
4067                    line_range: (0, 0),
4068                    enclosing_symbol_index: None,
4069                },
4070                ReferenceRecord {
4071                    name: "connect".to_string(),
4072                    qualified_name: Some("src/utils/connect".to_string()),
4073                    kind: ReferenceKind::Call,
4074                    byte_range: (36, 42),
4075                    line_range: (1, 1),
4076                    enclosing_symbol_index: Some(0),
4077                },
4078            ],
4079            alias_map: HashMap::new(),
4080            mtime_secs: 0,
4081        };
4082        let unrelated = make_indexed_file(
4083            "src/other.ts",
4084            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
4085            vec![make_reference("connect", ReferenceKind::Call, 1)],
4086            ParseStatus::Parsed,
4087        );
4088        let state = make_state(vec![
4089            ("src/utils/index.ts", target),
4090            ("src/app.ts", dependent),
4091            ("src/other.ts", unrelated),
4092        ]);
4093
4094        let partial = prompt_context_handler(
4095            State(state.clone()),
4096            Query(PromptContextParams {
4097                text: "inspect src/utilsx connect".to_string(),
4098            }),
4099        )
4100        .await
4101        .unwrap();
4102
4103        assert!(
4104            partial.contains("src/app.ts"),
4105            "partial slash module aliases should stay on the fallback path: {partial}"
4106        );
4107        assert!(
4108            partial.contains("src/other.ts"),
4109            "partial slash module aliases should not collapse to one exact file: {partial}"
4110        );
4111
4112        let continued = prompt_context_handler(
4113            State(state),
4114            Query(PromptContextParams {
4115                text: "inspect src/utils/more connect".to_string(),
4116            }),
4117        )
4118        .await
4119        .unwrap();
4120
4121        assert!(
4122            continued.contains("src/app.ts"),
4123            "continued slash module aliases should stay on the fallback path: {continued}"
4124        );
4125        assert!(
4126            continued.contains("src/other.ts"),
4127            "continued slash module aliases should not collapse to one exact file: {continued}"
4128        );
4129    }
4130
4131    #[tokio::test]
4132    async fn test_prompt_context_handler_slash_module_alias_ignores_unrelated_colon_numbers() {
4133        let target = IndexedFile {
4134            relative_path: "src/utils/index.ts".to_string(),
4135            language: LanguageId::TypeScript,
4136            classification: crate::domain::FileClassification::for_code_path("src/utils/index.ts"),
4137            content: b"export function connect() {}\n\nexport function connect() {}\n".to_vec(),
4138            symbols: vec![
4139                make_symbol("connect", SymbolKind::Function, 1, 1),
4140                make_symbol("connect", SymbolKind::Function, 3, 3),
4141            ],
4142            parse_status: ParseStatus::Parsed,
4143            parse_diagnostic: None,
4144            byte_len: 57,
4145            content_hash: "utils-ts-lines".to_string(),
4146            references: vec![],
4147            alias_map: HashMap::new(),
4148            mtime_secs: 0,
4149        };
4150        let dependent = IndexedFile {
4151            relative_path: "src/app.ts".to_string(),
4152            language: LanguageId::TypeScript,
4153            classification: crate::domain::FileClassification::for_code_path("src/app.ts"),
4154            content: b"import { connect } from 'src/utils';\nconnect();\n".to_vec(),
4155            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
4156            parse_status: ParseStatus::Parsed,
4157            parse_diagnostic: None,
4158            byte_len: 49,
4159            content_hash: "app-ts".to_string(),
4160            references: vec![
4161                ReferenceRecord {
4162                    name: "utils".to_string(),
4163                    qualified_name: Some("src/utils".to_string()),
4164                    kind: ReferenceKind::Import,
4165                    byte_range: (24, 33),
4166                    line_range: (0, 0),
4167                    enclosing_symbol_index: None,
4168                },
4169                ReferenceRecord {
4170                    name: "connect".to_string(),
4171                    qualified_name: Some("src/utils/connect".to_string()),
4172                    kind: ReferenceKind::Call,
4173                    byte_range: (36, 42),
4174                    line_range: (1, 1),
4175                    enclosing_symbol_index: Some(0),
4176                },
4177            ],
4178            alias_map: HashMap::new(),
4179            mtime_secs: 0,
4180        };
4181        let state = make_state(vec![
4182            ("src/utils/index.ts", target),
4183            ("src/app.ts", dependent),
4184        ]);
4185
4186        let result = prompt_context_handler(
4187            State(state),
4188            Query(PromptContextParams {
4189                text: "inspect src/utils build:3 connect".to_string(),
4190            }),
4191        )
4192        .await
4193        .unwrap();
4194
4195        assert!(
4196            result.contains("Ambiguous symbol selector"),
4197            "unrelated colon numbers should not disambiguate slash module aliases: {result}"
4198        );
4199    }
4200
4201    #[tokio::test]
4202    async fn test_prompt_context_handler_qualified_symbol_alias_prefers_exact_selector() {
4203        let src_target = make_indexed_file(
4204            "src/db.rs",
4205            vec![make_symbol("connect", SymbolKind::Function, 2, 2)],
4206            vec![],
4207            ParseStatus::Parsed,
4208        );
4209        let src_dependent = IndexedFile {
4210            relative_path: "src/service.rs".to_string(),
4211            language: LanguageId::Rust,
4212            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
4213            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
4214            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
4215            parse_status: ParseStatus::Parsed,
4216            parse_diagnostic: None,
4217            byte_len: 46,
4218            content_hash: "abc".to_string(),
4219            references: vec![
4220                ReferenceRecord {
4221                    name: "db".to_string(),
4222                    qualified_name: Some("crate::db".to_string()),
4223                    kind: ReferenceKind::Import,
4224                    byte_range: (0, 6),
4225                    line_range: (0, 0),
4226                    enclosing_symbol_index: Some(0),
4227                },
4228                ReferenceRecord {
4229                    name: "connect".to_string(),
4230                    qualified_name: Some("crate::db::connect".to_string()),
4231                    kind: ReferenceKind::Call,
4232                    byte_range: (10, 16),
4233                    line_range: (1, 1),
4234                    enclosing_symbol_index: Some(0),
4235                },
4236            ],
4237            alias_map: HashMap::new(),
4238            mtime_secs: 0,
4239        };
4240        let unrelated = make_indexed_file(
4241            "src/other.rs",
4242            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
4243            vec![make_reference("connect", ReferenceKind::Call, 1)],
4244            ParseStatus::Parsed,
4245        );
4246        let state = make_state(vec![
4247            ("src/db.rs", src_target),
4248            ("src/service.rs", src_dependent),
4249            ("src/other.rs", unrelated),
4250        ]);
4251
4252        let result = prompt_context_handler(
4253            State(state),
4254            Query(PromptContextParams {
4255                text: "inspect crate::db::connect".to_string(),
4256            }),
4257        )
4258        .await
4259        .unwrap();
4260
4261        assert!(
4262            result.contains("src/service.rs"),
4263            "qualified symbol aliases should keep exact-selector matches: {result}"
4264        );
4265        assert!(
4266            !result.contains("src/other.rs"),
4267            "qualified symbol aliases should drop unrelated same-name hits: {result}"
4268        );
4269    }
4270
4271    #[tokio::test]
4272    async fn test_prompt_context_handler_qualified_symbol_alias_line_hint_disambiguates_selector() {
4273        let src_target = make_indexed_file(
4274            "src/db.rs",
4275            vec![
4276                make_symbol("connect", SymbolKind::Function, 1, 1),
4277                make_symbol("connect", SymbolKind::Function, 2, 2),
4278            ],
4279            vec![],
4280            ParseStatus::Parsed,
4281        );
4282        let src_dependent = IndexedFile {
4283            relative_path: "src/service.rs".to_string(),
4284            language: LanguageId::Rust,
4285            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
4286            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
4287            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
4288            parse_status: ParseStatus::Parsed,
4289            parse_diagnostic: None,
4290            byte_len: 46,
4291            content_hash: "abc".to_string(),
4292            references: vec![
4293                ReferenceRecord {
4294                    name: "db".to_string(),
4295                    qualified_name: Some("crate::db".to_string()),
4296                    kind: ReferenceKind::Import,
4297                    byte_range: (0, 6),
4298                    line_range: (0, 0),
4299                    enclosing_symbol_index: Some(0),
4300                },
4301                ReferenceRecord {
4302                    name: "connect".to_string(),
4303                    qualified_name: Some("crate::db::connect".to_string()),
4304                    kind: ReferenceKind::Call,
4305                    byte_range: (10, 16),
4306                    line_range: (1, 1),
4307                    enclosing_symbol_index: Some(0),
4308                },
4309            ],
4310            alias_map: HashMap::new(),
4311            mtime_secs: 0,
4312        };
4313        let unrelated = make_indexed_file(
4314            "src/other.rs",
4315            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
4316            vec![make_reference("connect", ReferenceKind::Call, 1)],
4317            ParseStatus::Parsed,
4318        );
4319        let state = make_state(vec![
4320            ("src/db.rs", src_target),
4321            ("src/service.rs", src_dependent),
4322            ("src/other.rs", unrelated),
4323        ]);
4324
4325        let result = prompt_context_handler(
4326            State(state),
4327            Query(PromptContextParams {
4328                text: "inspect crate::db::connect:2".to_string(),
4329            }),
4330        )
4331        .await
4332        .unwrap();
4333
4334        assert!(
4335            !result.contains("Ambiguous symbol selector"),
4336            "qualified symbol aliases should allow direct line-hint disambiguation: {result}"
4337        );
4338        assert!(
4339            result.contains("src/service.rs"),
4340            "qualified symbol aliases with line hints should keep exact-selector matches: {result}"
4341        );
4342        assert!(
4343            !result.contains("src/other.rs"),
4344            "qualified symbol aliases with line hints should drop unrelated same-name hits: {result}"
4345        );
4346    }
4347
4348    #[tokio::test]
4349    async fn test_prompt_context_handler_partial_module_alias_without_line_does_not_activate() {
4350        let src_target = make_indexed_file(
4351            "src/db.rs",
4352            vec![make_symbol("connect", SymbolKind::Function, 2, 2)],
4353            vec![],
4354            ParseStatus::Parsed,
4355        );
4356        let src_dependent = make_indexed_file(
4357            "src/service.rs",
4358            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
4359            vec![make_reference("connect", ReferenceKind::Call, 1)],
4360            ParseStatus::Parsed,
4361        );
4362        let alt_dependent = make_indexed_file(
4363            "src/other.rs",
4364            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
4365            vec![make_reference("connect", ReferenceKind::Call, 1)],
4366            ParseStatus::Parsed,
4367        );
4368        let state = make_state(vec![
4369            ("src/db.rs", src_target),
4370            ("src/service.rs", src_dependent),
4371            ("src/other.rs", alt_dependent),
4372        ]);
4373
4374        let result = prompt_context_handler(
4375            State(state),
4376            Query(PromptContextParams {
4377                text: "inspect crate::dbx connect".to_string(),
4378            }),
4379        )
4380        .await
4381        .unwrap();
4382
4383        assert!(
4384            result.contains("src/service.rs"),
4385            "partial module aliases should stay on the fallback path: {result}"
4386        );
4387        assert!(
4388            result.contains("src/other.rs"),
4389            "partial module aliases should not collapse to one exact file: {result}"
4390        );
4391    }
4392
4393    #[tokio::test]
4394    async fn test_prompt_context_handler_partial_qualified_symbol_alias_does_not_activate() {
4395        let src_target = make_indexed_file(
4396            "src/db.rs",
4397            vec![make_symbol("connect", SymbolKind::Function, 2, 2)],
4398            vec![],
4399            ParseStatus::Parsed,
4400        );
4401        let src_dependent = make_indexed_file(
4402            "src/service.rs",
4403            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
4404            vec![make_reference("connect", ReferenceKind::Call, 1)],
4405            ParseStatus::Parsed,
4406        );
4407        let alt_dependent = make_indexed_file(
4408            "src/other.rs",
4409            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
4410            vec![make_reference("connect", ReferenceKind::Call, 1)],
4411            ParseStatus::Parsed,
4412        );
4413        let state = make_state(vec![
4414            ("src/db.rs", src_target),
4415            ("src/service.rs", src_dependent),
4416            ("src/other.rs", alt_dependent),
4417        ]);
4418
4419        let result = prompt_context_handler(
4420            State(state),
4421            Query(PromptContextParams {
4422                text: "inspect crate::db::connect::helper".to_string(),
4423            }),
4424        )
4425        .await
4426        .unwrap();
4427
4428        assert!(
4429            result.contains("src/service.rs"),
4430            "continued qualified symbol aliases should stay on the fallback path: {result}"
4431        );
4432        assert!(
4433            result.contains("src/other.rs"),
4434            "continued qualified symbol aliases should not collapse to one exact file: {result}"
4435        );
4436    }
4437
4438    #[tokio::test]
4439    async fn test_prompt_context_handler_dotted_qualified_symbol_alias_prefers_exact_selector() {
4440        let target = IndexedFile {
4441            relative_path: "pkg/db.py".to_string(),
4442            language: LanguageId::Python,
4443            classification: crate::domain::FileClassification::for_code_path("pkg/db.py"),
4444            content: b"def connect():\n    pass\n".to_vec(),
4445            symbols: vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
4446            parse_status: ParseStatus::Parsed,
4447            parse_diagnostic: None,
4448            byte_len: 24,
4449            content_hash: "db-py".to_string(),
4450            references: vec![],
4451            alias_map: HashMap::new(),
4452            mtime_secs: 0,
4453        };
4454        let dependent = IndexedFile {
4455            relative_path: "pkg/service.py".to_string(),
4456            language: LanguageId::Python,
4457            classification: crate::domain::FileClassification::for_code_path("pkg/service.py"),
4458            content: b"from pkg.db import connect\n\ndef run():\n    connect()\n".to_vec(),
4459            symbols: vec![make_symbol("run", SymbolKind::Function, 3, 3)],
4460            parse_status: ParseStatus::Parsed,
4461            parse_diagnostic: None,
4462            byte_len: 54,
4463            content_hash: "service-py".to_string(),
4464            references: vec![
4465                ReferenceRecord {
4466                    name: "db".to_string(),
4467                    qualified_name: Some("pkg.db".to_string()),
4468                    kind: ReferenceKind::Import,
4469                    byte_range: (5, 11),
4470                    line_range: (0, 0),
4471                    enclosing_symbol_index: None,
4472                },
4473                ReferenceRecord {
4474                    name: "connect".to_string(),
4475                    qualified_name: Some("pkg.db.connect".to_string()),
4476                    kind: ReferenceKind::Call,
4477                    byte_range: (41, 47),
4478                    line_range: (3, 3),
4479                    enclosing_symbol_index: Some(0),
4480                },
4481            ],
4482            alias_map: HashMap::new(),
4483            mtime_secs: 0,
4484        };
4485        let unrelated = IndexedFile {
4486            relative_path: "pkg/other.py".to_string(),
4487            language: LanguageId::Python,
4488            classification: crate::domain::FileClassification::for_code_path("pkg/other.py"),
4489            content: b"def run():\n    connect()\n".to_vec(),
4490            symbols: vec![make_symbol("run", SymbolKind::Function, 1, 1)],
4491            parse_status: ParseStatus::Parsed,
4492            parse_diagnostic: None,
4493            byte_len: 25,
4494            content_hash: "other-py".to_string(),
4495            references: vec![make_reference("connect", ReferenceKind::Call, 1)],
4496            alias_map: HashMap::new(),
4497            mtime_secs: 0,
4498        };
4499        let state = make_state(vec![
4500            ("pkg/db.py", target),
4501            ("pkg/service.py", dependent),
4502            ("pkg/other.py", unrelated),
4503        ]);
4504
4505        let result = prompt_context_handler(
4506            State(state),
4507            Query(PromptContextParams {
4508                text: "inspect pkg.db.connect".to_string(),
4509            }),
4510        )
4511        .await
4512        .unwrap();
4513
4514        assert!(
4515            result.contains("pkg/service.py"),
4516            "dotted qualified symbol aliases should keep exact-selector matches: {result}"
4517        );
4518        assert!(
4519            !result.contains("pkg/other.py"),
4520            "dotted qualified symbol aliases should drop unrelated same-name hits: {result}"
4521        );
4522    }
4523
4524    #[tokio::test]
4525    async fn test_prompt_context_handler_slash_qualified_symbol_alias_prefers_exact_selector() {
4526        let target = IndexedFile {
4527            relative_path: "src/utils/index.ts".to_string(),
4528            language: LanguageId::TypeScript,
4529            classification: crate::domain::FileClassification::for_code_path("src/utils/index.ts"),
4530            content: b"export function connect() {}\n".to_vec(),
4531            symbols: vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
4532            parse_status: ParseStatus::Parsed,
4533            parse_diagnostic: None,
4534            byte_len: 28,
4535            content_hash: "utils-ts".to_string(),
4536            references: vec![],
4537            alias_map: HashMap::new(),
4538            mtime_secs: 0,
4539        };
4540        let dependent = IndexedFile {
4541            relative_path: "src/app.ts".to_string(),
4542            language: LanguageId::TypeScript,
4543            classification: crate::domain::FileClassification::for_code_path("src/app.ts"),
4544            content: b"import { connect } from 'src/utils';\nconnect();\n".to_vec(),
4545            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
4546            parse_status: ParseStatus::Parsed,
4547            parse_diagnostic: None,
4548            byte_len: 49,
4549            content_hash: "app-ts".to_string(),
4550            references: vec![
4551                ReferenceRecord {
4552                    name: "utils".to_string(),
4553                    qualified_name: Some("src/utils".to_string()),
4554                    kind: ReferenceKind::Import,
4555                    byte_range: (24, 33),
4556                    line_range: (0, 0),
4557                    enclosing_symbol_index: None,
4558                },
4559                ReferenceRecord {
4560                    name: "connect".to_string(),
4561                    qualified_name: Some("src/utils/connect".to_string()),
4562                    kind: ReferenceKind::Call,
4563                    byte_range: (36, 42),
4564                    line_range: (1, 1),
4565                    enclosing_symbol_index: Some(0),
4566                },
4567            ],
4568            alias_map: HashMap::new(),
4569            mtime_secs: 0,
4570        };
4571        let unrelated = IndexedFile {
4572            relative_path: "src/other.ts".to_string(),
4573            language: LanguageId::TypeScript,
4574            classification: crate::domain::FileClassification::for_code_path("src/other.ts"),
4575            content: b"connect();\n".to_vec(),
4576            symbols: vec![make_symbol("run", SymbolKind::Function, 1, 1)],
4577            parse_status: ParseStatus::Parsed,
4578            parse_diagnostic: None,
4579            byte_len: 10,
4580            content_hash: "other-ts".to_string(),
4581            references: vec![make_reference("connect", ReferenceKind::Call, 1)],
4582            alias_map: HashMap::new(),
4583            mtime_secs: 0,
4584        };
4585        let state = make_state(vec![
4586            ("src/utils/index.ts", target),
4587            ("src/app.ts", dependent),
4588            ("src/other.ts", unrelated),
4589        ]);
4590
4591        let result = prompt_context_handler(
4592            State(state),
4593            Query(PromptContextParams {
4594                text: "inspect src/utils/connect".to_string(),
4595            }),
4596        )
4597        .await
4598        .unwrap();
4599
4600        assert!(
4601            result.contains("src/app.ts"),
4602            "slash qualified symbol aliases should keep exact-selector matches: {result}"
4603        );
4604        assert!(
4605            !result.contains("src/other.ts"),
4606            "slash qualified symbol aliases should drop unrelated same-name hits: {result}"
4607        );
4608    }
4609
4610    #[tokio::test]
4611    async fn test_prompt_context_handler_slash_qualified_symbol_alias_line_hint_disambiguates_selector()
4612     {
4613        let target = IndexedFile {
4614            relative_path: "src/utils/index.ts".to_string(),
4615            language: LanguageId::TypeScript,
4616            classification: crate::domain::FileClassification::for_code_path("src/utils/index.ts"),
4617            content: b"export function connect() {}\n\nexport function connect() {}\n".to_vec(),
4618            symbols: vec![
4619                make_symbol("connect", SymbolKind::Function, 1, 1),
4620                make_symbol("connect", SymbolKind::Function, 3, 3),
4621            ],
4622            parse_status: ParseStatus::Parsed,
4623            parse_diagnostic: None,
4624            byte_len: 57,
4625            content_hash: "utils-ts-lines".to_string(),
4626            references: vec![],
4627            alias_map: HashMap::new(),
4628            mtime_secs: 0,
4629        };
4630        let dependent = IndexedFile {
4631            relative_path: "src/app.ts".to_string(),
4632            language: LanguageId::TypeScript,
4633            classification: crate::domain::FileClassification::for_code_path("src/app.ts"),
4634            content: b"import { connect } from 'src/utils';\nconnect();\n".to_vec(),
4635            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
4636            parse_status: ParseStatus::Parsed,
4637            parse_diagnostic: None,
4638            byte_len: 49,
4639            content_hash: "app-ts".to_string(),
4640            references: vec![
4641                ReferenceRecord {
4642                    name: "utils".to_string(),
4643                    qualified_name: Some("src/utils".to_string()),
4644                    kind: ReferenceKind::Import,
4645                    byte_range: (24, 33),
4646                    line_range: (0, 0),
4647                    enclosing_symbol_index: None,
4648                },
4649                ReferenceRecord {
4650                    name: "connect".to_string(),
4651                    qualified_name: Some("src/utils/connect".to_string()),
4652                    kind: ReferenceKind::Call,
4653                    byte_range: (36, 42),
4654                    line_range: (1, 1),
4655                    enclosing_symbol_index: Some(0),
4656                },
4657            ],
4658            alias_map: HashMap::new(),
4659            mtime_secs: 0,
4660        };
4661        let unrelated = IndexedFile {
4662            relative_path: "src/other.ts".to_string(),
4663            language: LanguageId::TypeScript,
4664            classification: crate::domain::FileClassification::for_code_path("src/other.ts"),
4665            content: b"connect();\n".to_vec(),
4666            symbols: vec![make_symbol("run", SymbolKind::Function, 1, 1)],
4667            parse_status: ParseStatus::Parsed,
4668            parse_diagnostic: None,
4669            byte_len: 10,
4670            content_hash: "other-ts".to_string(),
4671            references: vec![make_reference("connect", ReferenceKind::Call, 1)],
4672            alias_map: HashMap::new(),
4673            mtime_secs: 0,
4674        };
4675        let state = make_state(vec![
4676            ("src/utils/index.ts", target),
4677            ("src/app.ts", dependent),
4678            ("src/other.ts", unrelated),
4679        ]);
4680
4681        let result = prompt_context_handler(
4682            State(state),
4683            Query(PromptContextParams {
4684                text: "inspect src/utils/connect:4".to_string(),
4685            }),
4686        )
4687        .await
4688        .unwrap();
4689
4690        assert!(
4691            !result.contains("Ambiguous symbol selector"),
4692            "slash qualified symbol aliases should allow direct line-hint disambiguation: {result}"
4693        );
4694        assert!(
4695            result.contains("src/app.ts"),
4696            "slash qualified symbol aliases with line hints should keep exact-selector matches: {result}"
4697        );
4698        assert!(
4699            !result.contains("src/other.ts"),
4700            "slash qualified symbol aliases with line hints should drop unrelated same-name hits: {result}"
4701        );
4702    }
4703
4704    #[tokio::test]
4705    async fn test_prompt_context_handler_continued_dotted_qualified_symbol_alias_does_not_activate()
4706    {
4707        let target = IndexedFile {
4708            relative_path: "pkg/db.py".to_string(),
4709            language: LanguageId::Python,
4710            classification: crate::domain::FileClassification::for_code_path("pkg/db.py"),
4711            content: b"def connect():\n    pass\n".to_vec(),
4712            symbols: vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
4713            parse_status: ParseStatus::Parsed,
4714            parse_diagnostic: None,
4715            byte_len: 24,
4716            content_hash: "db-py".to_string(),
4717            references: vec![],
4718            alias_map: HashMap::new(),
4719            mtime_secs: 0,
4720        };
4721        let dependent = IndexedFile {
4722            relative_path: "pkg/service.py".to_string(),
4723            language: LanguageId::Python,
4724            classification: crate::domain::FileClassification::for_code_path("pkg/service.py"),
4725            content: b"from pkg.db import connect\n\ndef run():\n    connect()\n".to_vec(),
4726            symbols: vec![make_symbol("run", SymbolKind::Function, 3, 3)],
4727            parse_status: ParseStatus::Parsed,
4728            parse_diagnostic: None,
4729            byte_len: 54,
4730            content_hash: "service-py".to_string(),
4731            references: vec![
4732                ReferenceRecord {
4733                    name: "db".to_string(),
4734                    qualified_name: Some("pkg.db".to_string()),
4735                    kind: ReferenceKind::Import,
4736                    byte_range: (5, 11),
4737                    line_range: (0, 0),
4738                    enclosing_symbol_index: None,
4739                },
4740                ReferenceRecord {
4741                    name: "connect".to_string(),
4742                    qualified_name: Some("pkg.db.connect".to_string()),
4743                    kind: ReferenceKind::Call,
4744                    byte_range: (41, 47),
4745                    line_range: (3, 3),
4746                    enclosing_symbol_index: Some(0),
4747                },
4748            ],
4749            alias_map: HashMap::new(),
4750            mtime_secs: 0,
4751        };
4752        let unrelated = IndexedFile {
4753            relative_path: "pkg/other.py".to_string(),
4754            language: LanguageId::Python,
4755            classification: crate::domain::FileClassification::for_code_path("pkg/other.py"),
4756            content: b"def run():\n    connect()\n".to_vec(),
4757            symbols: vec![make_symbol("run", SymbolKind::Function, 1, 1)],
4758            parse_status: ParseStatus::Parsed,
4759            parse_diagnostic: None,
4760            byte_len: 25,
4761            content_hash: "other-py".to_string(),
4762            references: vec![make_reference("connect", ReferenceKind::Call, 1)],
4763            alias_map: HashMap::new(),
4764            mtime_secs: 0,
4765        };
4766        let state = make_state(vec![
4767            ("pkg/db.py", target),
4768            ("pkg/service.py", dependent),
4769            ("pkg/other.py", unrelated),
4770        ]);
4771
4772        let result = prompt_context_handler(
4773            State(state),
4774            Query(PromptContextParams {
4775                text: "inspect pkg.db.connect.more connect".to_string(),
4776            }),
4777        )
4778        .await
4779        .unwrap();
4780
4781        assert!(
4782            result.contains("pkg/service.py"),
4783            "continued dotted aliases should stay on the fallback path: {result}"
4784        );
4785        assert!(
4786            result.contains("pkg/other.py"),
4787            "continued dotted aliases should not collapse to one exact file: {result}"
4788        );
4789    }
4790
4791    #[tokio::test]
4792    async fn test_prompt_context_handler_continued_slash_qualified_symbol_alias_does_not_activate()
4793    {
4794        let target = IndexedFile {
4795            relative_path: "src/utils/index.ts".to_string(),
4796            language: LanguageId::TypeScript,
4797            classification: crate::domain::FileClassification::for_code_path("src/utils/index.ts"),
4798            content: b"export function connect() {}\n".to_vec(),
4799            symbols: vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
4800            parse_status: ParseStatus::Parsed,
4801            parse_diagnostic: None,
4802            byte_len: 28,
4803            content_hash: "utils-ts".to_string(),
4804            references: vec![],
4805            alias_map: HashMap::new(),
4806            mtime_secs: 0,
4807        };
4808        let dependent = IndexedFile {
4809            relative_path: "src/app.ts".to_string(),
4810            language: LanguageId::TypeScript,
4811            classification: crate::domain::FileClassification::for_code_path("src/app.ts"),
4812            content: b"import { connect } from 'src/utils';\nconnect();\n".to_vec(),
4813            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
4814            parse_status: ParseStatus::Parsed,
4815            parse_diagnostic: None,
4816            byte_len: 49,
4817            content_hash: "app-ts".to_string(),
4818            references: vec![
4819                ReferenceRecord {
4820                    name: "utils".to_string(),
4821                    qualified_name: Some("src/utils".to_string()),
4822                    kind: ReferenceKind::Import,
4823                    byte_range: (24, 33),
4824                    line_range: (0, 0),
4825                    enclosing_symbol_index: None,
4826                },
4827                ReferenceRecord {
4828                    name: "connect".to_string(),
4829                    qualified_name: Some("src/utils/connect".to_string()),
4830                    kind: ReferenceKind::Call,
4831                    byte_range: (36, 42),
4832                    line_range: (1, 1),
4833                    enclosing_symbol_index: Some(0),
4834                },
4835            ],
4836            alias_map: HashMap::new(),
4837            mtime_secs: 0,
4838        };
4839        let unrelated = IndexedFile {
4840            relative_path: "src/other.ts".to_string(),
4841            language: LanguageId::TypeScript,
4842            classification: crate::domain::FileClassification::for_code_path("src/other.ts"),
4843            content: b"connect();\n".to_vec(),
4844            symbols: vec![make_symbol("run", SymbolKind::Function, 1, 1)],
4845            parse_status: ParseStatus::Parsed,
4846            parse_diagnostic: None,
4847            byte_len: 10,
4848            content_hash: "other-ts".to_string(),
4849            references: vec![make_reference("connect", ReferenceKind::Call, 1)],
4850            alias_map: HashMap::new(),
4851            mtime_secs: 0,
4852        };
4853        let state = make_state(vec![
4854            ("src/utils/index.ts", target),
4855            ("src/app.ts", dependent),
4856            ("src/other.ts", unrelated),
4857        ]);
4858
4859        let result = prompt_context_handler(
4860            State(state),
4861            Query(PromptContextParams {
4862                text: "inspect src/utils/connect/more connect".to_string(),
4863            }),
4864        )
4865        .await
4866        .unwrap();
4867
4868        assert!(
4869            result.contains("src/app.ts"),
4870            "continued slash aliases should stay on the fallback path: {result}"
4871        );
4872        assert!(
4873            result.contains("src/other.ts"),
4874            "continued slash aliases should not collapse to one exact file: {result}"
4875        );
4876    }
4877
4878    #[tokio::test]
4879    async fn test_prompt_context_handler_dotted_qualified_symbol_alias_line_hint_disambiguates_selector()
4880     {
4881        let target = IndexedFile {
4882            relative_path: "pkg/db.py".to_string(),
4883            language: LanguageId::Python,
4884            classification: crate::domain::FileClassification::for_code_path("pkg/db.py"),
4885            content: b"def connect():\n    pass\n\ndef connect():\n    pass\n".to_vec(),
4886            symbols: vec![
4887                make_symbol("connect", SymbolKind::Function, 1, 1),
4888                make_symbol("connect", SymbolKind::Function, 4, 4),
4889            ],
4890            parse_status: ParseStatus::Parsed,
4891            parse_diagnostic: None,
4892            byte_len: 49,
4893            content_hash: "db-py".to_string(),
4894            references: vec![],
4895            alias_map: HashMap::new(),
4896            mtime_secs: 0,
4897        };
4898        let dependent = IndexedFile {
4899            relative_path: "pkg/service.py".to_string(),
4900            language: LanguageId::Python,
4901            classification: crate::domain::FileClassification::for_code_path("pkg/service.py"),
4902            content: b"from pkg.db import connect\n\ndef run():\n    connect()\n".to_vec(),
4903            symbols: vec![make_symbol("run", SymbolKind::Function, 3, 3)],
4904            parse_status: ParseStatus::Parsed,
4905            parse_diagnostic: None,
4906            byte_len: 54,
4907            content_hash: "service-py".to_string(),
4908            references: vec![
4909                ReferenceRecord {
4910                    name: "db".to_string(),
4911                    qualified_name: Some("pkg.db".to_string()),
4912                    kind: ReferenceKind::Import,
4913                    byte_range: (5, 11),
4914                    line_range: (0, 0),
4915                    enclosing_symbol_index: None,
4916                },
4917                ReferenceRecord {
4918                    name: "connect".to_string(),
4919                    qualified_name: Some("pkg.db.connect".to_string()),
4920                    kind: ReferenceKind::Call,
4921                    byte_range: (41, 47),
4922                    line_range: (3, 3),
4923                    enclosing_symbol_index: Some(0),
4924                },
4925            ],
4926            alias_map: HashMap::new(),
4927            mtime_secs: 0,
4928        };
4929        let unrelated = IndexedFile {
4930            relative_path: "pkg/other.py".to_string(),
4931            language: LanguageId::Python,
4932            classification: crate::domain::FileClassification::for_code_path("pkg/other.py"),
4933            content: b"def run():\n    connect()\n".to_vec(),
4934            symbols: vec![make_symbol("run", SymbolKind::Function, 1, 1)],
4935            parse_status: ParseStatus::Parsed,
4936            parse_diagnostic: None,
4937            byte_len: 25,
4938            content_hash: "other-py".to_string(),
4939            references: vec![make_reference("connect", ReferenceKind::Call, 1)],
4940            alias_map: HashMap::new(),
4941            mtime_secs: 0,
4942        };
4943        let state = make_state(vec![
4944            ("pkg/db.py", target),
4945            ("pkg/service.py", dependent),
4946            ("pkg/other.py", unrelated),
4947        ]);
4948
4949        let result = prompt_context_handler(
4950            State(state),
4951            Query(PromptContextParams {
4952                text: "inspect pkg.db.connect:5".to_string(),
4953            }),
4954        )
4955        .await
4956        .unwrap();
4957
4958        assert!(
4959            !result.contains("Ambiguous symbol selector"),
4960            "dotted qualified symbol aliases should allow direct line-hint disambiguation: {result}"
4961        );
4962        assert!(
4963            result.contains("pkg/service.py"),
4964            "dotted qualified symbol aliases with line hints should keep exact-selector matches: {result}"
4965        );
4966        assert!(
4967            !result.contains("pkg/other.py"),
4968            "dotted qualified symbol aliases with line hints should drop unrelated same-name hits: {result}"
4969        );
4970    }
4971
4972    #[tokio::test]
4973    async fn test_prompt_context_handler_dotted_qualified_symbol_alias_ignores_unrelated_colon_numbers()
4974     {
4975        let target = IndexedFile {
4976            relative_path: "pkg/db.py".to_string(),
4977            language: LanguageId::Python,
4978            classification: crate::domain::FileClassification::for_code_path("pkg/db.py"),
4979            content: b"def connect():\n    pass\n\ndef connect():\n    pass\n".to_vec(),
4980            symbols: vec![
4981                make_symbol("connect", SymbolKind::Function, 1, 1),
4982                make_symbol("connect", SymbolKind::Function, 4, 4),
4983            ],
4984            parse_status: ParseStatus::Parsed,
4985            parse_diagnostic: None,
4986            byte_len: 49,
4987            content_hash: "db-py".to_string(),
4988            references: vec![],
4989            alias_map: HashMap::new(),
4990            mtime_secs: 0,
4991        };
4992        let dependent = IndexedFile {
4993            relative_path: "pkg/service.py".to_string(),
4994            language: LanguageId::Python,
4995            classification: crate::domain::FileClassification::for_code_path("pkg/service.py"),
4996            content: b"from pkg.db import connect\n\ndef run():\n    connect()\n".to_vec(),
4997            symbols: vec![make_symbol("run", SymbolKind::Function, 3, 3)],
4998            parse_status: ParseStatus::Parsed,
4999            parse_diagnostic: None,
5000            byte_len: 54,
5001            content_hash: "service-py".to_string(),
5002            references: vec![
5003                ReferenceRecord {
5004                    name: "db".to_string(),
5005                    qualified_name: Some("pkg.db".to_string()),
5006                    kind: ReferenceKind::Import,
5007                    byte_range: (5, 11),
5008                    line_range: (0, 0),
5009                    enclosing_symbol_index: None,
5010                },
5011                ReferenceRecord {
5012                    name: "connect".to_string(),
5013                    qualified_name: Some("pkg.db.connect".to_string()),
5014                    kind: ReferenceKind::Call,
5015                    byte_range: (41, 47),
5016                    line_range: (3, 3),
5017                    enclosing_symbol_index: Some(0),
5018                },
5019            ],
5020            alias_map: HashMap::new(),
5021            mtime_secs: 0,
5022        };
5023        let state = make_state(vec![("pkg/db.py", target), ("pkg/service.py", dependent)]);
5024
5025        let result = prompt_context_handler(
5026            State(state),
5027            Query(PromptContextParams {
5028                text: "inspect pkg.db.connect build:4".to_string(),
5029            }),
5030        )
5031        .await
5032        .unwrap();
5033
5034        assert!(
5035            result.contains("Ambiguous symbol selector"),
5036            "unrelated colon numbers should not disambiguate dotted qualified symbol aliases: {result}"
5037        );
5038    }
5039
5040    #[tokio::test]
5041    async fn test_prompt_context_handler_slash_qualified_symbol_alias_ignores_unrelated_colon_numbers()
5042     {
5043        let target = IndexedFile {
5044            relative_path: "src/utils/index.ts".to_string(),
5045            language: LanguageId::TypeScript,
5046            classification: crate::domain::FileClassification::for_code_path("src/utils/index.ts"),
5047            content: b"export function connect() {}\n\nexport function connect() {}\n".to_vec(),
5048            symbols: vec![
5049                make_symbol("connect", SymbolKind::Function, 1, 1),
5050                make_symbol("connect", SymbolKind::Function, 3, 3),
5051            ],
5052            parse_status: ParseStatus::Parsed,
5053            parse_diagnostic: None,
5054            byte_len: 57,
5055            content_hash: "utils-ts-lines".to_string(),
5056            references: vec![],
5057            alias_map: HashMap::new(),
5058            mtime_secs: 0,
5059        };
5060        let dependent = IndexedFile {
5061            relative_path: "src/app.ts".to_string(),
5062            language: LanguageId::TypeScript,
5063            classification: crate::domain::FileClassification::for_code_path("src/app.ts"),
5064            content: b"import { connect } from 'src/utils';\nconnect();\n".to_vec(),
5065            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
5066            parse_status: ParseStatus::Parsed,
5067            parse_diagnostic: None,
5068            byte_len: 49,
5069            content_hash: "app-ts".to_string(),
5070            references: vec![
5071                ReferenceRecord {
5072                    name: "utils".to_string(),
5073                    qualified_name: Some("src/utils".to_string()),
5074                    kind: ReferenceKind::Import,
5075                    byte_range: (24, 33),
5076                    line_range: (0, 0),
5077                    enclosing_symbol_index: None,
5078                },
5079                ReferenceRecord {
5080                    name: "connect".to_string(),
5081                    qualified_name: Some("src/utils/connect".to_string()),
5082                    kind: ReferenceKind::Call,
5083                    byte_range: (36, 42),
5084                    line_range: (1, 1),
5085                    enclosing_symbol_index: Some(0),
5086                },
5087            ],
5088            alias_map: HashMap::new(),
5089            mtime_secs: 0,
5090        };
5091        let state = make_state(vec![
5092            ("src/utils/index.ts", target),
5093            ("src/app.ts", dependent),
5094        ]);
5095
5096        let result = prompt_context_handler(
5097            State(state),
5098            Query(PromptContextParams {
5099                text: "inspect src/utils/connect build:3".to_string(),
5100            }),
5101        )
5102        .await
5103        .unwrap();
5104
5105        assert!(
5106            result.contains("Ambiguous symbol selector"),
5107            "unrelated colon numbers should not disambiguate slash qualified symbol aliases: {result}"
5108        );
5109    }
5110
5111    #[tokio::test]
5112    async fn test_prompt_context_handler_partial_module_alias_hint_does_not_activate() {
5113        let src_target = make_indexed_file(
5114            "src/db.rs",
5115            vec![make_symbol("connect", SymbolKind::Function, 2, 2)],
5116            vec![],
5117            ParseStatus::Parsed,
5118        );
5119        let alt_target = make_indexed_file(
5120            "src/data.rs",
5121            vec![make_symbol("connect", SymbolKind::Function, 2, 2)],
5122            vec![],
5123            ParseStatus::Parsed,
5124        );
5125        let src_dependent = make_indexed_file(
5126            "src/service.rs",
5127            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
5128            vec![make_reference("connect", ReferenceKind::Call, 1)],
5129            ParseStatus::Parsed,
5130        );
5131        let alt_dependent = make_indexed_file(
5132            "src/other.rs",
5133            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
5134            vec![make_reference("connect", ReferenceKind::Call, 1)],
5135            ParseStatus::Parsed,
5136        );
5137        let state = make_state(vec![
5138            ("src/db.rs", src_target),
5139            ("src/data.rs", alt_target),
5140            ("src/service.rs", src_dependent),
5141            ("src/other.rs", alt_dependent),
5142        ]);
5143
5144        let result = prompt_context_handler(
5145            State(state),
5146            Query(PromptContextParams {
5147                text: "inspect crate::d:2 connect".to_string(),
5148            }),
5149        )
5150        .await
5151        .unwrap();
5152
5153        assert!(
5154            result.contains("src/service.rs"),
5155            "partial module aliases should stay on the fallback path: {result}"
5156        );
5157        assert!(
5158            result.contains("src/other.rs"),
5159            "partial module aliases should not collapse to one exact file: {result}"
5160        );
5161    }
5162
5163    #[tokio::test]
5164    async fn test_prompt_context_handler_partial_extensionless_path_hint_does_not_activate() {
5165        let src_target = make_indexed_file(
5166            "src/db.rs",
5167            vec![make_symbol("connect", SymbolKind::Function, 2, 2)],
5168            vec![],
5169            ParseStatus::Parsed,
5170        );
5171        let alt_target = make_indexed_file(
5172            "src/data.rs",
5173            vec![make_symbol("connect", SymbolKind::Function, 2, 2)],
5174            vec![],
5175            ParseStatus::Parsed,
5176        );
5177        let src_dependent = make_indexed_file(
5178            "src/service.rs",
5179            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
5180            vec![make_reference("connect", ReferenceKind::Call, 1)],
5181            ParseStatus::Parsed,
5182        );
5183        let alt_dependent = make_indexed_file(
5184            "src/other.rs",
5185            vec![make_symbol("run", SymbolKind::Function, 1, 1)],
5186            vec![make_reference("connect", ReferenceKind::Call, 1)],
5187            ParseStatus::Parsed,
5188        );
5189        let state = make_state(vec![
5190            ("src/db.rs", src_target),
5191            ("src/data.rs", alt_target),
5192            ("src/service.rs", src_dependent),
5193            ("src/other.rs", alt_dependent),
5194        ]);
5195
5196        let result = prompt_context_handler(
5197            State(state),
5198            Query(PromptContextParams {
5199                text: "inspect src/d:2 connect".to_string(),
5200            }),
5201        )
5202        .await
5203        .unwrap();
5204
5205        assert!(
5206            result.contains("src/service.rs"),
5207            "partial extensionless paths should stay on the fallback path: {result}"
5208        );
5209        assert!(
5210            result.contains("src/other.rs"),
5211            "partial extensionless paths should not collapse to one exact file: {result}"
5212        );
5213    }
5214
5215    #[tokio::test]
5216    async fn test_prompt_context_handler_ignores_unrelated_colon_numbers_for_line_hint() {
5217        let target = make_indexed_file(
5218            "src/db.rs",
5219            vec![
5220                make_symbol("connect", SymbolKind::Function, 1, 1),
5221                make_symbol("connect", SymbolKind::Function, 2, 2),
5222            ],
5223            vec![],
5224            ParseStatus::Parsed,
5225        );
5226        let state = make_state(vec![("src/db.rs", target)]);
5227
5228        let result = prompt_context_handler(
5229            State(state),
5230            Query(PromptContextParams {
5231                text: "inspect src/db.rs connect port 8080:2".to_string(),
5232            }),
5233        )
5234        .await
5235        .unwrap();
5236
5237        assert!(
5238            result.contains("Ambiguous symbol selector"),
5239            "unrelated colon numbers should not count as path:line hints: {result}"
5240        );
5241    }
5242
5243    #[tokio::test]
5244    async fn test_prompt_context_handler_ambiguous_basename_line_hint_does_not_activate() {
5245        let src_target = make_indexed_file(
5246            "src/db.rs",
5247            vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
5248            vec![],
5249            ParseStatus::Parsed,
5250        );
5251        let test_target = make_indexed_file(
5252            "tests/db.rs",
5253            vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
5254            vec![],
5255            ParseStatus::Parsed,
5256        );
5257        let src_dependent = IndexedFile {
5258            relative_path: "src/service.rs".to_string(),
5259            language: LanguageId::Rust,
5260            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
5261            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
5262            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
5263            parse_status: ParseStatus::Parsed,
5264            parse_diagnostic: None,
5265            byte_len: 46,
5266            content_hash: "abc".to_string(),
5267            references: vec![
5268                ReferenceRecord {
5269                    name: "db".to_string(),
5270                    qualified_name: Some("crate::db".to_string()),
5271                    kind: ReferenceKind::Import,
5272                    byte_range: (0, 6),
5273                    line_range: (0, 0),
5274                    enclosing_symbol_index: Some(0),
5275                },
5276                ReferenceRecord {
5277                    name: "connect".to_string(),
5278                    qualified_name: Some("crate::db::connect".to_string()),
5279                    kind: ReferenceKind::Call,
5280                    byte_range: (10, 16),
5281                    line_range: (1, 1),
5282                    enclosing_symbol_index: Some(0),
5283                },
5284            ],
5285            alias_map: HashMap::new(),
5286            mtime_secs: 0,
5287        };
5288        let test_dependent = IndexedFile {
5289            relative_path: "tests/helper.rs".to_string(),
5290            language: LanguageId::Rust,
5291            classification: crate::domain::FileClassification::for_code_path("tests/helper.rs"),
5292            content: b"use crate::db::connect;\nfn helper() { connect(); }\n".to_vec(),
5293            symbols: vec![make_symbol("helper", SymbolKind::Function, 2, 2)],
5294            parse_status: ParseStatus::Parsed,
5295            parse_diagnostic: None,
5296            byte_len: 52,
5297            content_hash: "def".to_string(),
5298            references: vec![
5299                ReferenceRecord {
5300                    name: "db".to_string(),
5301                    qualified_name: Some("crate::db".to_string()),
5302                    kind: ReferenceKind::Import,
5303                    byte_range: (0, 6),
5304                    line_range: (0, 0),
5305                    enclosing_symbol_index: Some(0),
5306                },
5307                ReferenceRecord {
5308                    name: "connect".to_string(),
5309                    qualified_name: Some("crate::db::connect".to_string()),
5310                    kind: ReferenceKind::Call,
5311                    byte_range: (10, 16),
5312                    line_range: (1, 1),
5313                    enclosing_symbol_index: Some(0),
5314                },
5315            ],
5316            alias_map: HashMap::new(),
5317            mtime_secs: 0,
5318        };
5319        let state = make_state(vec![
5320            ("src/db.rs", src_target),
5321            ("tests/db.rs", test_target),
5322            ("src/service.rs", src_dependent),
5323            ("tests/helper.rs", test_dependent),
5324        ]);
5325
5326        let result = prompt_context_handler(
5327            State(state),
5328            Query(PromptContextParams {
5329                text: "inspect db.rs:1 connect".to_string(),
5330            }),
5331        )
5332        .await
5333        .unwrap();
5334
5335        assert!(
5336            result.contains("src/service.rs"),
5337            "ambiguous basename should fall back to name-only symbol context: {result}"
5338        );
5339        assert!(
5340            result.contains("tests/helper.rs"),
5341            "ambiguous basename should not collapse to one file hint: {result}"
5342        );
5343    }
5344
5345    #[tokio::test]
5346    async fn test_prompt_context_handler_ambiguous_extensionless_alias_does_not_activate() {
5347        let src_target = make_indexed_file(
5348            "src/db.rs",
5349            vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
5350            vec![],
5351            ParseStatus::Parsed,
5352        );
5353        let test_target = make_indexed_file(
5354            "tests/db.py",
5355            vec![make_symbol("connect", SymbolKind::Function, 1, 1)],
5356            vec![],
5357            ParseStatus::Parsed,
5358        );
5359        let src_dependent = IndexedFile {
5360            relative_path: "src/service.rs".to_string(),
5361            language: LanguageId::Rust,
5362            classification: crate::domain::FileClassification::for_code_path("src/service.rs"),
5363            content: b"use crate::db::connect;\nfn run() { connect(); }\n".to_vec(),
5364            symbols: vec![make_symbol("run", SymbolKind::Function, 2, 2)],
5365            parse_status: ParseStatus::Parsed,
5366            parse_diagnostic: None,
5367            byte_len: 46,
5368            content_hash: "abc".to_string(),
5369            references: vec![
5370                ReferenceRecord {
5371                    name: "db".to_string(),
5372                    qualified_name: Some("crate::db".to_string()),
5373                    kind: ReferenceKind::Import,
5374                    byte_range: (0, 6),
5375                    line_range: (0, 0),
5376                    enclosing_symbol_index: Some(0),
5377                },
5378                ReferenceRecord {
5379                    name: "connect".to_string(),
5380                    qualified_name: Some("crate::db::connect".to_string()),
5381                    kind: ReferenceKind::Call,
5382                    byte_range: (10, 16),
5383                    line_range: (1, 1),
5384                    enclosing_symbol_index: Some(0),
5385                },
5386            ],
5387            alias_map: HashMap::new(),
5388            mtime_secs: 0,
5389        };
5390        let test_dependent = IndexedFile {
5391            relative_path: "tests/helper.py".to_string(),
5392            language: LanguageId::Python,
5393            classification: crate::domain::FileClassification::for_code_path("tests/helper.py"),
5394            content: b"from db import connect\n\ndef helper():\n    connect()\n".to_vec(),
5395            symbols: vec![make_symbol("helper", SymbolKind::Function, 3, 4)],
5396            parse_status: ParseStatus::Parsed,
5397            parse_diagnostic: None,
5398            byte_len: 51,
5399            content_hash: "def".to_string(),
5400            references: vec![
5401                ReferenceRecord {
5402                    name: "db".to_string(),
5403                    qualified_name: Some("db".to_string()),
5404                    kind: ReferenceKind::Import,
5405                    byte_range: (5, 7),
5406                    line_range: (0, 0),
5407                    enclosing_symbol_index: None,
5408                },
5409                ReferenceRecord {
5410                    name: "connect".to_string(),
5411                    qualified_name: Some("db.connect".to_string()),
5412                    kind: ReferenceKind::Call,
5413                    byte_range: (39, 45),
5414                    line_range: (3, 3),
5415                    enclosing_symbol_index: Some(0),
5416                },
5417            ],
5418            alias_map: HashMap::new(),
5419            mtime_secs: 0,
5420        };
5421        let state = make_state(vec![
5422            ("src/db.rs", src_target),
5423            ("tests/db.py", test_target),
5424            ("src/service.rs", src_dependent),
5425            ("tests/helper.py", test_dependent),
5426        ]);
5427
5428        let result = prompt_context_handler(
5429            State(state),
5430            Query(PromptContextParams {
5431                text: "inspect db:1 connect".to_string(),
5432            }),
5433        )
5434        .await
5435        .unwrap();
5436
5437        assert!(
5438            result.contains("src/service.rs"),
5439            "ambiguous extensionless alias should fall back to name-only symbol context: {result}"
5440        );
5441        assert!(
5442            result.contains("tests/helper.py"),
5443            "ambiguous extensionless alias should not collapse to one file hint: {result}"
5444        );
5445    }
5446
5447    // -----------------------------------------------------------------------
5448    // stats_handler
5449    // -----------------------------------------------------------------------
5450
5451    #[tokio::test]
5452    async fn test_stats_handler_returns_snapshot() {
5453        let state = make_state(vec![]);
5454        // Record some stats manually.
5455        state.token_stats.record_read(1000, 200);
5456        state.token_stats.record_write();
5457
5458        let result = stats_handler(State(state)).await;
5459        let snap = result.0;
5460        assert_eq!(snap.read_fires, 1);
5461        assert_eq!(snap.write_fires, 1);
5462        assert_eq!(snap.read_saved_tokens, 200);
5463    }
5464}