diff --git a/CHANGELOG.md b/CHANGELOG.md index ad51b48..1ef9d08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,18 @@ All notable changes to srcwalk are documented here. -## Unreleased +## [1.6.0] - 2026-08-12 + +### Added +- Default-on Go structural owner attribution and bounded mechanical call evidence for `discover --match any --as text`: compact file rollups include a narrowest-owner rollup (`owners (#N=Nth query term; *K=hits)`) and a `## Mechanical Go calls` appendix with capped (≤10), deterministically ordered, same-file `@:`-elided direct-call edges. + +### Changed +- Go owner evidence is now emitted by default (no opt-in flag). It is navigation evidence only, not runtime order, dynamic dispatch, or an inferred chain; zero-edge owners abstain with an explicit caveat. Owner ranges are candidate exact reads, not relation or binding proof. + +### Docs +- `skills/srcwalk/GUIDE.md` documents the owner rollup, the `[recv]`/`[local]`/`[bare]` edge labels, the `calls NAME` = call-expression-name honesty note, `@:` same-file elision, and the mechanical-filter/dynamic-dispatch caveat. + +Known behavior: on very large monorepos, initial scope-narrowing may add extra navigation turns (srcwalk-general behavior, unrelated to owner evidence; observed in one eval3 run; tokens remained neutral-to-better). ## [1.5.0] - 2026-08-10 diff --git a/Cargo.lock b/Cargo.lock index 3cfb031..77d292c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -678,7 +678,7 @@ checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] name = "srcwalk" -version = "1.5.0" +version = "1.6.0" dependencies = [ "aho-corasick", "clap", diff --git a/Cargo.toml b/Cargo.toml index f085df1..4fabdf2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "srcwalk" -version = "1.5.0" +version = "1.6.0" edition = "2021" description = "Tree-sitter indexed lookups — smart code reading for AI agents" license = "MIT" diff --git a/README.md b/README.md index ed537b2..e828aa7 100644 --- a/README.md +++ b/README.md @@ -408,6 +408,39 @@ source: text · kind: name occurrence · confidence: text evidence ``` +
+Discover — Go owner rollup and mechanical call evidence + +For compact Go `discover --as text --match any` output, matching file rows may include a narrowest-owner rollup and a bounded mechanical call appendix. Owner ranges are candidate exact reads (dereference them with `srcwalk show`), not runtime binding proof. + +``` +$ srcwalk discover "apply body,set body,connect body" --match any --as text --scope . +# Text OR: "apply body,set body,connect body" in . — 3 terms, 3 matches, 1 file +> Caveat: literal OR text evidence only; not semantic relation proof. + +## Files ranked by term coverage +db.go — 3 terms, 3 shown matches + terms: apply body(1), connect body(1), set body(1) + hits: :4, :5, :6 + owners (#N=Nth query term; *K=hits): DB.Apply:4-4[#1]; DB.Set:5-5[#2]; connect:6-6[#3] + windows: :4-6 terms=apply body(1), connect body(1), set body(1) + > Next: srcwalk show db.go --section 4-6 -C 10 +> Caveat: hit-window proximity is literal navigation evidence, not semantic relation proof. + +## Terms +apply body — 1/1 matches, 1 file +set body — 1/1 matches, 1 file +connect body — 1/1 matches, 1 file + +## Mechanical Go calls [recv=same package-qualified receiver type; local=single-assignment constructor; calls NAME=call-expression name, not candidate binding; bare=same-package invocation] +- [recv] DB.Set calls Apply@db.go:5; candidate DB.Apply@:4-4 + +> Caveat: structural owner and mechanically filtered direct-call evidence only; not runtime order, dynamic dispatch, or an inferred chain. +``` + +`owners (#N...` attributes each matched line to its narrowest structural owner by original query-term position; `#N*K` means owner hit K times for query term N. `[recv]` marks a same package-qualified receiver type, `[local]` a single-assignment constructor local, and `[bare]` a same-package invocation. `calls NAME` names the call expression, not the candidate binding; `candidate ...@:` means the definition is in the same file as the call (cross-file candidates keep the repo-relative path). Owner ranges are navigation candidates, not relation or runtime proof. +
+
Multi-hop caller BFS diff --git a/npm/package.json b/npm/package.json index bc4db65..145a02c 100644 --- a/npm/package.json +++ b/npm/package.json @@ -1,6 +1,6 @@ { "name": "srcwalk", - "version": "1.5.0", + "version": "1.6.0", "description": "Code-intelligence CLI for AI agents — tree-sitter outlines, symbol search, caller/callee graphs, deps, overview", "bin": { "srcwalk": "run.js" diff --git a/skills/srcwalk/GUIDE.md b/skills/srcwalk/GUIDE.md index 33f84c2..5952d27 100644 --- a/skills/srcwalk/GUIDE.md +++ b/skills/srcwalk/GUIDE.md @@ -64,12 +64,18 @@ srcwalk discover 'foo,bar,baz' --match any --as text --scope # literal te Use auto overview depth first; explicit `--depth N` is strict. Narrow `overview --symbols` shows inline `kind name@line-range` anchors when budget allows; broad auto overview may summarize areas/candidates and emit narrow-scope drilldowns. -Intent inference: path-like globs infer file discovery; punctuation/path comma lists infer literal Text OR; symbol globs stay symbol search. Add `--as symbol|file|text|access` when ambiguous. After a first pass, use `--expand=3`, `--filter kind:fn`, or `--exclude 'tests/**'` only when output is too broad. Regex-style queries are translated, not executed as regex: `foo\(` de-escapes to literal + symbol search, `a.*b` runs same-line ordered co-occurrence, `models\.json` behaves like `models.json`, and an unresolved path fragment like `packages/ai` lists matching relative paths (≤20). Each translation is labeled `interpreted as`; zero-match branches print a `> Try:` recovery line. Windows drive paths and `./`/`../` paths are never treated as regex. +Intent inference: path-like globs infer file discovery; punctuation/path comma lists infer literal Text OR; symbol globs stay symbol search. Add `--as symbol|file|text|access` when ambiguous. After a first pass, use `--expand=3`, `--filter kind:fn`, or `--exclude 'tests/**'` only when output is too broad. Regex-style queries are translated, not executed as regex: `foo\(` de-escapes to literal + symbol search, `a.*b` runs same-line ordered co-occurrence, `models\.json` behaves like `models.json`, and an unresolved path fragment like `packages/ai` lists matching relative paths (≤20). Each translation is labeled `interpreted as`; zero-match branches print a `> Try:` recovery line. Windows drive paths and `./`/`../` paths are never treated as regex. Text Search and Text OR may add a conditional `> Note:` when a term has at least 400 matches across at least 150 files and reaches at least 1.5% of eligible files; treat it as measured spread, then consider `overview`, a narrower term or scope, or a structural route when that spread was not intentional. -If `discover` prints `## Confirmed structural targets`, run the matching `srcwalk show :` first. Use `srcwalk context ` only when you need a Flow Map, scoped occurrences, or call neighborhood; do not run `context` for each hop just to read source. +If `discover` prints `## Confirmed structural targets`, run the printed `> Next:` command verbatim. It is symbol-addressed (`show --section `) when the selector round-trips to the exact body; a numeric `:` command is the safe fallback when ambiguity prevents a unique symbol selector. A numeric range shown beside a stable symbol is evidence metadata (a bounded preview), not the preferred body address. Use `srcwalk context ` only when you need a Flow Map, scoped occurrences, or call neighborhood; do not run `context` for each hop just to read source. Symbol discovery separates parser-backed definitions from text-matched name occurrences. Repeated same-name definitions receive an ambiguity caveat. Text discovery remains literal evidence; `--match all` is same-file co-occurrence, not semantic relation proof. +For Go `discover --as text --match any`, matched lines may carry a structural owner rollup and a bounded mechanical call appendix: +- `owners (#N=...; *K=hits)` lists each matched line's narrowest structural owner by query-term position; the range is a candidate exact read (`srcwalk show`), not relation or runtime binding proof. +- Edge labels: `[recv]`=same package-qualified receiver type, `[local]`=single-assignment constructor local, `[bare]`=same-package invocation. +- `calls NAME` names the call expression, not the candidate binding; the candidate is a mechanically filtered definition candidate, not a proven binding. +- Edges are mechanically filtered direct-call navigation (absence does not rule out dynamic dispatch, DI, callbacks, or protocol wiring); `@:` = candidate in the same call file, cross-file keeps the repo-relative path. Capped, deterministically ordered; zero-edge owners abstain with an explicit caveat. + ### Understand one target or read exact evidence Use `show` for known bodies and citations. Use `context` when the task needs a rich local packet such as Flow Map, scoped occurrences, or call neighborhood. Exact path/range contexts may include bounded `Source Evidence`; `show` `Source frame` lines orient exact numeric reads and numeric `--section` blocks, not relation proof. @@ -89,7 +95,7 @@ Do not pass a bare file to `context`; use `show` or root reads. `context` accept ### Trace calls -Use `trace callers` for upstream call sites and `trace callees` for downstream calls. Do not grep `foo(` for relation claims. Long result lists collapse to the top entries plus a `+N more → ` pointer, and wide evidence ranges may appear as an anchor plus an `expand: ` line. These pointer lines are exact commands: run them verbatim when you need the remaining items or the full range. Nothing is dropped — collapsed items are always one command away. +Use `trace callers` for upstream call sites and `trace callees` for downstream calls. Do not grep `foo(` for relation claims. Long result lists collapse to the top entries plus a `+N more → ` pointer, and wide evidence ranges may appear as an anchor plus an `expand: ` line. These pointer lines are exact commands: run them verbatim when you need the remaining items or the full range. Nothing is dropped — collapsed items are always one command away. Drill down with exact call-site reads or `context` on a caller/callee. ```bash srcwalk trace callers --scope @@ -97,19 +103,15 @@ srcwalk trace callees --detailed --scope srcwalk trace callees --depth 2 --scope ``` -Drill down with exact call-site reads or `context` on a caller/callee. - ### Inspect file coupling -Use `deps` for imports, links/assets, local symbol deps, and dependents. Run it before file moves, deletes, or coupling explanations. For JS/TS/TSX, alias-derived edges marked `(via tsconfig paths)` are config-derived static evidence, not runtime proof, and `Uses (unresolved local-looking)` lists local-looking specifiers (`./`, `../`, `@/`, `~/`) that resolve to no existing file — known-missing local references, not external packages. +Use `deps` for imports, links/assets, local symbol deps, and dependents. Run it before file moves, deletes, or coupling explanations. Do not grep import/use/require/link tags for dependency claims. For JS/TS/TSX, alias-derived edges marked `(via tsconfig paths)` are config-derived static evidence, not runtime proof, and `Uses (unresolved local-looking)` lists local-looking specifiers (`./`, `../`, `@/`, `~/`) that resolve to no existing file — known-missing local references, not external packages. ```bash srcwalk deps srcwalk context --scope ``` -Do not grep import/use/require/link tags for dependency claims. - ### Assess and review changes `assess` is blast-radius triage; verify risky results with `trace callers` or `deps`. `review` composes changed evidence with bounded Flow Maps for changed function-like symbols. @@ -133,14 +135,12 @@ srcwalk compare --scope ### Confirm raw text or filesystem metadata -Use `rg` for raw regex and regex flags; srcwalk translates common regex-style queries into literal/co-occurrence searches but never runs a regex engine. srcwalk text discovery is literal evidence plus navigation context. Use shell `find`/`fd` only for filesystem metadata: permissions, mtimes, empty dirs, symlinks, binary assets, generated outputs, cleanup lists. +Use `rg` for raw regex and regex flags; srcwalk translates common regex-style queries into literal/co-occurrence searches but never runs a regex engine. srcwalk text discovery is literal evidence plus navigation context. Use shell `find`/`fd` only for filesystem metadata: permissions, mtimes, empty dirs, symlinks, binary assets, generated outputs, cleanup lists. Do not infer definitions, usages, callers, deps, or code paths from shell path lists, or convert identifiers into paths without evidence. ```bash rg '' ``` -Do not infer definitions, usages, callers, deps, or code paths from shell path lists. Do not convert identifiers into paths without evidence. - ## Artifact and language support Exact artifact reads/scopes may auto-enable artifact mode. Use `--artifact` for broad generated, bundled, minified, or binary-like traversal. Prefer exact footer commands. Artifact output is byte-span evidence only. diff --git a/src/commands/find.rs b/src/commands/find.rs index ca2504d..caf65f9 100644 --- a/src/commands/find.rs +++ b/src/commands/find.rs @@ -10,6 +10,11 @@ use crate::commands::multi_scope::{ parse_multi_symbol_query, unsupported_find_syntax_error, use_files_error, }; use crate::commands::section_disambiguation::disambiguate_glob_for_section; +use crate::evidence::owner_links::OWNER_NON_GO_CAVEAT; +use crate::evidence::owner_links::{ + build_owner_link_evidence, OwnerAnchor, OwnerCallMechanism, OwnerLinkEvidence, + OwnerLinkHitInput, OWNER_LINK_CAVEAT, OWNER_LINK_EDGE_CAP, OWNER_LINK_ZERO_EDGE, +}; use crate::evidence::{render_next_actions, NextAction}; use crate::types::{Match, QueryType, RegexCoOccurrenceQuery, RegexTextKind, RegexTextQuery}; use crate::OutlineCache; @@ -26,6 +31,20 @@ const TEXT_OR_WINDOW_CONTEXT_LINES: u32 = 10; const TEXT_OR_WINDOW_LIMIT: usize = 3; const TEXT_OR_WINDOW_MAX_SPAN: u32 = 80; +/// Mechanism tags + `calls NAME` honesty note, in a one-line legend framing. +const OWNER_LINK_MECH_LEGEND: &str = + "[recv=same package-qualified receiver type; local=single-assignment constructor; calls NAME=call-expression name, not candidate binding; bare=same-package invocation]"; + +/// Short stable tag for a call mechanism, kept plain-language. +fn owner_call_mechanism_tag(m: OwnerCallMechanism) -> &'static str { + match m { + OwnerCallMechanism::SingleAssignmentLocalConstructor => "local", + OwnerCallMechanism::CrossFileSameQualifiedReceiver + | OwnerCallMechanism::SameFileSameQualifiedReceiver => "recv", + OwnerCallMechanism::SamePackageBareInvocation => "bare", + } +} + fn comma_terms(query: &str) -> Vec<&str> { query .split(',') @@ -34,6 +53,24 @@ fn comma_terms(query: &str) -> Vec<&str> { .collect() } +/// Original 1-based comma-separated term positions (before dedup/drop). +/// Empty slots are dropped but NOT renumbered, so `#N` is honest occurrence +/// identity: `alpha,alpha,,missing,beta` -> [(1,alpha),(2,alpha),(4,missing),(5,beta)]. +fn indexed_comma_terms(query: &str) -> Vec<(usize, &str)> { + query + .split(',') + .enumerate() + .filter_map(|(i, t)| { + let t = t.trim(); + if t.is_empty() { + None + } else { + Some((i + 1, t)) + } + }) + .collect() +} + /// classify → match on query type → return formatted string. pub(crate) fn run( query: &str, @@ -121,8 +158,10 @@ pub(crate) fn run_text_filtered_with_artifact_and_hint( literal_comma_hint: bool, cache: &OutlineCache, ) -> Result { - let mut result = search::search_content_raw_with_artifact(query, scope, glob, artifact)?; + let mut result = + search::search_content_raw_with_artifact_counting(query, scope, glob, artifact)?; search::apply_general_filter(&mut result, scope, cache, filter)?; + let advisory = search::low_signal_term_advisory(&search::low_signal_term_stats(query, &result)); search::pagination::paginate(&mut result, limit, offset); search::compact_artifact_snippets(&mut result, artifact); let mut output = search::format_raw_result(&result, cache)?; @@ -131,6 +170,10 @@ pub(crate) fn run_text_filtered_with_artifact_and_hint( "\n\n> Hint: treated as one literal text query. Use `--match any --as text` for comma-separated literal OR, or `--match all --as text` for same-file co-occurrence.", ); } + let output = match advisory { + Some(note) => search::insert_low_signal_advisories(output, std::slice::from_ref(¬e)), + None => output, + }; let output = with_artifact_note(output, artifact); match budget_tokens { Some(budget) => Ok(budget::apply_preserving_footer(&output, budget)), @@ -151,6 +194,7 @@ pub(crate) fn run_text_or_filtered_with_artifact( cache: &OutlineCache, ) -> Result { let terms = comma_terms(query); + let indexed_terms = indexed_comma_terms(query); if terms.len() < 2 { return Err(SrcwalkError::InvalidQuery { query: query.to_string(), @@ -168,10 +212,17 @@ pub(crate) fn run_text_or_filtered_with_artifact( let mut total_found = 0usize; let mut total_files = BTreeSet::new(); let mut term_results = Vec::with_capacity(terms.len()); + let mut advisories = Vec::new(); - for term in &terms { - let mut result = search::search_content_raw_with_artifact(term, scope, glob, artifact)?; + for (query_term_index, term) in &indexed_terms { + let mut result = + search::search_content_raw_with_artifact_counting(term, scope, glob, artifact)?; search::apply_general_filter(&mut result, scope, cache, filter)?; + if let Some(note) = + search::low_signal_term_advisory(&search::low_signal_term_stats(term, &result)) + { + advisories.push(note); + } total_found += result.total_found; let file_count = result .matches @@ -189,6 +240,7 @@ pub(crate) fn run_text_or_filtered_with_artifact( let omitted = result.total_found.saturating_sub(shown_so_far); term_results.push(TextOrTermResult { + query_term_index: *query_term_index, term: (*term).to_string(), total_found: result.total_found, file_count, @@ -197,14 +249,29 @@ pub(crate) fn run_text_or_filtered_with_artifact( }); } + let owner_links = if artifact.enabled() { + OwnerLinkEvidence::default() + } else { + let inputs = term_results + .iter() + .flat_map(|result| { + result.matches.iter().map(|matched| OwnerLinkHitInput { + path: &matched.path, + line: matched.line, + }) + }) + .collect::>(); + build_owner_link_evidence(&inputs) + }; + let compact = terms.len() >= TEXT_OR_COMPACT_MIN_TERMS || total_found > TEXT_OR_COMPACT_MIN_MATCHES; let (rendered, has_specific_next) = if compact { - let rollup = render_text_or_file_rollup(&term_results, scope); + let rollup = render_text_or_file_rollup(&term_results, scope, &owner_links); (rollup.body, rollup.has_specific_next) } else { ( - render_text_or_term_details(&term_results, term_limit, scope), + render_text_or_term_details(&term_results, term_limit, scope, &owner_links), false, ) }; @@ -219,6 +286,10 @@ pub(crate) fn run_text_or_filtered_with_artifact( text_or_file_word(total_files.len()), rendered ); + output.push_str(&render_owner_link_appendix(&owner_links, scope)); + if !advisories.is_empty() { + output = search::insert_low_signal_advisories(output, &advisories); + } if total_found > 0 && (!has_specific_next || artifact.enabled()) { let rendered = render_next_actions(&[NextAction::guidance( "read raw hit evidence with `srcwalk show : -C 10`.", @@ -238,6 +309,10 @@ pub(crate) fn run_text_or_filtered_with_artifact( } struct TextOrTermResult { + /// 1-based position in the ORIGINAL comma-separated user input, before any + /// dedup/normalization/drop. Zero-hit and empty-invalid slots keep their + /// original index (never renumbered), so `#N` is honest occurrence identity. + query_term_index: usize, term: String, total_found: usize, file_count: usize, @@ -249,6 +324,7 @@ fn render_text_or_term_details( term_results: &[TextOrTermResult], term_limit: usize, scope: &Path, + owner_links: &OwnerLinkEvidence, ) -> String { use std::fmt::Write as _; @@ -260,15 +336,7 @@ fn render_text_or_term_details( "\n\n## {} — {shown}/{} matches", result.term, result.total_found ); - for m in &result.matches { - let _ = write!( - rendered, - "\n {}:{} — {}", - format::rel_nonempty(&m.path, scope), - m.line, - m.text.trim() - ); - } + render_text_or_term_matches(&mut rendered, &result.matches, scope, owner_links); if result.omitted > 0 { let _ = write!( rendered, @@ -280,6 +348,167 @@ fn render_text_or_term_details( rendered } +/// Render one term's visible matches, grouping same-file hits >= 2 and folding +/// contiguous equal-owner runs of >= 3 (owner K=3). Single-hit files keep the +/// current one-line shape. For multi-hit files, the grouped candidate wins only +/// when it is strictly fewer UTF-8 bytes than the ungrouped inline rows; a tie +/// keeps the current ungrouped inline shape. +/// +/// Ordering semantics: the per-file decision (grouped vs inline) is precomputed +/// once, then the ORIGINAL visible slice is iterated in order. A profitable +/// (grouped) file emits its whole group at the first occurrence of that path and +/// later occurrences are consumed; an unprofitable or single-hit file emits each +/// row at its original position. This keeps rejected/tied file rows in their +/// original relative order instead of clustering them together. +fn render_text_or_term_matches( + rendered: &mut String, + matches: &[Match], + scope: &Path, + owner_links: &OwnerLinkEvidence, +) { + use std::collections::HashMap; + use std::fmt::Write as _; + + // Group by path preserving first-appearance order. + let mut files: Vec<(&Path, Vec<&Match>)> = Vec::new(); + for m in matches { + match files.iter_mut().find(|(p, _)| *p == m.path.as_path()) { + Some((_, group)) => group.push(m), + None => files.push((m.path.as_path(), vec![m])), + } + } + + // Precompute the per-path rendering decision: `Some(grouped)` when the + // grouped candidate is strictly smaller than the inline rows, `None` when + // the file is single-hit or grouping ties/loses (emits rows inline). + let mut grouped_by_path: HashMap<&Path, String> = HashMap::new(); + for (path, group) in &files { + if group.len() < 2 { + continue; + } + let mut grouped_candidate = String::new(); + let _ = write!( + grouped_candidate, + "\n {} [{} matches]", + format::rel_nonempty(path, scope), + group.len() + ); + render_owner_runs(&mut grouped_candidate, group, owner_links); + + let mut ungrouped_candidate = String::new(); + render_text_or_term_ungrouped(&mut ungrouped_candidate, group, path, scope, owner_links); + + if grouped_candidate.len() < ungrouped_candidate.len() { + grouped_by_path.insert(path, grouped_candidate); + } + } + + // Iterate the original visible slice. Emit a profitable group once at its + // first occurrence; emit every other row at its original position. + let mut emitted: std::collections::HashSet<&Path> = std::collections::HashSet::new(); + for m in matches { + let path = m.path.as_path(); + if let Some(grouped) = grouped_by_path.get(path) { + if emitted.insert(path) { + rendered.push_str(grouped); + } + // Later occurrences of an emitted profitable group are consumed. + continue; + } + // Single-hit or unprofitable/tied: emit this row at its position. + render_text_or_term_ungrouped(rendered, &[m], path, scope, owner_links); + } +} + +/// Render every hit in a file as a one-line inline row (the ungrouped shape). +fn render_text_or_term_ungrouped( + rendered: &mut String, + group: &[&Match], + path: &Path, + scope: &Path, + owner_links: &OwnerLinkEvidence, +) { + use std::fmt::Write as _; + for m in group { + let owner = owner_tag_inline(owner_links, m); + let _ = write!( + rendered, + "\n {}:{}{} — {}", + format::rel_nonempty(path, scope), + m.line, + owner, + m.text.trim() + ); + } +} + +/// Render a multi-hit file group's child rows, folding contiguous runs of >= 3 +/// hits with the exact same owner anchor into an owner subgroup header. +fn render_owner_runs(rendered: &mut String, group: &[&Match], owner_links: &OwnerLinkEvidence) { + use std::fmt::Write as _; + + let mut i = 0; + while i < group.len() { + let owner = owner_links.owner_for(&group[i].path, group[i].line); + // Find the contiguous run sharing the same owner anchor. + let mut j = i + 1; + while j < group.len() + && owners_equal(owner, owner_links.owner_for(&group[j].path, group[j].line)) + { + j += 1; + } + let run_len = j - i; + if let Some(owner) = owner.filter(|_| run_len >= 3) { + // K=3 fold: owner once as a subgroup header. + let _ = write!( + rendered, + "\n [owner {}@{}-{}] [{} hits]", + owner.qualified_name(), + owner.start_line, + owner.end_line, + run_len + ); + for m in &group[i..j] { + let _ = write!(rendered, "\n :{} — {}", m.line, m.text.trim()); + } + } else { + // Runs of 1-2, unique/mixed owners, or unattributed stay inline. + for m in &group[i..j] { + let owner = owner_tag_inline(owner_links, m); + let _ = write!(rendered, "\n :{}{} — {}", m.line, owner, m.text.trim()); + } + } + i = j; + } +} + +/// Owner anchor tag with a leading space for inline hit rows, or empty string. +fn owner_tag_inline(owner_links: &OwnerLinkEvidence, m: &Match) -> String { + owner_links + .owner_for(&m.path, m.line) + .map_or_else(String::new, |owner| { + format!( + " [owner {}@{}-{}]", + owner.qualified_name(), + owner.start_line, + owner.end_line + ) + }) +} + +/// Whether two owner anchors are the same (same qualified name and range). +fn owners_equal(a: Option<&OwnerAnchor>, b: Option<&OwnerAnchor>) -> bool { + match (a, b) { + (Some(x), Some(y)) => { + x.qualified_name() == y.qualified_name() + && x.start_line == y.start_line + && x.end_line == y.end_line + } + (None, None) => true, + _ => false, + } +} + struct TextOrRollupRender { body: String, has_specific_next: bool, @@ -288,6 +517,7 @@ struct TextOrRollupRender { fn render_text_or_file_rollup( term_results: &[TextOrTermResult], scope: &Path, + owner_links: &OwnerLinkEvidence, ) -> TextOrRollupRender { use std::fmt::Write as _; @@ -357,6 +587,7 @@ fn render_text_or_file_rollup( file.lines.len() - TEXT_OR_ROLLUP_LINE_LIMIT ); } + render_text_or_owner_rollup(&mut rendered, &file.path, owner_links, term_results); let windows = text_or_select_hit_windows(file); if !windows.is_empty() { let summaries = windows @@ -428,6 +659,130 @@ fn render_text_or_file_rollup( } } +fn render_text_or_owner_rollup( + rendered: &mut String, + path: &Path, + owner_links: &OwnerLinkEvidence, + term_results: &[TextOrTermResult], +) { + use std::fmt::Write as _; + + // Aggregate owners by each indexed result's matches + owner attribution. + // `#N` is the ORIGINAL comma-separated position (query_term_index), so + // exact duplicate terms keep distinct honest indices. `#N` alone = count 1; + // `#N*K` = count K. + let mut owners: BTreeMap> = BTreeMap::new(); + for result in term_results { + for m in &result.matches { + if m.path != *path { + continue; + } + if let Some(owner) = owner_links.owner_for(&m.path, m.line) { + *owners + .entry(owner.clone()) + .or_default() + .entry(result.query_term_index) + .or_insert(0) += 1; + } + } + } + if owners.is_empty() { + return; + } + let summaries = owners + .into_iter() + .map(|(owner, terms)| { + let terms = terms + .into_iter() + .map(|(index, count)| { + if count <= 1 { + format!("#{index}") + } else { + format!("#{index}*{count}") + } + }) + .collect::>() + .join(","); + // The file path is already explicit in the enclosing file-scoped + // rollup header, so owner anchors use `:start-end` only. + format!( + "{}:{}-{}[{terms}]", + owner.qualified_name(), + owner.start_line, + owner.end_line + ) + }) + .collect::>() + .join("; "); + let _ = write!( + rendered, + "\n owners (#N=Nth query term; *K=hits): {summaries}" + ); +} + +fn render_owner_link_appendix(owner_links: &OwnerLinkEvidence, scope: &Path) -> String { + use std::fmt::Write as _; + + if !owner_links.has_owners() { + return String::new(); + } + let mut rendered = String::new(); + + // The Go mechanical-call appendix (zero-edge sentence, "## Mechanical Go + // calls", and its call-specific caveat) is gated only by an explicit, + // SUCCESSFUL Go call-analysis attempt PLUS actual Go owner evidence. It is + // never driven by non-Go owner presence. + if owner_links.go_call_analysis_attempted && owner_links.has_go_owners() { + if owner_links.edges.is_empty() { + // The zero-edge sentence means "no direct call evidence among the + // Go hit owners". It is only valid for a Go-only result, and only + // when at least two distinct Go owners exist (so the claim is + // meaningful). Non-Go owners must not satisfy its threshold. + if !owner_links.has_non_go_owners() && owner_links.attributed_go_owner_count() >= 2 { + let _ = write!(rendered, "\n\n{OWNER_LINK_ZERO_EDGE}"); + } + } else { + rendered.push_str("\n\n## Mechanical Go calls "); + rendered.push_str(OWNER_LINK_MECH_LEGEND); + for edge in owner_links.edges.iter().take(OWNER_LINK_EDGE_CAP) { + let call_path = format::rel_nonempty(&edge.caller.path, scope); + let cand_path = format::rel_nonempty(&edge.candidate.path, scope); + // `@:` explicitly means the same call file; cross-file candidates + // keep the full repo-relative path. + let cand_loc = if call_path == cand_path { + format!( + "@:{}-{}", + edge.candidate.start_line, edge.candidate.end_line + ) + } else { + format!( + "@{cand_path}:{}-{}", + edge.candidate.start_line, edge.candidate.end_line + ) + }; + let _ = write!( + rendered, + "\n- [{}] {} calls {}@{call_path}:{}; candidate {}{cand_loc}", + owner_call_mechanism_tag(edge.mechanism), + edge.caller.qualified_name(), + edge.callee_name, + edge.call_line, + edge.candidate.qualified_name() + ); + } + } + let _ = write!(rendered, "\n\n{OWNER_LINK_CAVEAT}"); + } + + // Non-Go owner attribution gets its own concise honesty caveat, gated by + // actually rendered non-Go owner evidence. It must not imply call analysis + // ran for non-Go languages. + if owner_links.has_non_go_owners() { + let _ = write!(rendered, "\n\n{OWNER_NON_GO_CAVEAT}"); + } + rendered +} + struct TextOrFileRollup { path: PathBuf, term_counts: BTreeMap, @@ -714,6 +1069,7 @@ pub(crate) fn run_cooccurrence_filtered_with_artifact( query: query.to_string(), scope: scope.to_path_buf(), total_found: matches.len(), + eligible_files: 0, definition_candidates: definitions, name_occurrence_candidates: matches .iter() @@ -1659,3 +2015,824 @@ pub(crate) fn symbol_or_file_suggestion( } read::suggest_similar_file(scope, query) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::evidence::owner_links::{OwnedTextHit, OwnerAnchor, OwnerCallEvidence}; + use std::path::PathBuf; + + /// Single parser that recovers (`tag`, `caller`, `callee`, `call_file`, + /// `call_line`, `candidate`, `def_range`) from one rendered bullet. The candidate location is + /// `@:start-end` (same call file) or `@full/path:start-end` (cross-file). + /// Location separators are resolved rightmost (`rsplit_once(':')`) so windows + /// drive paths like `C:\repo\pkg\a.go:22` parse correctly. + struct ParsedEdge { + tag: String, + caller: String, + callee: String, + call_file: String, + call_line: u32, + candidate: String, + cand_file: String, + def_range: String, + } + + fn parse_edge(b: &str) -> Option { + let rest = b.strip_prefix("- [")?; + let (tag, rest) = rest.split_once(']')?; + let rest = rest.strip_prefix(' ')?; + let (caller, rest) = rest.split_once(" calls ")?; + // rest = `CALLEE@PATH:LINE; candidate CANDIDATE@LOC` + let (callee, rest) = rest.split_once('@')?; + let (call_site, cand_site) = rest.split_once("; candidate ")?; + let (call_file, call_line) = rsplit_once_colon(call_site)?; + let (candidate, cand_loc) = cand_site.split_once('@')?; + let (cand_file, def_range) = if let Some(r) = cand_loc.strip_prefix(':') { + (call_file.to_string(), r.to_string()) + } else { + let (f, r) = rsplit_once_colon(cand_loc)?; + (f.to_string(), r.to_string()) + }; + Some(ParsedEdge { + tag: tag.to_string(), + caller: caller.to_string(), + callee: callee.to_string(), + call_file: call_file.to_string(), + call_line: call_line.to_string().parse().ok()?, + candidate: candidate.to_string(), + cand_file, + def_range, + }) + } + + fn rsplit_once_colon(s: &str) -> Option<(&str, &str)> { + let idx = s.rfind(':')?; + Some((&s[..idx], &s[idx + 1..])) + } + + fn anchor(path: &str, name: &str, receiver: &str, s: u32, e: u32) -> OwnerAnchor { + let display_name = if receiver.is_empty() { + name.to_string() + } else { + format!("{receiver}.{name}") + }; + OwnerAnchor { + path: PathBuf::from(path), + name: name.into(), + receiver_var: None, + receiver_type: (!receiver.is_empty()).then(|| receiver.to_string()), + package_dir: PathBuf::from("."), + start_line: s, + end_line: e, + language: crate::types::Lang::Go, + display_name, + } + } + + fn render(edges: &[OwnerCallEvidence]) -> String { + // Seed one hit so has_owners() holds; the appendix renders edges + // independently of hit content. + let anchor = anchor("seed.go", "Seed", "S", 1, 1); + let hits = vec![OwnedTextHit { + path: anchor.path.clone(), + line: 1, + owner: anchor, + }]; + let ev = OwnerLinkEvidence { + hits, + edges: edges.to_vec(), + go_call_analysis_attempted: true, + }; + render_owner_link_appendix(&ev, Path::new("")) + } + + #[test] + fn edge_bullets_round_trip_same_file_elision_and_cross_file() { + let same_file = OwnerCallEvidence { + caller: anchor("pkg/a.go", "Set", "DB", 10, 40), + call_line: 22, + callee_name: "Apply".into(), + candidate: anchor("pkg/a.go", "Apply", "DB", 30, 60), + mechanism: OwnerCallMechanism::SameFileSameQualifiedReceiver, + }; + let cross_file = OwnerCallEvidence { + caller: anchor("pkg/a.go", "SyncPod", "Kubelet", 5, 50), + call_line: 12, + callee_name: "killPod".into(), + candidate: anchor("pkg/kubelet/sub.go", "killPod", "Kubelet", 7, 20), + mechanism: OwnerCallMechanism::CrossFileSameQualifiedReceiver, + }; + let bare = OwnerCallEvidence { + caller: anchor("pkg/b.go", "Run", "", 1, 9), + call_line: 3, + callee_name: "cleanup".into(), + candidate: anchor("pkg/b.go", "cleanup", "", 2, 4), + mechanism: OwnerCallMechanism::SamePackageBareInvocation, + }; + let local = OwnerCallEvidence { + caller: anchor("pkg/c.go", "Setup", "", 1, 9), + call_line: 5, + callee_name: "Connect".into(), + candidate: anchor("pkg/c.go", "Connect", "Pool", 2, 6), + mechanism: OwnerCallMechanism::SingleAssignmentLocalConstructor, + }; + + let out = render(&[same_file, cross_file, bare, local]); + let bullets: Vec<&str> = out.lines().filter(|l| l.starts_with("- ")).collect(); + assert_eq!(bullets.len(), 4, "{out}"); + + let e0 = parse_edge(bullets[0]).unwrap(); + assert_eq!( + (e0.tag.as_str(), e0.caller.as_str(), e0.callee.as_str()), + ("recv", "DB.Set", "Apply") + ); + assert_eq!(e0.call_file, "pkg/a.go"); + assert_eq!(e0.call_line, 22); + assert_eq!(e0.candidate, "DB.Apply"); + assert_eq!(e0.cand_file, "pkg/a.go"); + assert_eq!(e0.def_range, "30-60"); + + let e1 = parse_edge(bullets[1]).unwrap(); + assert_eq!( + (e1.tag.as_str(), e1.caller.as_str()), + ("recv", "Kubelet.SyncPod") + ); + assert_eq!(e1.call_file, "pkg/a.go"); + assert_eq!(e1.call_line, 12); + assert_eq!(e1.candidate, "Kubelet.killPod"); + assert_eq!(e1.cand_file, "pkg/kubelet/sub.go"); + assert_eq!(e1.def_range, "7-20"); + + let e2 = parse_edge(bullets[2]).unwrap(); + assert_eq!( + (e2.tag.as_str(), e2.caller.as_str(), e2.callee.as_str()), + ("bare", "Run", "cleanup") + ); + assert_eq!(e2.call_file, "pkg/b.go"); + assert_eq!(e2.call_line, 3); + assert_eq!(e2.cand_file, "pkg/b.go"); + assert_eq!(e2.def_range, "2-4"); + + // `[local]` = single-assignment constructor local. + let e3 = parse_edge(bullets[3]).unwrap(); + assert_eq!( + (e3.tag.as_str(), e3.caller.as_str(), e3.callee.as_str()), + ("local", "Setup", "Connect") + ); + assert_eq!(e3.call_file, "pkg/c.go"); + assert_eq!(e3.call_line, 5); + assert_eq!(e3.cand_file, "pkg/c.go"); + assert_eq!(e3.def_range, "2-6"); + + // Legend must be present exactly once. + assert_eq!( + out.matches("[recv=same package-qualified receiver type") + .count(), + 1, + "{out}" + ); + } + + #[test] + fn edge_bullets_parse_windows_drive_paths_and_colon_safe() { + // Windows drive path in the call site; `@:` sentinel for same-file candidate. + let same_win = OwnerCallEvidence { + caller: anchor(r"C:\repo\pkg\a.go", "Run", "DB", 10, 40), + call_line: 22, + callee_name: "Apply".into(), + candidate: anchor(r"C:\repo\pkg\a.go", "Apply", "DB", 30, 60), + mechanism: OwnerCallMechanism::SameFileSameQualifiedReceiver, + }; + // Cross-file windows candidate keeps full path. + let cross_win = OwnerCallEvidence { + caller: anchor(r"C:\repo\pkg\a.go", "SyncPod", "Kubelet", 5, 50), + call_line: 12, + callee_name: "killPod".into(), + candidate: anchor(r"C:\repo\pkg\sub.go", "killPod", "Kubelet", 7, 20), + mechanism: OwnerCallMechanism::CrossFileSameQualifiedReceiver, + }; + let out = render(&[same_win, cross_win]); + let bullets: Vec<&str> = out.lines().filter(|l| l.starts_with("- ")).collect(); + assert_eq!(bullets.len(), 2, "{out}"); + + let expected_call_file = if cfg!(windows) { + "C:/repo/pkg/a.go" + } else { + r"C:\repo\pkg\a.go" + }; + let expected_candidate_file = if cfg!(windows) { + "C:/repo/pkg/sub.go" + } else { + r"C:\repo\pkg\sub.go" + }; + + let e0 = parse_edge(bullets[0]).unwrap(); + assert_eq!(e0.call_file, expected_call_file); + assert_eq!(e0.call_line, 22); + assert_eq!(e0.cand_file, expected_call_file); + assert_eq!(e0.def_range, "30-60"); + + let e1 = parse_edge(bullets[1]).unwrap(); + assert_eq!(e1.call_file, expected_call_file); + assert_eq!(e1.call_line, 12); + assert_eq!(e1.cand_file, expected_candidate_file); + assert_eq!(e1.def_range, "7-20"); + } + + #[test] + fn owner_rollup_uses_original_term_index_order_and_counts() { + // Three query terms in original positions #1,#3 (position #2 is a + // zero-hit/empty slot that must NOT renumber). Owner `Set` hits term #1 + // once and term #3 twice. + let path = PathBuf::from("pkg/a.go"); + let owner = anchor("pkg/a.go", "Set", "DB", 10, 40); + let mk_result = |index: usize, term: &str, lines: Vec| TextOrTermResult { + query_term_index: index, + term: term.into(), + total_found: lines.len(), + file_count: 1, + matches: lines + .into_iter() + .map(|line| Match { + path: path.clone(), + line, + text: String::new(), + is_definition: false, + exact: false, + file_lines: 100, + mtime: std::time::SystemTime::UNIX_EPOCH, + def_range: None, + def_name: None, + def_weight: 0, + impl_target: None, + base_target: None, + in_comment: false, + }) + .collect(), + omitted: 0, + }; + let terms = vec![ + mk_result(1, "alpha", vec![12]), + mk_result(3, "beta", vec![14, 15]), // original position 3 (slot 2 empty) + ]; + let hits = vec![ + OwnedTextHit { + path: path.clone(), + line: 12, + owner: owner.clone(), + }, + OwnedTextHit { + path: path.clone(), + line: 14, + owner: owner.clone(), + }, + OwnedTextHit { + path: path.clone(), + line: 15, + owner: owner.clone(), + }, + ]; + let ev = OwnerLinkEvidence { + hits, + edges: Vec::new(), + go_call_analysis_attempted: true, + }; + let mut rendered = String::new(); + render_text_or_owner_rollup(&mut rendered, &path, &ev, &terms); + assert!( + rendered.contains("owners (#N=Nth query term; *K=hits): DB.Set:10-40[#1,#3*2]"), + "{rendered}" + ); + // Determinism: rendering twice yields identical output. + let mut again = String::new(); + render_text_or_owner_rollup(&mut again, &path, &ev, &terms); + assert_eq!(rendered, again); + } + + #[test] + fn indexed_comma_terms_keep_original_positions_with_gaps_and_dups() { + // `alpha,alpha,,missing,beta` -> indices 1,2,4,5 (empty #3 retained as a + // gap; duplicates keep distinct identity). + let got = indexed_comma_terms("alpha,alpha,,missing,beta"); + let expected: Vec<(usize, &str)> = + vec![(1, "alpha"), (2, "alpha"), (4, "missing"), (5, "beta")]; + assert_eq!(got, expected); + // Leading/trailing empties and whitespace also do not renumber. + let got2 = indexed_comma_terms(", ,alpha,beta,"); + assert_eq!(got2, vec![(3, "alpha"), (4, "beta")]); + } + + #[test] + fn owner_rollup_duplicate_zero_hit_and_count_multiplier() { + // Query `alpha,alpha,,missing,beta` over a single owner who matches all + // four surviving terms on distinct lines. Duplicate #1,#2 both attribute; + // zero-hit #4 (missing) must NOT shift beta to a lower index; beta (#5) + // hits twice so it renders `#5*2`. + let path = PathBuf::from("pkg/a.go"); + let owner = anchor("pkg/a.go", "Set", "DB", 10, 40); + let mk_result = |index: usize, term: &str, lines: Vec| TextOrTermResult { + query_term_index: index, + term: term.into(), + total_found: lines.len(), + file_count: 1, + matches: lines + .into_iter() + .map(|line| Match { + path: path.clone(), + line, + text: String::new(), + is_definition: false, + exact: false, + file_lines: 100, + mtime: std::time::SystemTime::UNIX_EPOCH, + def_range: None, + def_name: None, + def_weight: 0, + impl_target: None, + base_target: None, + in_comment: false, + }) + .collect(), + omitted: 0, + }; + // alpha#1 line 12, alpha#2 line 13, missing#4 (no hits, omitted), beta#5 lines 14,15. + let terms = vec![ + mk_result(1, "alpha", vec![12]), + mk_result(2, "alpha", vec![13]), + mk_result(4, "missing", vec![]), + mk_result(5, "beta", vec![14, 15]), + ]; + let hits = vec![12, 13, 14, 15] + .into_iter() + .map(|line| OwnedTextHit { + path: path.clone(), + line, + owner: owner.clone(), + }) + .collect(); + let ev = OwnerLinkEvidence { + hits, + edges: Vec::new(), + go_call_analysis_attempted: true, + }; + let mut rendered = String::new(); + render_text_or_owner_rollup(&mut rendered, &path, &ev, &terms); + // Duplicate #1,#2 both attribute; zero-hit #4 gap keeps beta at #5 with + // count multiplier 2. Order within owner is by ascending index. + assert!(rendered.contains("DB.Set:10-40[#1,#2,#5*2]"), "{rendered}"); + } + fn py_anchor(path: &str, name: &str, s: u32, e: u32) -> OwnerAnchor { + OwnerAnchor { + path: PathBuf::from(path), + name: name.into(), + receiver_var: None, + receiver_type: None, + package_dir: PathBuf::from("."), + start_line: s, + end_line: e, + language: crate::types::Lang::Python, + display_name: name.to_string(), + } + } + + fn go_hit(anchor: OwnerAnchor, line: u32) -> OwnedTextHit { + OwnedTextHit { + path: anchor.path.clone(), + line, + owner: anchor, + } + } + + #[test] + fn non_go_only_result_never_renders_go_zero_edge_or_caveat() { + // Two Python owners, no Go analysis attempted -> no Go zero-edge, no + // Go mechanical caveat; only the non-Go honesty caveat may appear. + let py1 = py_anchor("app.py", "apply", 1, 2); + let py2 = py_anchor("app.py", "set", 3, 4); + let ev = OwnerLinkEvidence { + hits: vec![go_hit(py1, 1), go_hit(py2, 3)], + edges: Vec::new(), + go_call_analysis_attempted: false, + }; + let out = render_owner_link_appendix(&ev, Path::new("")); + assert!(!out.contains("No direct name-level call evidence"), "{out}"); + assert!( + !out.contains("structural owner and mechanically filtered"), + "{out}" + ); + assert!(!out.contains("## Mechanical Go calls"), "{out}"); + assert!( + out.contains("structural lexical ownership candidates"), + "{out}" + ); + } + + #[test] + fn single_go_owner_with_python_owners_suppresses_zero_edge_sentence() { + // 1 Go owner + 2 Python owners: Go analysis ran, but the zero-edge + // sentence must NOT render (it would be a measured-zero claim across + // languages it cannot support). The Go caveat and non-Go caveat may. + let go = anchor("a.go", "Run", "DB", 10, 40); + let py1 = py_anchor("app.py", "apply", 1, 2); + let py2 = py_anchor("app.py", "set", 3, 4); + let ev = OwnerLinkEvidence { + hits: vec![go_hit(go, 12), go_hit(py1, 1), go_hit(py2, 3)], + edges: Vec::new(), + go_call_analysis_attempted: true, + }; + let out = render_owner_link_appendix(&ev, Path::new("")); + assert!(!out.contains("No direct name-level call evidence"), "{out}"); + assert!( + out.contains("structural owner and mechanically filtered"), + "{out}" + ); + assert!( + out.contains("structural lexical ownership candidates"), + "{out}" + ); + } + + #[test] + fn two_go_owners_no_edges_preserves_zero_edge_and_go_caveat() { + // >=2 Go owners, Go-only, no edges -> zero-edge + Go caveat (byte + // identity preserved for the pure-Go case). + let go1 = anchor("a.go", "Run", "DB", 10, 40); + let go2 = anchor("a.go", "Apply", "DB", 50, 80); + let ev = OwnerLinkEvidence { + hits: vec![go_hit(go1, 12), go_hit(go2, 52)], + edges: Vec::new(), + go_call_analysis_attempted: true, + }; + let out = render_owner_link_appendix(&ev, Path::new("")); + assert!(out.contains("No direct name-level call evidence"), "{out}"); + assert!( + out.contains("structural owner and mechanically filtered"), + "{out}" + ); + // Pure Go: no non-Go caveat. + assert!( + !out.contains("structural lexical ownership candidates"), + "{out}" + ); + } + + // ---------- US-067: deterministic owner replay audit harness (test-only) ---------- + // + // Taps the same production seam as `run_text_or_*` (find.rs ~210-252): raw per-term + // `search_content_raw_with_artifact` results are filtered, paginated with a no-omission + // assertion, and fed ONCE into `build_owner_link_evidence`. Output is deterministic + // TSV (no timestamps/absolute machine paths) so an external pinned-repo replay can be + // diffed. No barrier/error classification and no AST/name logic live here. + + /// One raw term-hit row with an optional attached owner anchor. + #[derive(Clone)] + struct AuditRow { + term_index: usize, + term: String, + /// Repo-relative, `/`-normalized path (used for emission/sorting). + rel: String, + /// Original path, used only for owner-anchor lookup before emission. + path: PathBuf, + line: u32, + owner: Option<(String, u32, u32)>, // (qualified_name, start, end) + } + + /// Fail-fast field guard: a value containing `\t`, `\r`, or `\n` would corrupt + /// a TSV column (no escaping scheme is used), so reject it before serialization. + fn assert_tsv_safe(field: &str, what: &str) { + assert!( + !field.contains('\t') && !field.contains('\r') && !field.contains('\n'), + "TSV-unsafe {what} field corruption: {field:?}", + ); + } + + /// Deterministic serialization of the three audit outputs. Factored so the + /// ignored replay harness and the synthetic dedupe test share one emitter. + #[must_use] + fn audit_tsv_files( + rows: &[AuditRow], + per_term: &[(usize, String, usize)], // (term_index, term, total_found) + ) -> (String, String, String) { + // raw.tsv sorted by (term_index, rel, line). + let mut raw = rows.to_vec(); + raw.sort_by(|a, b| { + a.term_index + .cmp(&b.term_index) + .then(a.rel.cmp(&b.rel)) + .then(a.line.cmp(&b.line)) + }); + let mut raw_tsv = String::from( + "term_index\tterm\trelpath\tline\towner_or_empty\tstart_or_empty\tend_or_empty\n", + ); + for r in &raw { + assert_tsv_safe(&r.term, "term"); + assert_tsv_safe(&r.rel, "relpath"); + let (qn, start, end) = r.owner.as_ref().map_or( + (String::new(), String::new(), String::new()), + |(qn, s, e)| { + assert_tsv_safe(qn, "qualified_name"); + (qn.clone(), s.to_string(), e.to_string()) + }, + ); + raw_tsv.push_str(&format!( + "{}\t{}\t{}\t{}\t{}\t{}\t{}\n", + r.term_index, r.term, r.rel, r.line, qn, start, end + )); + } + + // tuples.tsv: DISTINCT sorted (rel, line, qualified_name, start, end). + let mut tuple_set: BTreeSet<(String, u32, String, u32, u32)> = BTreeSet::new(); + for r in rows { + if let Some((qn, s, e)) = &r.owner { + tuple_set.insert((r.rel.clone(), r.line, qn.clone(), *s, *e)); + } + } + let mut tuples_tsv = String::from("relpath\tline\tqualified_name\tstart\tend\n"); + for (rel, line, qn, s, e) in &tuple_set { + tuples_tsv.push_str(&format!("{}\t{}\t{}\t{}\t{}\n", rel, line, qn, s, e)); + } + + // summary.tsv (key/value, no header noise). + let mut summary = String::new(); + for (idx, term, total) in per_term { + assert_tsv_safe(term, "term"); + let raw_count = rows.iter().filter(|r| r.term_index == *idx).count(); + summary.push_str(&format!( + "per-term\t{}\t{}\t{}\t{}\n", + idx, term, total, raw_count + )); + } + let total_raw = rows.len(); + let unique_pl = rows + .iter() + .map(|r| (r.rel.clone(), r.line)) + .collect::>() + .len(); + let distinct_tuples = tuple_set.len(); + let distinct_qn = tuple_set + .iter() + .map(|t| t.2.clone()) + .collect::>() + .len(); + let unattributed = rows.iter().filter(|r| r.owner.is_none()).count(); + summary.push_str(&format!("aggregate\ttotal_raw_term_rows\t{}\n", total_raw)); + summary.push_str(&format!( + "aggregate\tunique_path_line_rows\t{}\n", + unique_pl + )); + summary.push_str(&format!( + "aggregate\tdistinct_attributed_tuples\t{}\n", + distinct_tuples + )); + summary.push_str(&format!( + "aggregate\tdistinct_qualified_names\t{}\n", + distinct_qn + )); + summary.push_str(&format!( + "aggregate\tunattributed_raw_term_rows\t{}\n", + unattributed + )); + + (raw_tsv, tuples_tsv, summary) + } + + /// Repo-relative, `/`-normalized path under the canonical scope. Fails on + /// non-UTF8 or any path outside the scope (never emits absolute machine paths). + #[must_use] + fn audit_relpath(canonical_scope: &Path, path: &Path) -> String { + let rel = path + .strip_prefix(canonical_scope) + .expect("match path is not under the canonical scope"); + let s = rel + .to_str() + .expect("non-UTF8 repo-relative path in US-067 audit"); + s.replace('\\', "/") + } + + /// Deterministic (path, line) -> owner map, asserting any duplicate key has a + /// byte-identical anchor (one owner per hit location). + fn owner_anchor_map(evidence: &OwnerLinkEvidence) -> BTreeMap<(PathBuf, u32), OwnerAnchor> { + let mut map = BTreeMap::new(); + for hit in &evidence.hits { + let key = (hit.path.clone(), hit.line); + if let Some(prev) = map.get(&key) { + assert_eq!( + prev, &hit.owner, + "duplicate (path,line) owner mismatch at {:?}:{}", + hit.path, hit.line + ); + } + map.insert(key, hit.owner.clone()); + } + map + } + + /// Drives the production search + owner pipeline and writes the three + /// deterministic TSV outputs into a FRESH `out_dir`. Panics on any protocol + /// breach (non-[1,2,3] term positions, TSV-unsafe term, per-term omission, + /// non-UTF8/outside-scope path, duplicate (path,line) owner mismatch, or a + /// pre-existing output dir). + fn run_us067_replay(scope: &Path, query: &str, limit: usize, out_dir: &Path) { + let indexed = indexed_comma_terms(query); + let positions: Vec = indexed.iter().map(|(i, _)| *i).collect(); + assert_eq!( + positions, + vec![1, 2, 3], + "SRCWALK_US067_AUDIT_QUERY must be exactly 3 comma terms with original positions [1,2,3] (no empty gaps); got {positions:?}: {query:?}" + ); + for (_, term) in &indexed { + assert_tsv_safe(term, "term"); + } + + let canonical_scope = scope + .canonicalize() + .expect("SRCWALK_US067_AUDIT_SCOPE must exist and be canonicalizable"); + // One shared outline cache across all terms, matching the production command. + let cache = OutlineCache::default(); + + let mut rows: Vec = Vec::new(); + let mut per_term: Vec<(usize, String, usize)> = Vec::new(); + + for (idx, term) in &indexed { + let mut result = search::search_content_raw_with_artifact( + term, + &canonical_scope, + None, + ArtifactMode::Source, + ) + .expect("search_content_raw_with_artifact"); + search::apply_general_filter(&mut result, &canonical_scope, &cache, None) + .expect("apply_general_filter"); + let total_found = result.total_found; + search::pagination::paginate(&mut result, Some(limit), 0); + assert_eq!( + total_found, + result.matches.len(), + "per-term omission: term {} total_found {} != matches.len() {}; raise SRCWALK_US067_AUDIT_LIMIT >= {}", + term, total_found, result.matches.len(), total_found + ); + per_term.push((*idx, term.to_string(), total_found)); + for m in &result.matches { + rows.push(AuditRow { + term_index: *idx, + term: term.to_string(), + rel: audit_relpath(&canonical_scope, &m.path), + path: m.path.clone(), + line: m.line, + owner: None, + }); + } + } + + // Build inputs from the stable `rows` paths in a short scope; drop them + // before mutating rows so no duplicate path vector is kept alive. + let anchors = { + let inputs: Vec = rows + .iter() + .map(|r| OwnerLinkHitInput { + path: &r.path, + line: r.line, + }) + .collect(); + let evidence = build_owner_link_evidence(&inputs); + owner_anchor_map(&evidence) + }; + for r in &mut rows { + r.owner = anchors + .get(&(r.path.clone(), r.line)) + .map(|a| (a.qualified_name(), a.start_line, a.end_line)); + } + + let (raw_tsv, tuples_tsv, summary_tsv) = audit_tsv_files(&rows, &per_term); + assert!( + !out_dir.exists(), + "SRCWALK_US067_AUDIT_OUT must be a fresh (non-existent) directory; refusing to overwrite {}", + out_dir.display() + ); + std::fs::create_dir_all(out_dir).expect("create audit out dir"); + std::fs::write(out_dir.join("raw.tsv"), raw_tsv).expect("write raw.tsv"); + std::fs::write(out_dir.join("tuples.tsv"), tuples_tsv).expect("write tuples.tsv"); + std::fs::write(out_dir.join("summary.tsv"), summary_tsv).expect("write summary.tsv"); + } + + #[test] + fn us067_audit_tsv_deterministic_and_tuples_dedupe() { + let rows = vec![ + AuditRow { + term_index: 2, + term: "return".into(), + rel: "a.ts".into(), + path: PathBuf::from("a.ts"), + line: 10, + owner: Some(("A.f".into(), 5, 12)), + }, + AuditRow { + term_index: 1, + term: "pipe".into(), + rel: "a.ts".into(), + path: PathBuf::from("a.ts"), + line: 10, + owner: Some(("A.f".into(), 5, 12)), // duplicate tuple + }, + AuditRow { + term_index: 1, + term: "pipe".into(), + rel: "b.ts".into(), + path: PathBuf::from("b.ts"), + line: 3, + owner: None, + }, + ]; + let per_term = vec![(1, "pipe".into(), 2), (2, "return".into(), 1)]; + let (raw, tuples, summary) = audit_tsv_files(&rows, &per_term); + + // raw.tsv sorted by (term_index, rel, line). + let rl: Vec<&str> = raw.lines().collect(); + assert_eq!(rl.len(), 4, "header + 3 rows: {raw}"); + assert!( + rl[1].starts_with("1\tpipe\ta.ts\t10\tA.f\t5\t12"), + "{}", + rl[1] + ); + assert!(rl[2].starts_with("1\tpipe\tb.ts\t3\t\t\t"), "{}", rl[2]); + assert!( + rl[3].starts_with("2\treturn\ta.ts\t10\tA.f\t5\t12"), + "{}", + rl[3] + ); + + // tuples.tsv dedupe: one distinct tuple despite two same-key raw rows. + let tl: Vec<&str> = tuples.lines().collect(); + assert_eq!(tl.len(), 2, "header + 1 distinct tuple: {tuples}"); + assert!(tl[1].starts_with("a.ts\t10\tA.f\t5\t12"), "{}", tl[1]); + + assert!(summary.contains("per-term\t1\tpipe\t2\t2\n"), "{summary}"); + assert!(summary.contains("per-term\t2\treturn\t1\t1\n"), "{summary}"); + assert!( + summary.contains("aggregate\ttotal_raw_term_rows\t3\n"), + "{summary}" + ); + assert!( + summary.contains("aggregate\tunique_path_line_rows\t2\n"), + "{summary}" + ); + assert!( + summary.contains("aggregate\tdistinct_attributed_tuples\t1\n"), + "{summary}" + ); + assert!( + summary.contains("aggregate\tdistinct_qualified_names\t1\n"), + "{summary}" + ); + assert!( + summary.contains("aggregate\tunattributed_raw_term_rows\t1\n"), + "{summary}" + ); + } + + #[test] + #[should_panic(expected = "TSV-unsafe term field corruption")] + fn us067_tsv_guard_rejects_delimiter_in_term() { + let rows = vec![AuditRow { + term_index: 1, + term: "pi\tpe".into(), + rel: "a.ts".into(), + path: PathBuf::from("a.ts"), + line: 1, + owner: None, + }]; + let _ = audit_tsv_files(&rows, &[(1, "pipe".into(), 1)]); + } + + #[test] + #[should_panic(expected = "TSV-unsafe qualified_name field corruption")] + fn us067_tsv_guard_rejects_delimiter_in_qualified_name() { + let rows = vec![AuditRow { + term_index: 1, + term: "pipe".into(), + rel: "a.ts".into(), + path: PathBuf::from("a.ts"), + line: 1, + owner: Some(("A\nB".into(), 5, 12)), + }]; + let _ = audit_tsv_files(&rows, &[(1, "pipe".into(), 1)]); + } + + #[test] + #[ignore = "requires pinned external repo; US-067 replay"] + fn us067_owner_replay_audit() { + let scope = + std::env::var("SRCWALK_US067_AUDIT_SCOPE").expect("SRCWALK_US067_AUDIT_SCOPE required"); + let query = + std::env::var("SRCWALK_US067_AUDIT_QUERY").expect("SRCWALK_US067_AUDIT_QUERY required"); + let limit: usize = std::env::var("SRCWALK_US067_AUDIT_LIMIT") + .expect("SRCWALK_US067_AUDIT_LIMIT required") + .parse() + .expect("SRCWALK_US067_AUDIT_LIMIT must be a usize"); + assert!(limit > 0, "SRCWALK_US067_AUDIT_LIMIT must be positive"); + let out = + std::env::var("SRCWALK_US067_AUDIT_OUT").expect("SRCWALK_US067_AUDIT_OUT required"); + run_us067_replay(Path::new(&scope), &query, limit, Path::new(&out)); + } +} diff --git a/src/commands/multi_scope.rs b/src/commands/multi_scope.rs index d722e34..0274b68 100644 --- a/src/commands/multi_scope.rs +++ b/src/commands/multi_scope.rs @@ -385,7 +385,8 @@ fn search_result_content( glob: Option<&str>, filter: Option<&str>, ) -> Result { - let mut result = search::search_content_raw(query, scope, glob)?; + let mut result = + search::search_content_raw_with_artifact(query, scope, glob, crate::ArtifactMode::Source)?; search::apply_general_filter(&mut result, scope, cache, filter)?; Ok(result) } @@ -427,10 +428,14 @@ fn merge_scope_results( let definitions = matches.iter().filter(|m| m.is_definition).count(); let comments = matches.iter().filter(|m| m.in_comment).count(); let total_found = matches.len(); + // Multi-scope finds have no explicit literal-text route, so they abstain + // from the low-signal advisory: no eligible-file denominator is reported. + let eligible_files = 0; Ok(types::SearchResult { query: query.to_string(), scope: common_scope(scopes), total_found, + eligible_files, definition_candidates: definitions, name_occurrence_candidates: matches .iter() @@ -527,3 +532,64 @@ fn scopes_overlap(scopes: &[PathBuf]) -> bool { .any(|(j, b)| i != j && (a.starts_with(b) || b.starts_with(a))) }) } + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + use std::time::SystemTime; + + use crate::types::{Match, SearchResult}; + + use super::merge_scope_results; + + fn hit(path: &str, line: u32) -> Match { + Match { + path: PathBuf::from(path), + line, + text: "hit".to_string(), + is_definition: false, + exact: true, + file_lines: 3, + mtime: SystemTime::UNIX_EPOCH, + def_range: None, + def_name: None, + def_weight: 0, + impl_target: None, + base_target: None, + in_comment: false, + } + } + + #[test] + fn merge_abstains_from_eligible_files_and_dedups_matches() { + // Multi-scope has no explicit literal-text route, so the merged result + // reports no eligible-file denominator (abstains) while still + // deduplicating matches across overlapping scopes. + let scopes = vec![PathBuf::from("a"), PathBuf::from("b")]; + let a = symbol_result(vec![hit("a/f1.rs", 1), hit("shared/f.rs", 1)], "term"); + let b = symbol_result(vec![hit("b/f1.rs", 1), hit("shared/f.rs", 1)], "term"); + + let merged = merge_scope_results("term", &scopes, vec![a, b]).unwrap(); + + assert_eq!(merged.matches.len(), 3, "3 unique matches after dedup"); + assert_eq!(merged.eligible_files, 0, "multi-scope abstains"); + } + + fn symbol_result(matches: Vec, query: &str) -> SearchResult { + let total = matches.len(); + SearchResult { + query: query.to_string(), + scope: PathBuf::from("."), + matches, + total_found: total, + eligible_files: 0, + definition_candidates: 0, + name_occurrence_candidates: 0, + definitions: 0, + usages: total, + comments: 0, + has_more: false, + offset: 0, + } + } +} diff --git a/src/evidence/mod.rs b/src/evidence/mod.rs index 65db209..6676792 100644 --- a/src/evidence/mod.rs +++ b/src/evidence/mod.rs @@ -4,6 +4,8 @@ pub(crate) mod confidence; pub(crate) mod direct_call; pub(crate) mod local_links; pub(crate) mod next_action; +pub(crate) mod owner_links; +pub(crate) mod owners; pub(crate) use anchor::Anchor; pub(crate) use atom::{EvidenceAtom, EvidenceKind, EvidenceRole}; diff --git a/src/evidence/next_action.rs b/src/evidence/next_action.rs index 22c2041..e3a4ef4 100644 --- a/src/evidence/next_action.rs +++ b/src/evidence/next_action.rs @@ -31,6 +31,10 @@ pub(crate) struct NextAction { rank: u16, confidence: NextActionConfidence, source_anchor: Option, + /// Non-action evidence/metadata lines rendered verbatim before the + /// `> Next:` line (e.g. a numeric anchor beside a symbol-addressed body + /// read). These are never actions, so they must not look like one. + preamble: Vec, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -55,9 +59,19 @@ impl NextAction { rank, confidence, source_anchor, + preamble: Vec::new(), } } + /// Attach non-action evidence/metadata lines rendered before `> Next:`. + pub(crate) fn with_preamble( + mut self, + preamble: impl IntoIterator>, + ) -> Self { + self.preamble = preamble.into_iter().map(Into::into).collect(); + self + } + pub(crate) fn from_evidence( command: impl Into, reason: impl Into, @@ -156,6 +170,10 @@ pub(crate) fn render_next_actions(actions: &[NextAction]) -> String { if !out.is_empty() { out.push('\n'); } + for line in &action.preamble { + out.push_str(line); + out.push('\n'); + } let _ = write!(out, "> Next: {}", action.command()); } out diff --git a/src/evidence/owner_links.rs b/src/evidence/owner_links.rs new file mode 100644 index 0000000..516a2da --- /dev/null +++ b/src/evidence/owner_links.rs @@ -0,0 +1,2055 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::{Path, PathBuf}; + +use crate::lang::outline::{get_outline_entries, outline_language}; +use crate::lang::qualified::normalize_receiver_type; +use crate::search::callees::{extract_call_sites, CallSite}; +use crate::types::{Lang, OutlineEntry, OutlineKind}; + +pub(crate) const OWNER_LINK_EDGE_CAP: usize = 10; +pub(crate) const OWNER_LINK_CAVEAT: &str = "> Caveat: structural owner and mechanically filtered direct-call evidence only; not runtime order, dynamic dispatch, or an inferred chain."; +pub(crate) const OWNER_LINK_ZERO_EDGE: &str = "No direct name-level call evidence among hit owners. Dynamic dispatch, DI, callbacks, and protocol wiring are not ruled out."; +/// Honesty caveat for non-Go owner attribution: ranges are structural lexical +/// ownership candidates, not runtime ownership/binding proof, and no call +/// analysis was run for non-Go languages. +pub(crate) const OWNER_NON_GO_CAVEAT: &str = + "> Caveat: owner ranges are structural lexical ownership candidates, not runtime ownership or binding proof; no call analysis was run for non-Go languages."; + +#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)] +pub(crate) struct OwnerAnchor { + pub(crate) path: PathBuf, + /// Unqualified callable name (e.g. `handle`). + pub(crate) name: String, + /// Go edge analysis may use a receiver binding; other languages leave this + /// `None`. Never overload this field to encode non-Go containers. + pub(crate) receiver_var: Option, + /// Go receiver type used only for Go edge identity. Non-Go anchors leave + /// this `None`; their qualified identity lives in `display_name`. + pub(crate) receiver_type: Option, + pub(crate) package_dir: PathBuf, + pub(crate) start_line: u32, + pub(crate) end_line: u32, + /// Source language of the owning file. + pub(crate) language: Lang, + /// Explicit display-qualified name for every owner (e.g. `Service.handle`, + /// `Outer.Inner.handle`, `DB.Set`). This is the single source of truth for + /// rendered identity; it is required for ALL anchors, including Go. Go + /// receiver binding stays in `receiver_var`/`receiver_type` and is never + /// derived from this field. + pub(crate) display_name: String, +} + +impl OwnerAnchor { + pub(crate) fn qualified_name(&self) -> String { + self.display_name.clone() + } + + fn receiver_identity(&self) -> Option<(&Path, &str)> { + Some((self.package_dir.as_path(), self.receiver_type.as_deref()?)) + } +} + +#[derive(Debug, Clone)] +pub(crate) struct OwnedTextHit { + pub(crate) path: PathBuf, + pub(crate) line: u32, + pub(crate) owner: OwnerAnchor, +} + +#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] +pub(crate) enum OwnerCallMechanism { + SingleAssignmentLocalConstructor, + CrossFileSameQualifiedReceiver, + SameFileSameQualifiedReceiver, + SamePackageBareInvocation, +} + +#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)] +pub(crate) struct OwnerCallEvidence { + pub(crate) caller: OwnerAnchor, + pub(crate) call_line: u32, + pub(crate) callee_name: String, + pub(crate) candidate: OwnerAnchor, + pub(crate) mechanism: OwnerCallMechanism, +} + +#[derive(Debug, Default)] +pub(crate) struct OwnerLinkEvidence { + pub(crate) hits: Vec, + pub(crate) edges: Vec, + /// True when Go call/edge analysis was actually attempted for this query + /// (at least one Go file was parsed for edge evidence). This is the only + /// gate for the Go mechanical-call appendix; it is never inferred from + /// `edges.is_empty()`. + pub(crate) go_call_analysis_attempted: bool, +} + +impl OwnerLinkEvidence { + pub(crate) fn owner_for(&self, path: &Path, line: u32) -> Option<&OwnerAnchor> { + self.hits + .iter() + .find(|hit| hit.path == path && hit.line == line) + .map(|hit| &hit.owner) + } + + pub(crate) fn has_owners(&self) -> bool { + !self.hits.is_empty() + } + + /// Whether any attributed owner is a non-Go language. Derived from the + /// anchors' required `language` field so it cannot drift from the evidence. + pub(crate) fn has_non_go_owners(&self) -> bool { + self.hits.iter().any(|hit| hit.owner.language != Lang::Go) + } + + /// Whether any attributed owner is Go. Gating the Go mechanical appendix on + /// this (not merely on `go_call_analysis_attempted`) prevents a non-Go-only + /// or mixed result from rendering a Go zero-edge/caveat it cannot support. + pub(crate) fn has_go_owners(&self) -> bool { + self.hits.iter().any(|hit| hit.owner.language == Lang::Go) + } + + /// Count of distinct attributed Go owners. The Go zero-edge sentence is + /// gated on this (>= 2) so two Python owners can never satisfy it. + pub(crate) fn attributed_go_owner_count(&self) -> usize { + self.hits + .iter() + .filter(|hit| hit.owner.language == Lang::Go) + .map(|hit| hit.owner.clone()) + .collect::>() + .len() + } +} + +pub(crate) struct OwnerLinkHitInput<'a> { + pub(crate) path: &'a Path, + pub(crate) line: u32, +} + +#[derive(Debug)] +struct FileOwner { + anchor: OwnerAnchor, +} + +#[derive(Debug)] +struct FileAnalysis { + owners: Vec, + calls: Vec, + /// Per-owner lexical bindings. `None` when the file could not be analyzed + /// for bindings (e.g. a parse error); a file with no binding evidence must + /// omit all edge evidence rather than fall back to weak guesses. + bindings: Option>>, + /// Function start line -> single unqualified identifier return type, built + /// structurally from the AST (see `go_function_results`). + functions: BTreeMap, +} + +/// A lexical binding of a simple identifier inside one named owner. +/// `start_byte` is where the binding is introduced; `scope_end` is the byte +/// just past the end of the lexical scope in which the binding is visible. +#[derive(Debug, Clone)] +struct Binding { + name: String, + start_byte: usize, + scope_end: usize, + is_param: bool, + is_receiver: bool, + initializer: Option, + write_count: usize, +} + +#[derive(Debug, Clone)] +enum Initializer { + LocalType(String), + Constructor(String), +} + +pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> OwnerLinkEvidence { + // Group inputs by path, tracking which go through the Go (owners + edges) + // pipeline versus a non-Go owner-only pipeline. Non-Go files are routed by + // their detected language; anything unsupported is skipped. + let mut by_path: BTreeMap>> = BTreeMap::new(); + for input in inputs { + let detected = crate::lang::detect_file_type(input.path); + let is_go = detected == crate::types::FileType::Code(Lang::Go); + let is_python = detected == crate::types::FileType::Code(Lang::Python); + let is_rust = detected == crate::types::FileType::Code(Lang::Rust); + let is_js_ts_family = matches!( + detected, + crate::types::FileType::Code(Lang::JavaScript | Lang::TypeScript | Lang::Tsx) + ); + let is_java = detected == crate::types::FileType::Code(Lang::Java); + let is_kotlin = detected == crate::types::FileType::Code(Lang::Kotlin); + let is_csharp = detected == crate::types::FileType::Code(Lang::CSharp); + let is_php = detected == crate::types::FileType::Code(Lang::Php); + if is_go + || is_python + || is_rust + || is_js_ts_family + || is_java + || is_kotlin + || is_csharp + || is_php + { + by_path + .entry(input.path.to_path_buf()) + .or_default() + .push(input); + } + } + + let mut files = BTreeMap::new(); + let mut hits = Vec::new(); + for (path, path_inputs) in &by_path { + let Ok(content) = fs::read_to_string(path) else { + continue; + }; + let detected = crate::lang::detect_file_type(path); + if detected == crate::types::FileType::Code(Lang::Python) { + // Python is owner-only: no call edges are inferred in phase 1. + let Some((regions, errors)) = + crate::evidence::owners::python::python_regions(path, &content) + else { + continue; + }; + for input in path_inputs { + if let Some(owner) = + crate::evidence::owners::python::python_owner_for(®ions, &errors, input.line) + { + hits.push(OwnedTextHit { + path: path.clone(), + line: input.line, + owner: owner.clone(), + }); + } + } + continue; + } + if detected == crate::types::FileType::Code(Lang::Rust) { + // Rust is owner-only: no call edges are inferred in phase 2. + let Some((regions, errors)) = + crate::evidence::owners::rust::rust_regions(path, &content) + else { + continue; + }; + for input in path_inputs { + if let Some(owner) = + crate::evidence::owners::rust::rust_owner_for(®ions, &errors, input.line) + { + hits.push(OwnedTextHit { + path: path.clone(), + line: input.line, + owner: owner.clone(), + }); + } + } + continue; + } + if let crate::types::FileType::Code( + owner_lang @ (Lang::JavaScript | Lang::TypeScript | Lang::Tsx), + ) = detected + { + // JS/TS/TSX is owner-only: no call edges are inferred in phases 3B/3C. + let Some((regions, errors)) = + crate::evidence::owners::js_ts::regions_for(owner_lang, path, &content) + else { + continue; + }; + for input in path_inputs { + if let Some(owner) = + crate::evidence::owners::js_ts::owner_for(®ions, &errors, input.line) + { + hits.push(OwnedTextHit { + path: path.clone(), + line: input.line, + owner: owner.clone(), + }); + } + } + continue; + } + if detected == crate::types::FileType::Code(Lang::Java) { + // Java is owner-only: no call edges are inferred in Wave 2A. + let Some((regions, errors)) = + crate::evidence::owners::java::java_regions(path, &content) + else { + continue; + }; + for input in path_inputs { + if let Some(owner) = + crate::evidence::owners::java::java_owner_for(®ions, &errors, input.line) + { + hits.push(OwnedTextHit { + path: path.clone(), + line: input.line, + owner: owner.clone(), + }); + } + } + continue; + } + if detected == crate::types::FileType::Code(Lang::Kotlin) { + // Kotlin is owner-only: no call edges are inferred in Wave 2A. + let Some((regions, errors)) = + crate::evidence::owners::kotlin::kotlin_regions(path, &content) + else { + continue; + }; + for input in path_inputs { + if let Some(owner) = + crate::evidence::owners::kotlin::kotlin_owner_for(®ions, &errors, input.line) + { + hits.push(OwnedTextHit { + path: path.clone(), + line: input.line, + owner: owner.clone(), + }); + } + } + continue; + } + if detected == crate::types::FileType::Code(Lang::CSharp) { + // C# is owner-only: no call edges are inferred in Wave 2A. + let Some((regions, errors)) = + crate::evidence::owners::csharp::csharp_regions(path, &content) + else { + continue; + }; + for input in path_inputs { + if let Some(owner) = + crate::evidence::owners::csharp::csharp_owner_for(®ions, &errors, input.line) + { + hits.push(OwnedTextHit { + path: path.clone(), + line: input.line, + owner: owner.clone(), + }); + } + } + continue; + } + if detected == crate::types::FileType::Code(Lang::Php) { + // PHP is owner-only: no call edges are inferred in Wave 2A. + let Some((regions, errors)) = crate::evidence::owners::php::php_regions(path, &content) + else { + continue; + }; + for input in path_inputs { + if let Some(owner) = + crate::evidence::owners::php::php_owner_for(®ions, &errors, input.line) + { + hits.push(OwnedTextHit { + path: path.clone(), + line: input.line, + owner: owner.clone(), + }); + } + } + continue; + } + let package_dir = canonical_package_dir(path); + let Some((owners, functions)) = go_file_owners(path, &package_dir, &content) else { + // Malformed/unparsed Go: preserve raw hits, omit owner/edge evidence. + continue; + }; + for input in path_inputs { + if let Some(owner) = narrowest_owner(&owners, input.line) { + hits.push(OwnedTextHit { + path: path.clone(), + line: input.line, + owner: owner.anchor.clone(), + }); + } + } + files.insert( + path.clone(), + FileAnalysis { + calls: extract_call_sites(&content, Lang::Go, None), + bindings: collect_go_bindings(&content), + owners, + functions, + }, + ); + } + + // Edge analysis is Go-only: the candidate set must contain ONLY Go owners. + // `hits` also carries Python/Rust owners, but they must never populate + // `OwnerCallEvidence` — a same-name non-Go owner in the same package/dir + // would otherwise create a fake Go->non-Go bare edge (cross-language + // contamination). Callers and candidates accordingly remain Go-only. + let candidate_owners = hits + .iter() + .map(|hit| hit.owner.clone()) + .filter(|owner| owner.language == Lang::Go) + .collect::>(); + let constructors = collect_constructors(&files); + let mut edges = BTreeSet::new(); + + for (path, file) in &files { + // A file whose bindings could not be analyzed has no binding evidence; + // omit all of its edge evidence rather than guess from an empty scope. + if file.bindings.is_none() { + continue; + } + for call in &file.calls { + // The calling owner is the unique narrowest owner containing the + // call line; abstain on ties (column-less line cannot disambiguate). + let Some(caller) = unique_narrowest_owner( + candidate_owners.iter().filter(|owner| owner.path == *path), + call.line, + ) else { + continue; + }; + let (bare, receiver) = call_shape(call); + for candidate in candidate_owners + .iter() + .filter(|owner| owner.name == call.callee && *owner != caller) + { + let mechanism = + resolve_mechanism(caller, candidate, call, bare, receiver, file, &constructors); + if let Some(mechanism) = mechanism { + edges.insert(OwnerCallEvidence { + caller: caller.clone(), + call_line: call.line, + callee_name: call.callee.clone(), + candidate: candidate.clone(), + mechanism, + }); + } + } + } + } + + let mut edges = edges.into_iter().collect::>(); + edges.sort_by(|a, b| { + a.mechanism + .cmp(&b.mechanism) + .then(a.caller.path.cmp(&b.caller.path)) + .then(a.call_line.cmp(&b.call_line)) + .then(a.caller.name.cmp(&b.caller.name)) + .then(a.candidate.path.cmp(&b.candidate.path)) + .then(a.candidate.start_line.cmp(&b.candidate.start_line)) + }); + + // `files` holds exactly the Go files that parsed successfully and entered + // edge-analysis setup. A malformed/unparseable Go input is skipped before + // insertion, so this is the only honest signal that Go call/edge analysis + // was actually attempted for the query. + let go_call_analysis_attempted = !files.is_empty(); + + OwnerLinkEvidence { + hits, + edges, + go_call_analysis_attempted, + } +} + +fn resolve_mechanism( + caller: &OwnerAnchor, + candidate: &OwnerAnchor, + call: &CallSite, + bare: bool, + receiver: Option<&str>, + file: &FileAnalysis, + constructors: &BTreeMap<(PathBuf, String), String>, +) -> Option { + let call_byte = call.call_byte_range.map(|(start, _)| start); + + // P1: same qualified receiver — only when the receiver variable's lexical + // binding at the call is the method receiver itself (not shadowed by a + // nested func-literal parameter or local declaration). + if let (Some(receiver), Some(caller_var)) = (receiver, caller.receiver_var.as_deref()) { + if receiver == caller_var + && caller.receiver_identity().is_some() + && caller.receiver_identity() == candidate.receiver_identity() + && binding_at(file, caller, receiver, call_byte) + .is_some_and(|binding| binding.is_receiver) + { + return Some(if caller.path == candidate.path { + OwnerCallMechanism::SameFileSameQualifiedReceiver + } else { + OwnerCallMechanism::CrossFileSameQualifiedReceiver + }); + } + } + + if bare && candidate.receiver_type.is_none() && caller.package_dir == candidate.package_dir { + // Reject a bare invocation when the callee name is shadowed by a local + // or parameter binding visible at the call, so we never link to a + // package-level function that is actually a local variable here. + if binding_at(file, caller, &call.callee, call_byte).is_none() { + return Some(OwnerCallMechanism::SamePackageBareInvocation); + } + return None; + } + + let receiver = receiver.filter(|receiver| is_simple_go_identifier(receiver))?; + let binding = binding_at(file, caller, receiver, call_byte)?; + if binding.is_param || binding.write_count != 1 { + return None; + } + let receiver_type = match binding.initializer.as_ref()? { + Initializer::LocalType(receiver_type) => receiver_type.clone(), + Initializer::Constructor(name) => { + // Resolve the constructor against the package-level map only when + // the constructor name is not locally bound at the initializer + // byte (i.e. a local/parameter shadows the package constructor). + if binding_at(file, caller, name, Some(binding.start_byte)).is_some() { + return None; + } + constructors + .get(&(caller.package_dir.clone(), name.clone()))? + .clone() + } + }; + if candidate.receiver_identity() == Some((caller.package_dir.as_path(), receiver_type.as_str())) + { + Some(OwnerCallMechanism::SingleAssignmentLocalConstructor) + } else { + None + } +} + +/// Resolve the innermost lexical binding of `receiver` visible at the call's +/// byte offset. Returns `None` if the binding is out of scope or the receiver +/// is not a simple local identifier. +fn binding_at<'a>( + file: &'a FileAnalysis, + caller: &OwnerAnchor, + receiver: &str, + call_byte: Option, +) -> Option<&'a Binding> { + let call_byte = call_byte?; + file.bindings + .as_ref()? + .get(&caller.start_line)? + .iter() + .filter(|binding| binding.name == receiver) + .filter(|binding| binding.start_byte <= call_byte && call_byte < binding.scope_end) + .max_by_key(|binding| binding.start_byte) +} + +fn call_shape(call: &CallSite) -> (bool, Option<&str>) { + let Some(prefix) = call.call_prefix.as_deref() else { + return (false, None); + }; + if prefix == call.callee { + return (true, None); + } + let receiver = prefix + .strip_suffix(&call.callee) + .and_then(|prefix| prefix.strip_suffix('.')) + .map(str::trim) + .filter(|receiver| !receiver.is_empty()); + (false, receiver) +} + +/// Parse a Go file once. Returns `None` when the tree has parse errors +/// (malformed Go), in which case the caller preserves raw hits but omits all +/// owner/edge evidence for the file. Receivers are derived structurally from +/// each `method_declaration` AST node keyed by start line — never from the +/// rendered outline signature. +fn go_file_owners( + path: &Path, + package_dir: &Path, + content: &str, +) -> Option<(Vec, BTreeMap)> { + let language = outline_language(Lang::Go)?; + let mut parser = tree_sitter::Parser::new(); + if parser.set_language(&language).is_err() { + return None; + } + let tree = parser.parse(content, None)?; + if tree.root_node().has_error() { + return None; + } + let receivers = go_method_receivers(&tree, content.as_bytes()); + let mut owners = Vec::new(); + collect_file_owners( + path, + package_dir, + &get_outline_entries(content, Lang::Go), + &receivers, + &mut owners, + ); + Some((owners, go_function_results(&tree, content.as_bytes()))) +} + +/// Build a map from top-level `method_declaration` start line to +/// `(receiver variable, normalized receiver type)` derived from the AST's +/// `receiver` parameter list. +fn go_method_receivers( + tree: &tree_sitter::Tree, + content: &[u8], +) -> BTreeMap, String)>> { + let mut receivers = BTreeMap::new(); + let mut cursor = tree.root_node().walk(); + for node in tree.root_node().children(&mut cursor) { + if node.kind() != "method_declaration" { + continue; + } + let start_line = node.start_position().row as u32 + 1; + receivers.insert(start_line, go_node_receiver(node, content)); + } + receivers +} + +/// Extract the receiver variable and normalized type from a top-level +/// `method_declaration` node's `receiver` parameter list. +fn go_node_receiver( + node: tree_sitter::Node<'_>, + content: &[u8], +) -> Option<(Option, String)> { + let receiver = node.child_by_field_name("receiver")?; + let mut cursor = receiver.walk(); + let pd = receiver + .named_children(&mut cursor) + .find(|child| child.kind() == "parameter_declaration")?; + let variable = pd + .child_by_field_name("name") + .and_then(|name| name.utf8_text(content).ok()) + .map(str::to_string); + let type_node = pd.child_by_field_name("type")?; + let type_text = type_node.utf8_text(content).ok()?; + Some((variable, normalize_receiver_type(type_text))) +} + +/// Build a map from top-level `function_declaration` start line to its single +/// return type, derived structurally from the AST `result` node. Only a return +/// that is exactly one unqualified identifier (after stripping pointer/array +/// wrappers) is recorded — this is the conservative constructor contract. +/// Construction is structural, never signature-string parsed, so generics, +/// qualified types, multi-return, interfaces, and parse errors all abstain. +fn go_function_results(tree: &tree_sitter::Tree, content: &[u8]) -> BTreeMap { + let mut results = BTreeMap::new(); + let mut cursor = tree.root_node().walk(); + for node in tree.root_node().children(&mut cursor) { + if node.kind() != "function_declaration" { + continue; + } + let start_line = node.start_position().row as u32 + 1; + if let Some(return_type) = go_single_unqualified_result(node, content) { + results.insert(start_line, return_type); + } + } + results +} + +/// Extract a single unqualified identifier return type from a function's +/// `result` node, using only AST node kinds (never raw text heuristics). +/// +/// Accepted shapes (exactly): +/// * a direct `type_identifier` (e.g. `*`-free `Batch`), or +/// * exactly one `pointer_type` whose single named child is a +/// `type_identifier` (e.g. `*Batch`). +/// +/// Rejected (return `None`): multi-return (`(a, b int)`, `(T, error)`), +/// generics, qualified types, interfaces, arrays, `**T`, unnamed results, +/// parenthesized types, and any other AST kind. +fn go_single_unqualified_result(node: tree_sitter::Node<'_>, content: &[u8]) -> Option { + let result = node.child_by_field_name("result")?; + let type_node = if result.kind() == "parameter_list" { + // Count the named/slot results across every parameter declaration so + // `(a, b int)` (two values) and `(int, error)` (two types) abstain. + let mut cursor = result.walk(); + let pds = result + .named_children(&mut cursor) + .filter(|child| child.kind() == "parameter_declaration") + .collect::>(); + if pds.len() != 1 { + return None; + } + let pd = pds[0]; + let mut name_cursor = pd.walk(); + let name_count = pd.children_by_field_name("name", &mut name_cursor).count(); + if name_count != 1 { + return None; + } + pd.child_by_field_name("type")? + } else { + result + }; + go_identifier_through_at_most_one_pointer(type_node, content) +} + +/// Resolve a type node to a single unqualified identifier by walking through +/// at most one `pointer_type` wrapper. `None` for any other shape or for a +/// pointer wrapping a non-identifier (e.g. `**T`, `*pkg.T`, `*[]T`). +fn go_identifier_through_at_most_one_pointer( + type_node: tree_sitter::Node<'_>, + content: &[u8], +) -> Option { + let inner = match type_node.kind() { + "type_identifier" => type_node, + "pointer_type" => { + let child = type_node.named_child(0)?; + // A pointer wrapping anything other than a bare identifier is + // rejected (this also rejects `**T` because the inner node is + // itself a `pointer_type`, not a `type_identifier`). + if child.kind() != "type_identifier" { + return None; + } + child + } + _ => return None, + }; + inner.utf8_text(content).ok().map(str::to_string) +} + +fn collect_file_owners( + path: &Path, + package_dir: &Path, + entries: &[OutlineEntry], + receivers: &BTreeMap, String)>>, + owners: &mut Vec, +) { + for entry in entries { + if entry.kind == OutlineKind::Function { + // `receivers.get(&start_line)` is: + // None -> not a method (a plain function) -> bare owner + // Some(None) -> a method whose receiver failed to parse -> omit + // Some(Some((v,t))) -> a method with a structural receiver -> method owner + match receivers.get(&entry.start_line) { + Some(None) => { + // AST confirmed this is a method but its receiver could not + // be extracted. Omit the owner rather than misclassify it + // as a bare function and risk a false link. + continue; + } + Some(Some((receiver_var, receiver_type))) => { + let receiver_type = + (!receiver_type.is_empty()).then_some(receiver_type.clone()); + let display_name = receiver_type + .as_ref() + .map_or_else(|| entry.name.clone(), |r| format!("{r}.{}", entry.name)); + owners.push(FileOwner { + anchor: OwnerAnchor { + path: path.to_path_buf(), + name: entry.name.clone(), + receiver_var: receiver_var.clone(), + receiver_type, + package_dir: package_dir.to_path_buf(), + start_line: entry.start_line, + end_line: entry.end_line, + language: Lang::Go, + display_name, + }, + }); + } + None => { + owners.push(FileOwner { + anchor: OwnerAnchor { + path: path.to_path_buf(), + name: entry.name.clone(), + receiver_var: None, + receiver_type: None, + package_dir: package_dir.to_path_buf(), + start_line: entry.start_line, + end_line: entry.end_line, + language: Lang::Go, + display_name: entry.name.clone(), + }, + }); + } + } + } + collect_file_owners(path, package_dir, &entry.children, receivers, owners); + } +} + +/// Pick the unique owner whose `[start_line, end_line]` contains `line` and has +/// the smallest span. Returns `None` when nothing contains `line` or when two +/// or more distinct owners tie for the narrowest span: without a column there +/// is no deterministic way to choose, so we abstain rather than risk a false +/// owner. The minimum is computed first, then uniqueness is required, so a +/// later narrower owner is never lost to an earlier tie. +fn narrowest_owner(owners: &[FileOwner], line: u32) -> Option<&FileOwner> { + let containing = owners + .iter() + .filter(|owner| owner.anchor.start_line <= line && line <= owner.anchor.end_line) + .collect::>(); + let min_span = containing + .iter() + .map(|owner| { + owner + .anchor + .end_line + .saturating_sub(owner.anchor.start_line) + }) + .min()?; + let mut narrowest = containing.iter().filter(|owner| { + owner + .anchor + .end_line + .saturating_sub(owner.anchor.start_line) + == min_span + }); + let first = narrowest.next()?; + if narrowest.next().is_some() { + None + } else { + Some(&**first) + } +} + +/// Pick the unique `OwnerAnchor` whose `[start_line, end_line]` contains +/// `line` and has the smallest span, abstaining on any tie (column-less lines +/// cannot be disambiguated). +pub(crate) fn unique_narrowest_owner<'a>( + owners: impl IntoIterator, + line: u32, +) -> Option<&'a OwnerAnchor> { + let containing = owners + .into_iter() + .filter(|owner| owner.start_line <= line && line <= owner.end_line) + .collect::>(); + let min_span = containing + .iter() + .map(|owner| owner.end_line.saturating_sub(owner.start_line)) + .min()?; + let mut narrowest = containing + .iter() + .filter(|owner| owner.end_line.saturating_sub(owner.start_line) == min_span); + let first = narrowest.next()?; + if narrowest.next().is_some() { + None + } else { + Some(first) + } +} + +fn collect_constructors( + files: &BTreeMap, +) -> BTreeMap<(PathBuf, String), String> { + let mut constructors = BTreeMap::new(); + for file in files.values() { + for owner in &file.owners { + if owner.anchor.receiver_type.is_some() { + continue; + } + // Only a function whose AST `result` is a single unqualified + // identifier is a candidate constructor. Structural extraction is + // abstain-only on generics, qualified, multi-return, interface, and + // parse errors. + if let Some(return_type) = file.functions.get(&owner.anchor.start_line) { + constructors.insert( + (owner.anchor.package_dir.clone(), owner.anchor.name.clone()), + return_type.clone(), + ); + } + } + } + constructors +} + +/// Canonicalize a file's parent directory for normalized package identity. +/// Falls back to the raw parent when canonicalization fails (e.g. missing +/// dir). Normalizing makes symlink and Windows path aliases compare equal. +fn canonical_package_dir(path: &Path) -> PathBuf { + let parent = path.parent().unwrap_or_else(|| Path::new(".")); + fs::canonicalize(parent).unwrap_or_else(|_| parent.to_path_buf()) +} + +/// Collect lexical bindings for every named owner in a Go file, keyed by the +/// owner's start line. A binding carries its introduction byte, the byte just +/// past its lexical scope, whether it is a parameter/receiver, and its +/// single-assignment initializer plus write count. Shadowing is resolved by +/// choosing the innermost binding whose `[start_byte, scope_end)` contains the +/// call site. +/// +/// Returns `None` when the file cannot be analyzed structurally (missing +/// language, parser failure, or a parse error). A caller must omit edge +/// evidence for such a file rather than treat an absent scope as "no shadow". +fn collect_go_bindings(content: &str) -> Option>> { + let language = outline_language(Lang::Go)?; + let mut parser = tree_sitter::Parser::new(); + if parser.set_language(&language).is_err() { + return None; + } + let tree = parser.parse(content, None)?; + if tree.root_node().has_error() { + return None; + } + let bytes = content.as_bytes(); + let mut bindings = BTreeMap::new(); + let mut cursor = tree.root_node().walk(); + for node in tree.root_node().children(&mut cursor) { + if matches!(node.kind(), "function_declaration" | "method_declaration") { + let owner_start = node.start_position().row as u32 + 1; + let owner_end = node.end_byte(); + let mut scope = Vec::new(); + collect_owner_bindings(node, bytes, owner_end, &mut scope); + bindings.insert(owner_start, scope); + } + } + Some(bindings) +} + +/// Walk one owner's parameter list and body, collecting lexical bindings. +fn collect_owner_bindings( + node: tree_sitter::Node<'_>, + content: &[u8], + owner_end: usize, + scope: &mut Vec, +) { + // Receiver and named parameters are parameters bound to the owner scope. + if let Some(receiver) = node.child_by_field_name("receiver") { + collect_parameter_bindings(receiver, owner_end, true, content, scope); + } + if let Some(parameters) = node.child_by_field_name("parameters") { + collect_parameter_bindings(parameters, owner_end, false, content, scope); + } + // Named results are in scope across the body and shadow like parameters. + if let Some(results) = node.child_by_field_name("result") { + collect_parameter_bindings(results, owner_end, false, content, scope); + } + if let Some(body) = node.child_by_field_name("body") { + collect_body_bindings(body, owner_end, content, scope); + } + // Every explicit write to a simple identifier records a write on the + // innermost in-scope binding, so reassignment and shadowing disqualify the + // single-assignment rule. + count_binding_writes(node, content, scope); +} + +/// Record the owner's receiver and named parameters as in-scope bindings. +fn collect_parameter_bindings( + parameter_list: tree_sitter::Node<'_>, + owner_end: usize, + is_receiver: bool, + content: &[u8], + scope: &mut Vec, +) { + let mut cursor = parameter_list.walk(); + for child in parameter_list.named_children(&mut cursor) { + if child.kind() != "parameter_declaration" { + continue; + } + let start = child.start_byte(); + if let Some(name_node) = child.child_by_field_name("name") { + for name in list_items(name_node) { + if name.kind() != "identifier" { + continue; + } + if let Ok(name) = name.utf8_text(content) { + scope.push(Binding { + name: name.to_string(), + start_byte: start, + scope_end: owner_end, + is_param: true, + is_receiver, + initializer: None, + write_count: 0, + }); + } + } + } + } +} + +/// Recurse a body, pushing a nested scope boundary for each block and func +/// literal, and registering declarations as bindings scoped to that block end. +fn collect_body_bindings( + node: tree_sitter::Node<'_>, + scope_end: usize, + content: &[u8], + scope: &mut Vec, +) { + let mut cursor = node.walk(); + for child in node.named_children(&mut cursor) { + collect_node_bindings(child, scope_end, content, scope); + } +} + +fn collect_node_bindings( + node: tree_sitter::Node<'_>, + scope_end: usize, + content: &[u8], + scope: &mut Vec, +) { + match node.kind() { + // `block` and the control statements (`if`/`for`/`switch`) each open a + // lexical scope that ends at the node's own boundary, so declarations + // inside them (including init-clause/range locals) expire there instead + // of leaking into the enclosing scope. + "block" + | "if_statement" + | "for_statement" + | "expression_switch_statement" + | "type_switch_statement" => { + let block_end = node.end_byte(); + let mut cursor = node.walk(); + for child in node.named_children(&mut cursor) { + collect_node_bindings(child, block_end, content, scope); + } + } + "func_literal" => { + let literal_end = node.end_byte(); + if let Some(parameters) = node.child_by_field_name("parameters") { + collect_parameter_bindings(parameters, literal_end, false, content, scope); + } + // Named results in a func literal shadow the outer receiver too. + if let Some(results) = node.child_by_field_name("result") { + collect_parameter_bindings(results, literal_end, false, content, scope); + } + if let Some(body) = node.child_by_field_name("body") { + collect_body_bindings(body, literal_end, content, scope); + } + } + "short_var_declaration" | "var_spec" => { + collect_declaration_bindings(node, scope_end, content, scope); + } + "range_clause" => { + collect_unknown_bindings(node, scope_end, content, scope); + } + _ => { + let mut cursor = node.walk(); + for child in node.named_children(&mut cursor) { + collect_node_bindings(child, scope_end, content, scope); + } + } + } +} + +/// Register a declaration (`:=`, `=`, `var`) as a binding with its initializer. +fn collect_declaration_bindings( + node: tree_sitter::Node<'_>, + scope_end: usize, + content: &[u8], + scope: &mut Vec, +) { + let Some(left) = node + .child_by_field_name("left") + .or_else(|| node.child_by_field_name("name")) + else { + return; + }; + let right = node + .child_by_field_name("right") + .or_else(|| node.child_by_field_name("value")); + let left_nodes = list_items(left); + let right_nodes = right.map(list_items).unwrap_or_default(); + for (index, lhs) in left_nodes.into_iter().enumerate() { + if lhs.kind() != "identifier" { + continue; + } + let Ok(name) = lhs.utf8_text(content) else { + continue; + }; + let initializer = right_nodes + .get(index) + .and_then(|rhs| classify_initializer(*rhs, content)); + scope.push(Binding { + name: name.to_string(), + start_byte: node.start_byte(), + scope_end, + is_param: false, + is_receiver: false, + initializer, + write_count: 0, + }); + } +} + +/// Record range variables and `x++` as writes that disqualify single-assignment +/// (no constructor initializer can be proven). +fn collect_unknown_bindings( + node: tree_sitter::Node<'_>, + scope_end: usize, + content: &[u8], + scope: &mut Vec, +) { + let left = node + .child_by_field_name("left") + .or_else(|| node.child_by_field_name("operand")) + .or_else(|| node.named_child(0)); + let Some(left) = left else { return }; + for item in list_items(left) { + if item.kind() != "identifier" { + continue; + } + if let Ok(name) = item.utf8_text(content) { + scope.push(Binding { + name: name.to_string(), + start_byte: node.start_byte(), + scope_end, + is_param: false, + is_receiver: false, + initializer: None, + write_count: 0, + }); + } + } +} + +/// After collecting bindings for an owner, walk every write site and bump the +/// `write_count` of the innermost in-scope binding for that name. A single +/// assignment keeps `write_count == 1`; reassignment, tuple writes, branch +/// writes, and shadowed pre-existing bindings push it above one. +fn count_binding_writes(node: tree_sitter::Node<'_>, content: &[u8], scope: &mut [Binding]) { + if matches!( + node.kind(), + "short_var_declaration" + | "assignment_statement" + | "var_spec" + | "range_clause" + | "inc_statement" + ) { + let left = node + .child_by_field_name("left") + .or_else(|| node.child_by_field_name("name")) + .or_else(|| node.child_by_field_name("operand")) + .or_else(|| node.named_child(0)); + if let Some(left) = left { + let write_byte = node.start_byte(); + for item in list_items(left) { + if item.kind() != "identifier" { + continue; + } + if let Ok(name) = item.utf8_text(content) { + if let Some(binding) = innermost_binding_mut(scope, name, write_byte) { + binding.write_count += 1; + } + } + } + } + } + let mut cursor = node.walk(); + for child in node.named_children(&mut cursor) { + if matches!(child.kind(), "function_declaration" | "method_declaration") { + continue; + } + count_binding_writes(child, content, scope); + } +} + +/// Find the innermost binding of `name` whose `[start_byte, scope_end)` +/// contains `at_byte`. +fn innermost_binding_mut<'a>( + scope: &'a mut [Binding], + name: &str, + at_byte: usize, +) -> Option<&'a mut Binding> { + let candidates: Vec = scope + .iter() + .enumerate() + .filter(|(_, binding)| binding.name == name) + .filter(|(_, binding)| binding.start_byte <= at_byte && at_byte < binding.scope_end) + .map(|(idx, _)| idx) + .collect(); + let idx = candidates + .into_iter() + .max_by_key(|&idx| scope[idx].start_byte)?; + Some(&mut scope[idx]) +} + +fn list_items(node: tree_sitter::Node<'_>) -> Vec> { + if matches!(node.kind(), "expression_list" | "identifier_list") { + let mut cursor = node.walk(); + node.named_children(&mut cursor).collect() + } else { + vec![node] + } +} + +fn classify_initializer(node: tree_sitter::Node<'_>, content: &[u8]) -> Option { + if node.kind() == "call_expression" { + let function = node.child_by_field_name("function")?; + if function.kind() == "identifier" { + return function + .utf8_text(content) + .ok() + .map(|name| Initializer::Constructor(name.to_string())); + } + return None; + } + let composite = if node.kind() == "composite_literal" { + Some(node) + } else if node.kind() == "unary_expression" { + let mut cursor = node.walk(); + let composite = node + .named_children(&mut cursor) + .find(|child| child.kind() == "composite_literal"); + composite + } else { + None + }?; + let type_node = composite.child_by_field_name("type")?; + let type_text = type_node.utf8_text(content).ok()?; + let receiver_type = normalize_receiver_type(type_text); + is_simple_go_identifier(&receiver_type).then_some(Initializer::LocalType(receiver_type)) +} + +fn is_simple_go_identifier(value: &str) -> bool { + let mut chars = value.chars(); + chars + .next() + .is_some_and(|first| first == '_' || first.is_ascii_alphabetic()) + && chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric()) +} + +#[cfg(test)] +mod tests { + use std::fmt::Write as _; + use std::time::{SystemTime, UNIX_EPOCH}; + + use super::*; + + fn temp_dir(name: &str) -> PathBuf { + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let dir = std::env::temp_dir().join(format!("srcwalk-owner-links-{name}-{nonce}")); + fs::create_dir_all(&dir).unwrap(); + dir + } + + fn inputs<'a>(_term: &'a str, path: &'a Path, lines: &[u32]) -> Vec> { + lines + .iter() + .map(|line| OwnerLinkHitInput { path, line: *line }) + .collect() + } + + #[test] + fn attributes_method_hits_and_abstains_outside_functions() { + let dir = temp_dir("owners"); + let path = dir.join("sample.go"); + fs::write( + &path, + "package p\n// Set docs\ntype T struct{}\nfunc (t *T) Set() {\n // Set inside\n}\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("Set", &path, &[2, 4, 5])); + + assert!(evidence.owner_for(&path, 2).is_none()); + assert_eq!( + evidence + .owner_for(&path, 4) + .map(OwnerAnchor::qualified_name), + Some("T.Set".to_string()) + ); + assert_eq!(evidence.hits.len(), 2); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn resolves_same_receiver_bare_and_single_assignment_edges() { + let dir = temp_dir("positive"); + let path = dir.join("sample.go"); + fs::write( + &path, + "package p\ntype DB struct{}\ntype Batch struct{}\nfunc helper() {}\nfunc newBatch() *Batch { return &Batch{} }\nfunc (d *DB) Apply() {}\nfunc (b *Batch) Close() {}\nfunc (d *DB) Set() {\n helper()\n d.Apply()\n b := newBatch()\n b.Close()\n}\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4, 5, 6, 7, 8])); + let mechanisms = evidence + .edges + .iter() + .map(|edge| edge.mechanism) + .collect::>(); + + assert!(mechanisms.contains(&OwnerCallMechanism::SamePackageBareInvocation)); + assert!(mechanisms.contains(&OwnerCallMechanism::SameFileSameQualifiedReceiver)); + assert!(mechanisms.contains(&OwnerCallMechanism::SingleAssignmentLocalConstructor)); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn rejects_composite_literal_reassignment_field_and_cross_package_type_name() { + let root = temp_dir("negative"); + let p1 = root.join("p1"); + let p2 = root.join("p2"); + fs::create_dir_all(&p1).unwrap(); + fs::create_dir_all(&p2).unwrap(); + let path1 = p1.join("one.go"); + let path2 = p2.join("two.go"); + fs::write( + &path1, + "package p1\ntype Metrics struct{}\ntype T struct{ other *T }\nfunc MetricsFn() {}\nfunc newT() *T { return &T{} }\nfunc (t *T) Close() {}\nfunc (t *T) Run() {\n _ = &Metrics{}\n x := newT()\n x = t.other\n x.Close()\n t.other.Close()\n}\n", + ) + .unwrap(); + fs::write( + &path2, + "package p2\ntype T struct{}\nfunc (t *T) Close() {}\n", + ) + .unwrap(); + let mut all = inputs("hit", &path1, &[3, 4, 5, 6, 7]); + all.extend(inputs("hit", &path2, &[2, 3])); + let evidence = build_owner_link_evidence(&all); + + assert_eq!(evidence.edges.len(), 1, "{:#?}", evidence.edges); + assert_eq!(evidence.edges[0].callee_name, "newT"); + assert_eq!( + evidence.edges[0].mechanism, + OwnerCallMechanism::SamePackageBareInvocation + ); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn single_assignment_accepts_closure_capture_and_rejects_ambiguous_writes() { + let dir = temp_dir("single-assignment"); + let path = dir.join("sample.go"); + fs::write( + &path, + "package p\ntype Batch struct{}\ntype Other struct{}\nfunc newBatch() *Batch { return &Batch{} }\nfunc (b *Batch) Close() {}\nfunc Safe() { b := newBatch(); defer func() { b.Close() }() }\nfunc Reassigned() { b := newBatch(); b = &Batch{}; b.Close() }\nfunc WrittenAfter() { b := newBatch(); b.Close(); b = &Batch{} }\nfunc Tuple() { b := newBatch(); b, _ = &Batch{}, 1; b.Close() }\nfunc Branch(ok bool) { var b *Batch; if ok { b = newBatch() }; b.Close() }\nfunc Ranged() { for b := range []*Batch{} { b.Close() } }\nfunc ParamBind(x *Other) { x = newBatch(); x.Close() }\nfunc ClosureShadow() { b := newBatch(); func(b *Other) { b.Close() }() }\n", + ) + .unwrap(); + let evidence = + build_owner_link_evidence(&inputs("hit", &path, &[4, 5, 6, 7, 8, 9, 10, 11, 12, 13])); + let close_edges = evidence + .edges + .iter() + .filter(|edge| edge.callee_name == "Close") + .collect::>(); + + assert_eq!(close_edges.len(), 1, "{:#?}", evidence.edges); + assert_eq!(close_edges[0].caller.name, "Safe"); + assert_eq!( + close_edges[0].mechanism, + OwnerCallMechanism::SingleAssignmentLocalConstructor + ); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn same_receiver_identity_crosses_files_but_not_package_directories() { + let root = temp_dir("package-identity"); + let package = root.join("same"); + let other = root.join("other"); + fs::create_dir_all(&package).unwrap(); + fs::create_dir_all(&other).unwrap(); + let apply = package.join("apply.go"); + let set = package.join("set.go"); + let other_apply = other.join("apply.go"); + fs::write( + &apply, + "package same\ntype DB struct{}\nfunc (d *DB) Apply() {}\n", + ) + .unwrap(); + fs::write(&set, "package same\nfunc (d *DB) Set() { d.Apply() }\n").unwrap(); + fs::write( + &other_apply, + "package other\ntype DB struct{}\nfunc (d *DB) Apply() {}\n", + ) + .unwrap(); + let mut all = inputs("hit", &apply, &[3]); + all.extend(inputs("hit", &set, &[2])); + all.extend(inputs("hit", &other_apply, &[3])); + let evidence = build_owner_link_evidence(&all); + let apply_edges = evidence + .edges + .iter() + .filter(|edge| edge.callee_name == "Apply") + .collect::>(); + + assert_eq!(apply_edges.len(), 1, "{:#?}", evidence.edges); + assert_eq!( + apply_edges[0].mechanism, + OwnerCallMechanism::CrossFileSameQualifiedReceiver + ); + assert_eq!(apply_edges[0].candidate.path, apply); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn duplicate_method_names_attribute_by_receiver_and_range() { + let dir = temp_dir("duplicate-methods"); + let path = dir.join("sample.go"); + fs::write( + &path, + "package p\ntype A struct{}\ntype B struct{}\nfunc (a *A) Set() { /* alpha */ }\nfunc (b *B) Set() { /* beta */ }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4, 5])); + + assert_eq!( + evidence + .owner_for(&path, 4) + .map(OwnerAnchor::qualified_name), + Some("A.Set".to_string()) + ); + assert_eq!( + evidence + .owner_for(&path, 5) + .map(OwnerAnchor::qualified_name), + Some("B.Set".to_string()) + ); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn call_shape_distinguishes_bare_and_selector_calls() { + let bare = CallSite { + line: 1, + callee: "f".into(), + call_text: "f()".into(), + call_prefix: Some("f".into()), + args: vec![], + return_var: None, + is_return: false, + call_byte_range: None, + }; + let selector = CallSite { + call_prefix: Some("x.f".into()), + call_text: "x.f()".into(), + ..bare.clone() + }; + assert_eq!(call_shape(&bare), (true, None)); + assert_eq!(call_shape(&selector), (false, Some("x"))); + } + + #[test] + fn p1_receiver_shadowed_by_closure_param_abstains() { + let dir = temp_dir("p1-shadow"); + let path = dir.join("sample.go"); + // Inner `d` is a func-literal parameter, so `d.Apply()` inside must NOT + // resolve to the outer `DB.Apply` receiver method. + fs::write( + &path, + "package p\ntype DB struct{}\ntype Other struct{}\nfunc (d *DB) Apply() {}\nfunc (d *DB) Run() { func(d *Other) { d.Apply() }() }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4, 5])); + assert_eq!(evidence.edges.len(), 0, "{:#?}", evidence.edges); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn p1_receiver_unshadowed_closure_still_links() { + let dir = temp_dir("p1-unshadowed"); + let path = dir.join("sample.go"); + fs::write( + &path, + "package p\ntype DB struct{}\nfunc (d *DB) Apply() {}\nfunc (d *DB) Run() { func() { d.Apply() }() }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[3, 4])); + assert_eq!(evidence.edges.len(), 1, "{:#?}", evidence.edges); + assert_eq!( + evidence.edges[0].mechanism, + OwnerCallMechanism::SameFileSameQualifiedReceiver + ); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn p2_closure_param_shadow_and_owner_param_binding_abstain() { + let dir = temp_dir("p2-shadow"); + let path = dir.join("sample.go"); + fs::write( + &path, + "package p\ntype Batch struct{}\ntype Other struct{}\nfunc newBatch() *Batch { return &Batch{} }\nfunc (b *Batch) Close() {}\nfunc (o *Other) Close() {}\nfunc OwnerParam(x *Batch) { x = newBatch(); x.Close() }\nfunc ClosureShadow() { b := newBatch(); func(b *Other) { b.Close() }() }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4, 5, 6, 7, 8])); + let close_edges = evidence + .edges + .iter() + .filter(|edge| { + edge.callee_name == "Close" + && edge.candidate.receiver_type.as_deref() == Some("Batch") + }) + .collect::>(); + // OwnerParam rebinds the `*Batch` parameter, so its `x.Close()` must + // abstain (param binding); ClosureShadow's inner `b *Other` shadows and + // its `b.Close()` resolves to Other.Close, not Batch.Close. + assert_eq!(close_edges.len(), 0, "{:#?}", evidence.edges); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn mixed_go_rust_python_owners_keep_edges_go_only() { + // US-067 cross-language guard: Go edge resolution must only ever link + // Go-owned callers to Go-owned candidates. Python/Rust owners sharing + // the same bare callable name are owner-only (no call analysis) and must + // never populate `OwnerCallEvidence`; a mixed query whose hits include a + // non-Go `helper` must still emit only Go->Go edges, and the valid Go + // bare edge must remain unchanged. + let dir = temp_dir("cross-lang"); + let go = dir.join("handler.go"); + let rs = dir.join("other.rs"); + let py = dir.join("other.py"); + fs::write( + &go, + "package p\nfunc helper() {}\nfunc Run() {\n helper()\n}\n", + ) + .unwrap(); + fs::write(&rs, "fn helper() {\n let x = 1;\n}\n").unwrap(); + fs::write(&py, "def helper():\n pass\n").unwrap(); + let mut all = inputs("hit", &go, &[2, 3]); + all.extend(inputs("hit", &rs, &[1])); + all.extend(inputs("hit", &py, &[1])); + let evidence = build_owner_link_evidence(&all); + + // Every attributed edge is Go->Go; no non-Go path appears as a caller + // or candidate anywhere (the cross-language candidate never renders). + for edge in &evidence.edges { + assert_eq!(edge.caller.language, Lang::Go, "{:#?}", evidence.edges); + assert_eq!(edge.candidate.language, Lang::Go, "{:#?}", evidence.edges); + assert_eq!(edge.caller.path, go, "{:#?}", evidence.edges); + assert_eq!(edge.candidate.path, go, "{:#?}", evidence.edges); + } + // The valid Go->Go bare edge is preserved unchanged. + let helper_edges = evidence + .edges + .iter() + .filter(|edge| edge.callee_name == "helper") + .collect::>(); + assert_eq!(helper_edges.len(), 1, "{:#?}", evidence.edges); + assert_eq!(helper_edges[0].caller.name, "Run"); + assert_eq!( + helper_edges[0].mechanism, + OwnerCallMechanism::SamePackageBareInvocation + ); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn malformed_go_abstains_completely() { + let dir = temp_dir("malformed"); + let path = dir.join("broken.go"); + fs::write(&path, "package p\nfunc (d *DB { d.Apply() \n").unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[2])); + assert!(evidence.hits.is_empty(), "{:#?}", evidence.hits); + assert!(evidence.edges.is_empty(), "{:#?}", evidence.edges); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn hit_inside_nested_closure_attributes_to_named_owner() { + let dir = temp_dir("nested-closure"); + let path = dir.join("sample.go"); + // A hit inside a func literal body is attributed to the enclosing named + // owner (the closure is not a top-level outline owner). + fs::write( + &path, + "package p\ntype DB struct{}\nfunc (d *DB) Run() {\n f := func() { /* alpha */ }\n f()\n}\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4])); + assert_eq!(evidence.hits.len(), 1, "{:#?}", evidence.hits); + assert_eq!( + evidence.hits[0].owner.name.as_str(), + "Run", + "{:#?}", + evidence.hits + ); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn self_recursive_call_pair_is_omitted() { + let dir = temp_dir("self-recursion"); + let path = dir.join("sample.go"); + fs::write( + &path, + "package p\ntype DB struct{}\nfunc (d *DB) Run() { d.Run() }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[3])); + assert_eq!(evidence.edges.len(), 0, "{:#?}", evidence.edges); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn constructor_ast_helper_accepts_only_identifier_or_single_pointer_to_identifier() { + // Direct unit assertions on the structural constructor helper, parsing + // each candidate return type and checking the node-kind proof. + fn single_result(src: &str) -> Option { + let lang = outline_language(Lang::Go).unwrap(); + let mut parser = tree_sitter::Parser::new(); + parser.set_language(&lang).unwrap(); + let tree = parser.parse(src, None).unwrap(); + let mut cursor = tree.root_node().walk(); + for node in tree.root_node().children(&mut cursor) { + if node.kind() == "function_declaration" { + return go_single_unqualified_result(node, src.as_bytes()); + } + } + None + } + // Accepted: exact identifier and single pointer to identifier. + assert_eq!( + single_result("package p\nfunc newT() Batch { return Batch{} }\n").as_deref(), + Some("Batch") + ); + assert_eq!( + single_result("package p\nfunc newT() *Batch { return &Batch{} }\n").as_deref(), + Some("Batch") + ); + // Rejected: generics, qualified, multi-return, interface, **T, arrays. + assert_eq!( + single_result("package p\nfunc f[T any]() *Box[T] { return nil }\n"), + None + ); + assert_eq!( + single_result("package p\nfunc f() *pkg.Batch { return nil }\n"), + None + ); + assert_eq!( + single_result("package p\nfunc f() (Batch, error) { return Batch{}, nil }\n"), + None + ); + assert_eq!( + single_result("package p\nfunc f() interface{} { return nil }\n"), + None + ); + assert_eq!( + single_result("package p\nfunc f() **Batch { return nil }\n"), + None + ); + assert_eq!( + single_result("package p\nfunc f() *[3]Batch { return nil }\n"), + None + ); + assert_eq!( + single_result("package p\nfunc f() []Batch { return nil }\n"), + None + ); + assert_eq!(single_result("package p\nfunc f() {}\n"), None); + assert_eq!( + single_result("package p\nfunc f() (b Batch, e error) { return Batch{}, nil }\n"), + None + ); + } + + #[test] + fn structural_constructor_abstains_on_generic_qualified_multi_interface() { + let dir = temp_dir("ctor-abstain"); + let path = dir.join("sample.go"); + fs::write( + &path, + "package p\ntype Batch struct{}\ntype BatchT[T any] struct{}\nfunc (b *Batch) Close() {}\nfunc newBatch() *Batch { return &Batch{} }\nfunc gen[T any]() *BatchT[T] { return &BatchT[T]{} }\nfunc qual() *pkg.Batch { return nil }\nfunc multi() (*Batch, error) { return nil, nil }\nfunc iface() interface{} { return nil }\nfunc hmm() *[3]Batch { return nil }\n", + ) + .unwrap(); + // Only the exact single unqualified ident return `*Batch` qualifies as + // a constructor. Generics, qualified, multi-return, interface, and + // array-of-pointer all abstain. + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4, 5, 6, 7, 8, 9, 10])); + let close_edges = evidence + .edges + .iter() + .filter(|edge| edge.callee_name == "Close") + .collect::>(); + assert_eq!(close_edges.len(), 0, "{:#?}", evidence.edges); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn bare_callee_shadowed_by_local_abstains_but_unshadowed_links() { + let dir = temp_dir("bare-shadow"); + let path = dir.join("sample.go"); + fs::write( + &path, + "package p\nfunc helper() {}\nfunc Shadowed() { helper := func() {}; helper() }\nfunc Unshadowed() { helper() }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[2, 3, 4])); + let helper_edges = evidence + .edges + .iter() + .filter(|edge| edge.callee_name == "helper") + .collect::>(); + // Only the unshadowed call links; the local `helper` shadows the + // package-level function in Shadowed. + assert_eq!(helper_edges.len(), 1, "{:#?}", evidence.edges); + assert_eq!(helper_edges[0].caller.name, "Unshadowed"); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn constructor_callee_shadowed_by_local_abstains() { + let dir = temp_dir("ctor-shadow"); + let path = dir.join("sample.go"); + fs::write( + &path, + "package p\ntype Batch struct{}\nfunc newBatch() *Batch { return &Batch{} }\nfunc (b *Batch) Close() {}\nfunc Shadowed(x *Batch) { newBatch := x; b := newBatch(); b.Close() }\nfunc Unshadowed() { b := newBatch(); b.Close() }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[3, 4, 5, 6])); + let close_edges = evidence + .edges + .iter() + .filter(|edge| edge.callee_name == "Close") + .collect::>(); + // Shadowed rebinds `newBatch` to a local, so its `b := newBatch()` must + // not resolve to the package constructor; Unshadowed still links. + assert_eq!(close_edges.len(), 1, "{:#?}", evidence.edges); + assert_eq!(close_edges[0].caller.name, "Unshadowed"); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn p1_local_shadow_before_call_abstains_but_shadow_after_still_links() { + let dir = temp_dir("p1-local-shadow"); + let path = dir.join("sample.go"); + // A nested block shadows the receiver `d`; the inner `d.Apply()` must + // abstain. A call before the nested block still links to DB.Apply. + fs::write( + &path, + "package p\ntype DB struct{}\ntype Other struct{}\nfunc (d *DB) Apply() {}\nfunc (d *DB) ShadowedScope() { { d := &Other{}; d.Apply() } }\nfunc (d *DB) ShadowAfter() { d.Apply(); { d := &Other{}; _ = d } }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4, 5, 6])); + let apply_edges = evidence + .edges + .iter() + .filter(|edge| { + edge.callee_name == "Apply" && edge.candidate.receiver_type.as_deref() == Some("DB") + }) + .collect::>(); + // ShadowAfter calls before the inner block shadows `d`, so it still + // links to DB.Apply; ShadowedScope's nested block shadows the receiver. + assert_eq!(apply_edges.len(), 1, "{:#?}", evidence.edges); + assert_eq!(apply_edges[0].caller.name, "ShadowAfter"); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn p1_multi_level_nested_closure_shadow_abstains() { + let dir = temp_dir("p1-multi-shadow"); + let path = dir.join("sample.go"); + // Two levels of nested closures; the innermost declares `d *Other`, + // shadowing the receiver `d`, so `d.Apply()` must abstain from DB.Apply. + fs::write( + &path, + "package p\ntype DB struct{}\ntype Other struct{}\nfunc (d *DB) Apply() {}\nfunc (o *Other) Apply() {}\nfunc (d *DB) Run() { func() { func(d *Other) { d.Apply() }() }() }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4, 5, 6])); + let apply_edges = evidence + .edges + .iter() + .filter(|edge| { + edge.callee_name == "Apply" && edge.candidate.receiver_type.as_deref() == Some("DB") + }) + .collect::>(); + assert_eq!(apply_edges.len(), 0, "{:#?}", evidence.edges); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn p1_named_result_in_func_literal_shadows_receiver_abstains() { + let dir = temp_dir("p1-named-result"); + let path = dir.join("sample.go"); + // The func literal declares a named result `d *DB` that shadows the + // receiver `d` across the literal body; `d.Apply()` must abstain. + fs::write( + &path, + "package p\ntype DB struct{}\ntype Other struct{}\nfunc (d *DB) Apply() {}\nfunc (d *DB) Run() { func() (d *DB) { d.Apply(); return d }() }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4, 5])); + let apply_edges = evidence + .edges + .iter() + .filter(|edge| { + edge.callee_name == "Apply" && edge.candidate.receiver_type.as_deref() == Some("DB") + }) + .collect::>(); + assert_eq!(apply_edges.len(), 0, "{:#?}", evidence.edges); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn control_stmt_init_clause_ctor_local_does_not_leak_past_statement() { + let dir = temp_dir("control-scope"); + let path = dir.join("sample.go"); + // A ctor local declared in the init clause of `if`/`for`/`switch` is + // scoped to that statement; a `.Close()` after the statement must NOT + // resolve to it via the leaked binding. + fs::write( + &path, + "package p\ntype Batch struct{}\ntype Other struct{}\nfunc newBatch() *Batch { return &Batch{} }\nfunc (b *Batch) Close() {}\nfunc (o *Other) Close() {}\nfunc Run(b *Other) { if b := newBatch(); true { _ = b }; b.Close() }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4, 5, 6, 7])); + let batch_close = evidence + .edges + .iter() + .filter(|edge| { + edge.callee_name == "Close" + && edge.candidate.receiver_type.as_deref() == Some("Batch") + }) + .collect::>(); + // The `b := newBatch()` inside the if-init is scoped to the `if`; the + // trailing `b.Close()` uses the outer `*Other` param `b`, so it links + // to Other.Close (or abstains), never Batch.Close. + assert_eq!(batch_close.len(), 0, "{:#?}", evidence.edges); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn control_stmt_init_clause_ctor_local_still_links_inside_body() { + let dir = temp_dir("control-scope-in"); + let path = dir.join("sample.go"); + // Inside the statement body the ctor local is in scope and links. + fs::write( + &path, + "package p\ntype Batch struct{}\ntype Other struct{}\nfunc newBatch() *Batch { return &Batch{} }\nfunc (b *Batch) Close() {}\nfunc Run() { if b := newBatch(); true { b.Close() } }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4, 5, 6])); + let batch_close = evidence + .edges + .iter() + .filter(|edge| { + edge.callee_name == "Close" + && edge.candidate.receiver_type.as_deref() == Some("Batch") + }) + .collect::>(); + assert_eq!(batch_close.len(), 1, "{:#?}", evidence.edges); + assert_eq!(batch_close[0].caller.name, "Run"); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn range_and_for_clause_ctor_locals_do_not_leak_past_statement() { + let dir = temp_dir("range-scope"); + let path = dir.join("sample.go"); + fs::write( + &path, + "package p\ntype Batch struct{}\ntype Other struct{}\nfunc newBatch() *Batch { return &Batch{} }\nfunc (b *Batch) Close() {}\nfunc (o *Other) Close() {}\nfunc R(b *Other) { for b := newBatch(); ; { break }; b.Close() }\nfunc S(b *Other) { for ; ; { _ = b }; b.Close() }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4, 5, 6, 7, 8])); + let batch_close = evidence + .edges + .iter() + .filter(|edge| { + edge.callee_name == "Close" + && edge.candidate.receiver_type.as_deref() == Some("Batch") + }) + .collect::>(); + assert_eq!(batch_close.len(), 0, "{:#?}", evidence.edges); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn range_clause_ctor_local_does_not_leak_past_loop() { + let dir = temp_dir("range-leak"); + let path = dir.join("sample.go"); + // `range` binds a ctor local with per-iteration scope; after the loop + // the outer `*Other` param is used, so no Batch.Close link. + fs::write( + &path, + "package p\ntype Batch struct{}\ntype Other struct{}\nfunc newBatch() *Batch { return &Batch{} }\nfunc (b *Batch) Close() {}\nfunc (o *Other) Close() {}\nfunc R(xs *Other, ys []Other) { for b := range ys { _ = b }; xs.Close() }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4, 5, 6, 7])); + let batch_close = evidence + .edges + .iter() + .filter(|edge| { + edge.callee_name == "Close" + && edge.candidate.receiver_type.as_deref() == Some("Batch") + }) + .collect::>(); + assert_eq!(batch_close.len(), 0, "{:#?}", evidence.edges); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn direct_composite_literal_positive_and_same_line_write_after_call_reject() { + let dir = temp_dir("direct-composite"); + let path = dir.join("sample.go"); + fs::write( + &path, + "package p\ntype Batch struct{}\ntype Other struct{}\nfunc (b *Batch) Close() {}\nfunc Direct() { x := &Batch{}; x.Close() }\nfunc WriteAfter() { b := &Batch{}; b.Close(); b = &Other{} }\n", + ) + .unwrap(); + let evidence = build_owner_link_evidence(&inputs("hit", &path, &[4, 5, 6])); + let close_edges = evidence + .edges + .iter() + .filter(|edge| edge.callee_name == "Close") + .collect::>(); + // Direct composite literal is a positive single-assignment link; + // the same-line write-after-call (`b.Close(); b = &Other{}`) rejects. + assert_eq!(close_edges.len(), 1, "{:#?}", evidence.edges); + assert_eq!(close_edges[0].caller.name, "Direct"); + assert_eq!( + close_edges[0].mechanism, + OwnerCallMechanism::SingleAssignmentLocalConstructor + ); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn equal_narrowest_owner_span_abstains() { + let dir = temp_dir("tie-abstain"); + let path = dir.join("sample.go"); + // Two methods on the same single line; a hit on that line has no column, + // so attribution must abstain rather than pick one arbitrarily. + fs::write(&path, "package p\ntype A struct{}\ntype B struct{}\nfunc (a *A) Set() {}; func (b *B) Set() {}\n").unwrap(); + let owners = vec![ + FileOwner { + anchor: OwnerAnchor { + path: path.clone(), + name: "Set".into(), + receiver_var: Some("a".into()), + receiver_type: Some("A".into()), + package_dir: dir.clone(), + start_line: 4, + end_line: 4, + language: Lang::Go, + display_name: "A.Set".into(), + }, + }, + FileOwner { + anchor: OwnerAnchor { + path: path.clone(), + name: "Set".into(), + receiver_var: Some("b".into()), + receiver_type: Some("B".into()), + package_dir: dir.clone(), + start_line: 4, + end_line: 4, + language: Lang::Go, + display_name: "B.Set".into(), + }, + }, + ]; + assert!(narrowest_owner(&owners, 4).is_none()); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn duplicate_input_lines_produce_no_duplicate_edges() { + let dir = temp_dir("dup-input"); + let path = dir.join("sample.go"); + fs::write( + &path, + "package p\ntype DB struct{}\nfunc (d *DB) Apply() {}\nfunc (d *DB) Set() { d.Apply() }\n", + ) + .unwrap(); + let mut all = inputs("hit", &path, &[3, 4]); + all.extend(inputs("hit", &path, &[3, 4])); // duplicate inputs + let evidence = build_owner_link_evidence(&all); + assert_eq!(evidence.edges.len(), 1, "{:#?}", evidence.edges); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn deterministic_dedup_and_cap_10_edges_and_renderer_caps() { + let dir = temp_dir("cap10"); + let path = dir.join("sample.go"); + // 12 candidate methods on the same receiver; Run calls each once so we + // exceed the 10-edge cap with deterministic ordering. + let mut src = String::from("package p\ntype DB struct{}"); + let mut call_lines = vec![]; + for i in 0..12 { + let _ = write!(src, "\nfunc (d *DB) M{i}() {{ /* body */ }}"); + call_lines.push(i + 3); + } + // Run calls each candidate once; each M method body is hit so every M + // is a candidate owner in the shown set. + let _ = writeln!(src, "\nfunc (d *DB) Run() {{"); + for i in 0..12 { + let _ = writeln!(src, " d.M{i}()"); + } + src.push('}'); + fs::write(&path, src).unwrap(); + let mut lines = call_lines.clone(); + for i in 0..12 { + lines.push(15 + i); + } + let evidence = build_owner_link_evidence(&inputs("hit", &path, &lines)); + assert!(evidence.edges.len() > 10, "{:#?}", evidence.edges.len()); + // The builder keeps all 12 edges (deterministic); the renderer caps at + // 10 via `.take(OWNER_LINK_EDGE_CAP)`. + assert_eq!(evidence.edges.len(), 12, "{:#?}", evidence.edges); + // Deterministic ordering by mechanism then path/line. + let mut sorted = evidence.edges.clone(); + sorted.sort_by(|a, b| { + a.mechanism + .cmp(&b.mechanism) + .then(a.caller.path.cmp(&b.caller.path)) + .then(a.call_line.cmp(&b.call_line)) + .then(a.caller.name.cmp(&b.caller.name)) + .then(a.candidate.path.cmp(&b.candidate.path)) + .then(a.candidate.start_line.cmp(&b.candidate.start_line)) + }); + assert_eq!(evidence.edges, sorted, "edges must already be sorted"); + // The renderer applies `.take(OWNER_LINK_EDGE_CAP)`; assert exactly 10 + // would be emitted by replicating the renderer's capping seam. + let rendered_count = evidence.edges.iter().take(OWNER_LINK_EDGE_CAP).count(); + assert_eq!(rendered_count, OWNER_LINK_EDGE_CAP); + assert_eq!(rendered_count, 10); + fs::remove_dir_all(dir).unwrap(); + } + + // US-067 permutation determinism: the owner aggregation seam must be + // invariant to hit input order (CLI traversal order is not injectable). + #[test] + fn mixed_owner_evidence_is_permutation_invariant() { + let dir = temp_dir("permutation"); + let go = dir.join("feature.go"); + let py = dir.join("app.py"); + let rs = dir.join("lib.rs"); + fs::write( + &go, + "package feature\nfunc First() { /* alpha */ }\nfunc Second() { /* beta */ First() }\n", + ) + .unwrap(); + fs::write(&py, "def load():\n return \"alpha\"\n").unwrap(); + fs::write(&rs, "fn load() {\n let _ = \"alpha\";\n}\n").unwrap(); + + // File-group permutation: Go internal order [2,3] is preserved in both + // inputs; only the file-group order is reversed (Go/Rust/Python → + // Python/Rust/Go). + let forward = vec![ + OwnerLinkHitInput { path: &go, line: 2 }, + OwnerLinkHitInput { path: &go, line: 3 }, + OwnerLinkHitInput { path: &rs, line: 2 }, + OwnerLinkHitInput { path: &py, line: 2 }, + ]; + let reversed = vec![ + OwnerLinkHitInput { path: &py, line: 2 }, + OwnerLinkHitInput { path: &rs, line: 2 }, + OwnerLinkHitInput { path: &go, line: 2 }, + OwnerLinkHitInput { path: &go, line: 3 }, + ]; + + let fwd = build_owner_link_evidence(&forward); + let rev = build_owner_link_evidence(&reversed); + + // Direct projection (NO sort): if the pipeline output order were + // nondeterministic this would catch it, not mask it. + let project = |ev: &OwnerLinkEvidence| -> Vec<(PathBuf, u32, String)> { + ev.hits + .iter() + .map(|h| (h.path.clone(), h.line, h.owner.display_name.clone())) + .collect() + }; + assert_eq!( + project(&fwd), + project(&rev), + "hits differ under file-group permutation" + ); + assert_eq!(fwd.edges, rev.edges, "edges differ under permutation"); + assert_eq!( + fwd.go_call_analysis_attempted, rev.go_call_analysis_attempted, + "go-analysis flag differs under permutation" + ); + + // BTreeMap ordering yields app.py, feature.go, lib.rs regardless of + // input order. + let owners = project(&fwd); + assert_eq!( + owners, + vec![ + (py.clone(), 2, "load".to_string()), + (go.clone(), 2, "First".to_string()), + (go.clone(), 3, "Second".to_string()), + (rs.clone(), 2, "load".to_string()), + ] + ); + assert_eq!(fwd.edges.len(), 1, "{:#?}", fwd.edges); + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/src/evidence/owners/csharp.rs b/src/evidence/owners/csharp.rs new file mode 100644 index 0000000..83921b0 --- /dev/null +++ b/src/evidence/owners/csharp.rs @@ -0,0 +1,1491 @@ +//! C# owner-region extraction (US-068 Wave 2A). +//! +//! Supported named owners: body-bearing methods under their lexical type and +//! namespace containers (`Service.Load`, `Acme.Api.Service.Load`); nested +//! class/struct/interface/record/enum containers appended with `.`; property +//! accessors (`Container.Property.get`/`.set`/`.init`), event accessors +//! (`Container.Event.add`/`.remove`), and indexer accessors +//! (`Container.this.get`/`.set`); expression-bodied property getters +//! (`Container.Property.get`); expression-bodied methods, constructors, +//! destructors, operators, local functions, and explicit accessors; local +//! functions appended to their enclosing callable (`Service.Load.parse`); +//! constructors and destructors using the declared type name; operators +//! (`Service.operator +`); and conversion operators including `implicit`/ +//! `explicit` and the structurally spelled target type. +//! +//! Abstentions/barriers: every `lambda_expression` and +//! `anonymous_method_expression` is an anonymous barrier; body-less callables +//! (abstract, extern, interface-only, partial-signature) are not owners; an +//! accessor abstains when the parent identity or accessor kind is not complete; +//! a local function abstains when its enclosing callable/type identity is +//! anonymous or unreadable; a local function among top-level statements abstains +//! (no supported enclosing callable identity); explicit interface members are +//! preserved completely or abstain. Partial type parts are parsed independently +//! and never merged. + +use std::path::Path; + +use tree_sitter::Node; + +use crate::evidence::owner_links::OwnerAnchor; +use crate::evidence::owners::{ + attribute_line, collect_error_ranges, degrade_named_on_error, ErrorRange, OwnerRegion, +}; +use crate::lang::outline::outline_language; +use crate::types::Lang; + +/// Version-pinned C# callable manifest (anti-drift contract) for the pinned +/// tree-sitter-c-sharp grammar. +#[cfg(test)] +const CSHARP_EXECUTABLE_CALLABLES: &[&str] = &[ + "method_declaration", + "local_function_statement", + "constructor_declaration", + "destructor_declaration", + "operator_declaration", + "conversion_operator_declaration", + "property_declaration", + "event_declaration", + "indexer_declaration", + "accessor_declaration", + "lambda_expression", + "anonymous_method_expression", +]; +#[cfg(test)] +const CSHARP_CONTAINER_KINDS: &[&str] = &[ + "namespace_declaration", + "file_scoped_namespace_declaration", + "class_declaration", + "struct_declaration", + "interface_declaration", + "record_declaration", + "enum_declaration", + "declaration_list", +]; +#[cfg(test)] +const CSHARP_BODILESS_OR_BARRIER_KINDS: &[&str] = &[ + "arrow_expression_clause", + "block", + "explicit_interface_specifier", + "global_statement", +]; + +/// FNV-1a-64 fingerprint of the bundled `tree-sitter-c-sharp` `NODE_TYPES` JSON +/// (tree-sitter-c-sharp 0.23.5). Pinned so any grammar metadata change fails the +/// manifest gate and forces a re-audit. +#[cfg(test)] +const CSHARP_NODE_TYPES_FINGERPRINT: u64 = 0xeb71_2764_c7f6_699f; + +/// Stable FNV-1a 64-bit hash, dependency-free and reproducible across builds. +#[cfg(test)] +fn fnv1a(bytes: &[u8]) -> u64 { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for &b in bytes { + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x100_0000_01b3); + } + hash +} + +/// Parse a C# file and produce its owner regions and local error ranges. +/// Returns `None` when the file cannot be read, has no tree, or its root node +/// itself is an `ERROR` (preserve raw hits, emit no owner evidence). +pub(crate) fn csharp_regions( + path: &Path, + content: &str, +) -> Option<(Vec, Vec)> { + let language = outline_language(Lang::CSharp)?; + let mut parser = tree_sitter::Parser::new(); + if parser.set_language(&language).is_err() { + return None; + } + let tree = parser.parse(content, None)?; + if tree.root_node().kind() == "ERROR" { + return None; + } + let bytes = content.as_bytes(); + let errors = collect_error_ranges(&tree, bytes); + let mut regions = Vec::new(); + let mut containers: Vec = Vec::new(); + walk( + tree.root_node(), + bytes, + path, + false, + false, + &mut containers, + &errors, + &mut regions, + ); + Some((regions, errors)) +} + +/// Emit a full-range `AnonymousBarrier` for a node and descend `in_anonymous`. +fn barrier_and_descend( + node: Node<'_>, + bytes: &[u8], + path: &Path, + in_callable: bool, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + walk_children( + node, + bytes, + path, + true, + in_callable, + containers, + errors, + regions, + ); +} + +/// Emit a `Named` owner covering `node`'s body-bearing range after degrading on +/// local errors, then descend. +fn named_and_descend( + node: Node<'_>, + bytes: &[u8], + path: &Path, + anchor_builder: impl FnOnce() -> OwnerAnchor, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + let anchor = anchor_builder(); + let start_line = anchor.start_line; + let end_line = anchor.end_line; + let callable_segment = anchor.name.clone(); + let region = OwnerRegion::Named(anchor); + let region = degrade_named_on_error(region, errors, node.start_byte(), node.end_byte()); + regions.push(region); + let _ = (start_line, end_line); + // Push the callable segment so nested local functions append to the + // complete lexical callable path (`Service.Load.parse`). + containers.push(callable_segment); + walk_children(node, bytes, path, false, true, containers, errors, regions); + containers.pop(); +} + +/// The structurally spelled explicit-interface prefix, if any (e.g. `IFoo.` +/// for `IFoo.GetBar`). Returns the trimmed prefix without the trailing dot. +fn explicit_interface_prefix(node: Node<'_>, bytes: &[u8]) -> Option { + node.named_children(&mut node.walk()) + .find(|c| c.kind() == "explicit_interface_specifier") + .and_then(|c| c.utf8_text(bytes).ok()) + .map(|s| s.trim().trim_end_matches('.').to_string()) + .filter(|s| !s.is_empty()) +} + +/// The `implicit`/`explicit` keyword of a conversion operator, if present. The +/// grammar surfaces it as an unnamed child node kind, not a modifier. Returns +/// `None` when absent so callers never synthesize a default keyword. +fn conversion_keyword(node: Node<'_>) -> Option { + node.children(&mut node.walk()) + .find(|c| matches!(c.kind(), "implicit" | "explicit")) + .map(|c| c.kind().to_string()) +} + +/// Extract a required identity component, trimming whitespace and rejecting empty +/// results. Empty required components (e.g. `identifier err ''`) must not yield +/// dangling segments like `Service.` / `.get` / `operator `; callers fall back to +/// their existing fail-closed barrier/abstain path. +fn required_identity(node: Node<'_>, field: &str, bytes: &[u8]) -> Option { + node.child_by_field_name(field) + .and_then(|n| n.utf8_text(bytes).ok()) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) +} + +/// Walk a C# tree, emitting `Named` regions for body-bearing callables and +/// `AnonymousBarrier` regions for lambdas and anonymous methods. +/// `in_anonymous` is true inside such an identity barrier; `in_callable` is true +/// when inside a body-bearing callable body (used to gate top-level local +/// functions). +fn walk( + node: Node<'_>, + bytes: &[u8], + path: &Path, + in_anonymous: bool, + in_callable: bool, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + let kind = node.kind(); + // The file-scoped namespace is emitted as a sibling of the top-level + // declarations, not a lexical wrapper. Hoist its name into the container + // path for the whole compilation unit. + if kind == "compilation_unit" { + let mut cur = node.walk(); + let has_fs_ns = node + .named_children(&mut cur) + .any(|c| c.kind() == "file_scoped_namespace_declaration"); + let mut cur2 = node.walk(); + let fs_name: Option = node + .named_children(&mut cur2) + .find(|c| c.kind() == "file_scoped_namespace_declaration") + .and_then(|c| c.child_by_field_name("name")) + .and_then(|n| n.utf8_text(bytes).ok()) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()); + // A malformed file-scoped namespace (e.g. `namespace ;`) surfaces as an + // ERROR child whose text begins with the `namespace` keyword. + let mut cur3 = node.walk(); + let has_malformed_fs_ns = node.named_children(&mut cur3).any(|c| { + c.kind() == "ERROR" + && c.utf8_text(bytes) + .ok() + .is_some_and(|t| t.trim_start().starts_with("namespace")) + }); + // A file-scoped namespace exists but its name is missing/unreadable: + // fail closed so sibling declarations cannot leak unqualified to an + // outer container. + if (has_fs_ns && fs_name.is_none()) || has_malformed_fs_ns { + let start = node.start_position().row as u32 + 1; + let end = node.end_position().row as u32 + 1; + regions.push(OwnerRegion::AnonymousBarrier { + start_line: start, + end_line: end, + }); + for child in node.named_children(&mut node.walk()) { + if child.kind() == "file_scoped_namespace_declaration" { + continue; + } + walk( + child, + bytes, + path, + true, + in_callable, + containers, + errors, + regions, + ); + } + return; + } + if let Some(name) = fs_name.as_ref() { + containers.push(name.clone()); + } + let mut c2 = node.walk(); + for child in node.named_children(&mut c2) { + if child.kind() == "file_scoped_namespace_declaration" { + continue; + } + walk( + child, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + } + if fs_name.is_some() { + containers.pop(); + } + return; + } + + // Anonymous identity barriers. + if matches!(kind, "lambda_expression" | "anonymous_method_expression") { + barrier_and_descend(node, bytes, path, in_callable, containers, errors, regions); + return; + } + + // Axis-crossing identity barriers: a body-bearing callable inside an + // anonymous context is itself a barrier (its hits must not cross into the + // anonymous lambda/initializer identity). + if in_anonymous { + match kind { + "method_declaration" + | "local_function_statement" + | "constructor_declaration" + | "destructor_declaration" + | "operator_declaration" + | "conversion_operator_declaration" + | "accessor_declaration" => { + let start = node.start_position().row as u32 + 1; + let end = node.end_position().row as u32 + 1; + regions.push(OwnerRegion::AnonymousBarrier { + start_line: start, + end_line: end, + }); + walk_children( + node, + bytes, + path, + true, + in_callable, + containers, + errors, + regions, + ); + return; + } + _ => {} + } + } + + match kind { + "namespace_declaration" | "file_scoped_namespace_declaration" => { + if let Some(name) = required_identity(node, "name", bytes) { + containers.push(name.clone()); + walk_children( + node, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + containers.pop(); + } else { + // Missing/unreadable namespace identity: fail closed so nested + // methods cannot leak to an outer container. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + walk_children( + node, + bytes, + path, + true, + in_callable, + containers, + errors, + regions, + ); + } + } + "class_declaration" + | "struct_declaration" + | "interface_declaration" + | "record_declaration" + | "enum_declaration" => { + if let Some(name) = required_identity(node, "name", bytes) { + containers.push(name.clone()); + walk_children( + node, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + containers.pop(); + } else { + // Missing/unreadable type identity: fail closed so nested + // methods cannot leak to an outer container. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + walk_children( + node, + bytes, + path, + true, + in_callable, + containers, + errors, + regions, + ); + } + } + "method_declaration" => { + let start = node.start_position().row as u32 + 1; + let end = node.end_position().row as u32 + 1; + let has_body = node.child_by_field_name("body").is_some(); + if !has_body { + // Body-less (abstract/extern/interface-only/partial-signature). + walk_children( + node, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + return; + } + let Some(name) = required_identity(node, "name", bytes) else { + walk_children( + node, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + return; + }; + // Explicit interface members preserve the interface prefix from the + // AST (`IFoo.GetBar`); if it cannot be read, abstain. + let segment = match explicit_interface_prefix(node, bytes) { + Some(prefix) => format!("{prefix}.{name}"), + None => name.clone(), + }; + let qualified = join_containers(containers, &segment); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: segment.clone(), + receiver_var: None, + receiver_type: None, + package_dir: Path::new(".").to_path_buf(), + start_line: start, + end_line: end, + language: Lang::CSharp, + display_name: qualified, + }; + named_and_descend( + node, + bytes, + path, + move || anchor, + containers, + errors, + regions, + ); + } + "local_function_statement" => { + let start = node.start_position().row as u32 + 1; + let end = node.end_position().row as u32 + 1; + let has_body = node.child_by_field_name("body").is_some(); + if !has_body { + walk_children( + node, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + return; + } + let Some(name) = required_identity(node, "name", bytes) else { + walk_children( + node, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + return; + }; + // A local function among top-level statements has no supported + // enclosing callable identity: intentional abstention. + if !in_callable { + regions.push(OwnerRegion::AnonymousBarrier { + start_line: start, + end_line: end, + }); + walk_children( + node, + bytes, + path, + true, + in_callable, + containers, + errors, + regions, + ); + return; + } + let qualified = join_containers(containers, &name); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: name.clone(), + receiver_var: None, + receiver_type: None, + package_dir: Path::new(".").to_path_buf(), + start_line: start, + end_line: end, + language: Lang::CSharp, + display_name: qualified, + }; + named_and_descend( + node, + bytes, + path, + move || anchor, + containers, + errors, + regions, + ); + } + "constructor_declaration" | "destructor_declaration" => { + let start = node.start_position().row as u32 + 1; + let end = node.end_position().row as u32 + 1; + let has_body = node.child_by_field_name("body").is_some(); + if !has_body { + walk_children( + node, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + return; + } + // Uses the structurally declared type name. + let Some(type_name) = required_identity(node, "name", bytes) + .or_else(|| containers.last().cloned()) + .filter(|s| !s.is_empty()) + else { + walk_children( + node, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + return; + }; + let qualified = join_containers(containers, &type_name); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: type_name.clone(), + receiver_var: None, + receiver_type: None, + package_dir: Path::new(".").to_path_buf(), + start_line: start, + end_line: end, + language: Lang::CSharp, + display_name: qualified, + }; + named_and_descend( + node, + bytes, + path, + move || anchor, + containers, + errors, + regions, + ); + } + "operator_declaration" => { + let start = node.start_position().row as u32 + 1; + let end = node.end_position().row as u32 + 1; + let has_body = node.child_by_field_name("body").is_some(); + if !has_body { + walk_children( + node, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + return; + } + if let Some(op) = required_identity(node, "operator", bytes) { + let segment = format!("operator {op}"); + let qualified = join_containers(containers, &segment); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: segment.clone(), + receiver_var: None, + receiver_type: None, + package_dir: Path::new(".").to_path_buf(), + start_line: start, + end_line: end, + language: Lang::CSharp, + display_name: qualified, + }; + named_and_descend( + node, + bytes, + path, + move || anchor, + containers, + errors, + regions, + ); + } else { + walk_children( + node, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + } + } + "conversion_operator_declaration" => { + let start = node.start_position().row as u32 + 1; + let end = node.end_position().row as u32 + 1; + let has_body = node.child_by_field_name("body").is_some(); + if !has_body { + walk_children( + node, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + return; + } + let target = required_identity(node, "type", bytes); + if let Some(target) = target { + let kv = conversion_keyword(node); + if let Some(kv) = kv { + let segment = format!("operator {kv} {target}"); + let qualified = join_containers(containers, &segment); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: segment.clone(), + receiver_var: None, + receiver_type: None, + package_dir: Path::new(".").to_path_buf(), + start_line: start, + end_line: end, + language: Lang::CSharp, + display_name: qualified, + }; + named_and_descend( + node, + bytes, + path, + move || anchor, + containers, + errors, + regions, + ); + } else { + // Missing `implicit`/`explicit` keyword: fail closed. Descend + // anonymous so nested named callables cannot leak. + barrier_and_descend( + node, + bytes, + path, + in_callable, + containers, + errors, + regions, + ); + } + } else { + // Missing/unreadable conversion target type: fail closed. + barrier_and_descend(node, bytes, path, in_callable, containers, errors, regions); + } + } + "property_declaration" | "event_declaration" | "indexer_declaration" => { + handle_accessor_container( + node, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + } + _ => walk_children( + node, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ), + } +} + +/// Handle property/event/indexer declarations: expression-bodied properties +/// become getter owners, and accessor lists become per-accessor owners. +fn handle_accessor_container( + declaration: Node<'_>, + bytes: &[u8], + path: &Path, + in_anonymous: bool, + in_callable: bool, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + let kind = declaration.kind(); + // Determine the base identity segment. + // property -> `Property`, event -> `Event`, indexer -> `this`. + let base = if kind == "indexer_declaration" { + Some("this".to_string()) + } else { + required_identity(declaration, "name", bytes) + }; + + // Expression-bodied property: the `value` field is the arrow clause. + if kind == "property_declaration" && declaration.child_by_field_name("accessors").is_none() { + if let Some(value) = declaration.child_by_field_name("value") { + if let Some(base) = &base { + let start = value.start_position().row as u32 + 1; + let end = value.end_position().row as u32 + 1; + let segment = format!("{base}.get"); + let qualified = join_containers(containers, &segment); + if in_anonymous { + regions.push(OwnerRegion::AnonymousBarrier { + start_line: start, + end_line: end, + }); + } else { + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: segment.clone(), + receiver_var: None, + receiver_type: None, + package_dir: Path::new(".").to_path_buf(), + start_line: start, + end_line: end, + language: Lang::CSharp, + display_name: qualified, + }; + let region = OwnerRegion::Named(anchor); + let region = degrade_named_on_error( + region, + errors, + value.start_byte(), + value.end_byte(), + ); + regions.push(region); + } + } + } + walk_children( + declaration, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + return; + } + + // Accessor list: accessor_declaration nodes live under an `accessor_list` + // child. Iterate them. + let mut cur = declaration.walk(); + let accessors: Vec = declaration + .named_children(&mut cur) + .filter(|c| c.kind() == "accessor_list") + .flat_map(|al| { + let mut alwalk = al.walk(); + al.named_children(&mut alwalk).collect::>() + }) + .collect(); + for child in accessors { + let start = child.start_position().row as u32 + 1; + let end = child.end_position().row as u32 + 1; + let has_body = child.child_by_field_name("body").is_some(); + let accessor_kind = required_identity(child, "name", bytes); + let segment = match (&base, accessor_kind.as_deref()) { + (Some(base), Some(accessor_kind)) => Some(format!("{base}.{accessor_kind}")), + _ => None, + }; + if let Some(segment) = segment.as_ref() { + let qualified = join_containers(containers, segment); + if in_anonymous { + regions.push(OwnerRegion::AnonymousBarrier { + start_line: start, + end_line: end, + }); + } else if has_body { + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: segment.clone(), + receiver_var: None, + receiver_type: None, + package_dir: Path::new(".").to_path_buf(), + start_line: start, + end_line: end, + language: Lang::CSharp, + display_name: qualified, + }; + let region = OwnerRegion::Named(anchor); + let region = + degrade_named_on_error(region, errors, child.start_byte(), child.end_byte()); + regions.push(region); + } + } + // Required parent/accessor identity unreadable: fail closed so nested + // local fns cannot leak to an outer container. Only a complete identity + // (segment Some) + body + non-anonymous lets nested fns regain under the + // full pushed accessor segment. + match (segment.as_ref(), has_body, in_anonymous) { + (Some(segment), true, false) => { + // Owner already emitted above; push the segment so nested local + // fns regain their full enclosing callable path. + containers.push(segment.clone()); + walk_children(child, bytes, path, false, true, containers, errors, regions); + containers.pop(); + } + (None, true, _) => { + // Identity unreadable: full-range barrier + anonymous descend. + barrier_and_descend(child, bytes, path, true, containers, errors, regions); + } + _ => walk_children( + child, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ), + } + } +} + +fn walk_children( + node: Node<'_>, + bytes: &[u8], + path: &Path, + in_anonymous: bool, + in_callable: bool, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + let mut cursor = node.walk(); + for child in node.named_children(&mut cursor) { + walk( + child, + bytes, + path, + in_anonymous, + in_callable, + containers, + errors, + regions, + ); + } +} + +fn join_containers(containers: &[String], name: &str) -> String { + if containers.is_empty() { + name.to_string() + } else { + let mut joined = containers.join("."); + joined.push('.'); + joined.push_str(name); + joined + } +} + +/// Attribute a C# hit line to a named owner, honoring local errors. +pub(crate) fn csharp_owner_for<'a>( + regions: &'a [OwnerRegion], + errors: &[ErrorRange], + line: u32, +) -> Option<&'a OwnerAnchor> { + attribute_line(regions, errors, line) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + use std::path::PathBuf; + + fn path() -> PathBuf { + PathBuf::from("tests/fixtures/x.cs") + } + + fn parse(src: &str) -> (Vec, Vec) { + csharp_regions(&path(), src).expect("should parse") + } + + fn assert_owner(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32, name: &str) { + let owner = csharp_owner_for(regions, errors, line); + assert_eq!( + owner.map(OwnerAnchor::qualified_name), + Some(name.to_string()), + "line {line} should attribute to {name}" + ); + } + + fn assert_abstain(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32) { + assert!( + csharp_owner_for(regions, errors, line).is_none(), + "line {line} should abstain" + ); + } + + #[test] + fn malformed_named_container_abstains_nested_method() { + // Anonymous/missing-name class must fail closed: nested `Leaf` abstains, + // and sibling `A` still resolves to the outer `Service` container. + let (r, e) = parse( + "class Service {\n public static class {\n void Leaf() {}\n }\n void A() {}\n}\n", + ); + assert_abstain(&r, &e, 3); // Leaf inside malformed anonymous class + assert_owner(&r, &e, 5, "Service.A"); // sibling unaffected + } + + #[test] + fn conversion_keyword_requires_implicit_explicit() { + use tree_sitter::Parser; + let mut p = Parser::new(); + let lang = tree_sitter_c_sharp::LANGUAGE; + p.set_language(&lang.into()).unwrap(); + let valid = "class Service { public static explicit operator int(Service s) {} }\n"; + let t = p.parse(valid, None).unwrap(); + let conv = find_kind(t.root_node(), "conversion_operator_declaration"); + assert_eq!(conversion_keyword(conv), Some("explicit".to_string()),); + let missing = "class Service { public static operator int(Service s) {} }\n"; + let t2 = p.parse(missing, None).unwrap(); + let m = find_kind(t2.root_node(), "method_declaration"); + assert_eq!(conversion_keyword(m), None); + } + + fn find_kind<'t>(n: tree_sitter::Node<'t>, kind: &str) -> tree_sitter::Node<'t> { + if n.kind() == kind { + return n; + } + for c in n.named_children(&mut n.walk()) { + let r = find_kind(c, kind); + if r.kind() == kind { + return r; + } + } + n + } + + #[test] + fn required_identity_trims_and_rejects_empty() { + // Every required identity component must be trimmed and must never yield + // a dangling segment (`Service.` / `.get` / `operator `). + use tree_sitter::Parser; + let mut p = Parser::new(); + let lang = tree_sitter_c_sharp::LANGUAGE; + p.set_language(&lang.into()).unwrap(); + let s = "class Service {\n void Load() {}\n}\n"; + let tree = p.parse(s, None).unwrap(); + let root = tree.root_node(); + let cls = find_kind(root, "class_declaration"); + let method = find_kind(root, "method_declaration"); + assert_eq!( + required_identity(cls, "name", s.as_bytes()), + Some("Service".to_string()), + ); + assert_eq!( + required_identity(method, "name", s.as_bytes()), + Some("Load".to_string()), + ); + // Absent fields yield None (no dangling `operator ` / `.get`). + assert_eq!(required_identity(cls, "operator", s.as_bytes()), None); + assert_eq!(required_identity(method, "type", s.as_bytes()), None); + } + + #[test] + fn top_level_method_and_class_method() { + let (r, e) = parse("class Service {\n void Load() {\n int x = 1;\n }\n}\n"); + assert_owner(&r, &e, 2, "Service.Load"); + assert_owner(&r, &e, 3, "Service.Load"); + } + + #[test] + fn namespace_container_dotted() { + let (r, e) = parse("namespace Acme.Api {\n class Service {\n void Load() {\n }\n }\n}\n"); + assert_owner(&r, &e, 3, "Acme.Api.Service.Load"); + } + + #[test] + fn malformed_file_scoped_namespace_abstains_sibling() { + // A malformed file-scoped namespace (`namespace ;`) must not let the + // sibling method leak unqualified as `Service.Load`. + let (r, e) = parse("namespace ;\nclass Service {\n void Load() {}\n}\n"); + assert_abstain(&r, &e, 3); + } + #[test] + fn file_scoped_namespace_container() { + let (r, e) = parse("namespace Acme;\nclass Service {\n void Load() {\n }\n}\n"); + assert_owner(&r, &e, 3, "Acme.Service.Load"); + } + + #[test] + fn malformed_accessor_identity_abstains_nested_local() { + // An accessor whose `get`/`set` identity is unreadable (empty name) must + // fail closed: the nested local function cannot leak to the parent type. + let (r, e) = parse("class Service {\n int P {\n { int Parse(){} }\n }\n}\n"); + assert_abstain(&r, &e, 3); // Parse inside malformed accessor + } + + #[test] + fn nested_type_containers() { + let (r, e) = parse( + "class Outer {\n class Inner {\n void Handle() {\n }\n }\n}\n", + ); + assert_owner(&r, &e, 3, "Outer.Inner.Handle"); + } + + #[test] + fn expression_bodied_method_is_body_bearing() { + let (r, e) = parse("class Service {\n int Load() => 42;\n}\n"); + assert_owner(&r, &e, 2, "Service.Load"); + } + + #[test] + fn property_accessor_get_set() { + let (r, e) = parse( + "class Service {\n int P {\n get { return 1; }\n set { }\n }\n}\n", + ); + assert_owner(&r, &e, 3, "Service.P.get"); + assert_owner(&r, &e, 4, "Service.P.set"); + } + + #[test] + fn local_fn_inside_getter_follows_full_accessor_path() { + let (r, e) = parse( + "class Service {\n int P {\n get {\n int Parse() { return 1; }\n }\n }\n}\n", + ); + assert_owner(&r, &e, 4, "Service.P.get.Parse"); + } + + #[test] + fn expression_bodied_property_is_getter() { + let (r, e) = parse("class Service {\n int P => 42;\n}\n"); + assert_owner(&r, &e, 2, "Service.P.get"); + } + + #[test] + fn auto_property_accessors_abstain() { + let (r, e) = parse("class Service {\n int P { get; set; }\n}\n"); + assert_abstain(&r, &e, 2); + } + + #[test] + fn event_accessors_add_remove() { + let (r, e) = parse("class Service {\n event System.Action E {\n add { }\n remove { }\n }\n}\n"); + assert_owner(&r, &e, 3, "Service.E.add"); + assert_owner(&r, &e, 4, "Service.E.remove"); + } + + #[test] + fn indexer_accessor_this() { + let (r, e) = parse("class Service {\n int this[int i] {\n get { return i; }\n set { }\n }\n}\n"); + assert_owner(&r, &e, 3, "Service.this.get"); + assert_owner(&r, &e, 4, "Service.this.set"); + } + + #[test] + fn explicit_interface_method_preserved() { + let (r, e) = parse("interface IFoo { int GetBar(); }\nclass Service : IFoo {\n int IFoo.GetBar() => 7;\n}\n"); + assert_owner(&r, &e, 3, "Service.IFoo.GetBar"); + } + + #[test] + fn operator_and_conversion_operator() { + let (r, e) = parse("class Service {\n public static Service operator +(Service a, Service b) => a;\n public static implicit operator int(Service s) => 1;\n public static explicit operator int(Service s) => 1;\n}\n"); + assert_owner(&r, &e, 2, "Service.operator +"); + assert_owner(&r, &e, 3, "Service.operator implicit int"); + assert_owner(&r, &e, 4, "Service.operator explicit int"); + } + + #[test] + fn constructor_and_destructor_use_type_name() { + let (r, e) = parse("class Service {\n Service() { }\n ~Service() { }\n}\n"); + assert_owner(&r, &e, 2, "Service.Service"); + assert_owner(&r, &e, 3, "Service.Service"); + } + + #[test] + fn local_function_appends_to_callable() { + let (r, e) = parse( + "class Service {\n void Load() {\n int Parse() { return 1; }\n }\n}\n", + ); + assert_owner(&r, &e, 3, "Service.Load.Parse"); + } + + #[test] + fn top_level_local_function_abstains() { + let (r, e) = parse("int TopLocal() => 5;\n"); + assert_abstain(&r, &e, 1); + } + + #[test] + fn lambda_and_anonymous_method_barriers() { + let (r, e) = parse("class Service {\n void Load() {\n System.Func f = () => 42;\n System.Action a = delegate { };\n }\n}\n"); + assert_owner(&r, &e, 2, "Service.Load"); + assert_abstain(&r, &e, 3); + assert_abstain(&r, &e, 4); + } + + #[test] + fn bodyless_method_abstains() { + let (r, e) = parse("interface IFace {\n void Abs();\n}\n"); + assert_abstain(&r, &e, 2); + } + + #[test] + fn partial_method_signature_abstains_impl_eligible() { + let (r, e) = parse("partial class P {\n partial void M();\n}\n"); + assert_abstain(&r, &e, 2); + } + + #[test] + fn malformed_local_error_degrades() { + let (r, e) = parse("class Service {\n void Broken() {\n int x = (\n }\n}\n"); + assert_abstain(&r, &e, 3); + } + + #[test] + fn clean_method_elsewhere_in_partial_tree_eligible() { + let (r, e) = parse("class Service {\n void Good() {\n int x = 1;\n }\n void Broken() {\n int x = (\n }\n}\n"); + assert_owner(&r, &e, 2, "Service.Good"); + assert_owner(&r, &e, 3, "Service.Good"); + assert_abstain(&r, &e, 6); + } + + /// A single independent fixture, parsed on its own with 1-based local line + /// numbers. `owners` lists `(hit_line, name, start_line, end_line)` that + /// must attribute to the exact owner; `abstain` lists lines that must + /// abstain and count toward the intentional-abstention floor; `incidental` + /// lists lines that must abstain but do NOT count. + struct Case { + label: &'static str, + source: &'static str, + owners: &'static [(u32, &'static str, u32, u32)], + abstain: &'static [u32], + incidental: &'static [u32], + } + + /// US-068 curated C# accuracy gate. + #[test] + fn csharp_owner_matrix_meets_quality_gates() { + let cases: &[Case] = &[ + Case { + label: "multi-line method body", + source: "class Service {\n void Load() {\n int a = 1;\n int b = 2;\n System.Console.WriteLine(a + b);\n }\n}\n", + owners: &[(2, "Service.Load", 2, 6), (3, "Service.Load", 2, 6), (4, "Service.Load", 2, 6), (5, "Service.Load", 2, 6), (6, "Service.Load", 2, 6)], + abstain: &[1], + incidental: &[7], + }, + Case { + label: "class method", + source: "class Service {\n void Load() {\n int x = 1;\n }\n}\n", + owners: &[(2, "Service.Load", 2, 4), (3, "Service.Load", 2, 4), (4, "Service.Load", 2, 4)], + abstain: &[1], + incidental: &[5], + }, + Case { + label: "two methods", + source: "class Service {\n void A() {\n int x = 1;\n }\n void B() {\n int y = 2;\n }\n}\n", + owners: &[ + (2, "Service.A", 2, 4), + (3, "Service.A", 2, 4), + (4, "Service.A", 2, 4), + (5, "Service.B", 5, 7), + (6, "Service.B", 5, 7), + (7, "Service.B", 5, 7), + ], + abstain: &[1], + incidental: &[8], + }, + Case { + label: "multi-line method two statements", + source: "class Service {\n int Add(int a, int b) {\n int sum = a + b;\n return sum;\n }\n}\n", + owners: &[(2, "Service.Add", 2, 5), (3, "Service.Add", 2, 5), (4, "Service.Add", 2, 5), (5, "Service.Add", 2, 5)], + abstain: &[1], + incidental: &[6], + }, + Case { + label: "multi-line setter body", + source: "class Service {\n int P {\n set {\n int y = value + 1;\n Apply(y);\n }\n }\n}\n", + owners: &[(3, "Service.P.set", 3, 6), (4, "Service.P.set", 3, 6), (5, "Service.P.set", 3, 6), (6, "Service.P.set", 3, 6)], + abstain: &[1, 2], + incidental: &[7, 8], + }, + Case { + label: "three-method region", + source: "class Service {\n void A() {}\n void B() {}\n void C() {}\n}\n", + owners: &[(2, "Service.A", 2, 2), (3, "Service.B", 3, 3), (4, "Service.C", 4, 4)], + abstain: &[1], + incidental: &[5], + }, + Case { + label: "multi-line getter body", + source: "class Service {\n int P {\n get {\n return 1;\n }\n }\n}\n", + owners: &[(3, "Service.P.get", 3, 5), (4, "Service.P.get", 3, 5), (5, "Service.P.get", 3, 5)], + abstain: &[1, 2], + incidental: &[6, 7], + }, + Case { + label: "namespace + nested type method", + source: "namespace Acme {\n namespace Api {\n class Service {\n void Load() {}\n }\n }\n}\n", + owners: &[(4, "Acme.Api.Service.Load", 4, 4)], + abstain: &[1, 2, 3], + incidental: &[5, 6, 7], + }, + Case { + label: "block namespace container", + source: "namespace Acme.Api {\n class Service {\n void Load() {\n }\n }\n}\n", + owners: &[(3, "Acme.Api.Service.Load", 3, 4), (4, "Acme.Api.Service.Load", 3, 4)], + abstain: &[1, 2], + incidental: &[5, 6], + }, + Case { + label: "file-scoped namespace container", + source: "namespace Acme;\nclass Service {\n void Load() {\n }\n}\n", + owners: &[(3, "Acme.Service.Load", 3, 4), (4, "Acme.Service.Load", 3, 4)], + abstain: &[1, 2], + incidental: &[5], + }, + Case { + label: "nested declared types", + source: "class Outer {\n class Inner {\n void Handle() {\n }\n }\n}\n", + owners: &[(3, "Outer.Inner.Handle", 3, 4), (4, "Outer.Inner.Handle", 3, 4)], + abstain: &[1, 2], + incidental: &[5, 6], + }, + Case { + label: "expression-bodied method", + source: "class Service {\n int Load() => 42;\n}\n", + owners: &[(2, "Service.Load", 2, 2)], + abstain: &[1], + incidental: &[3], + }, + Case { + label: "expression-bodied property getter", + source: "class Service {\n int P => 42;\n}\n", + owners: &[(2, "Service.P.get", 2, 2)], + abstain: &[1], + incidental: &[3], + }, + Case { + label: "property accessor get/set", + source: "class Service {\n int P {\n get { return 1; }\n set { }\n }\n}\n", + owners: &[(3, "Service.P.get", 3, 3), (4, "Service.P.set", 4, 4), (3, "Service.P.get", 3, 3)], + abstain: &[1, 2], + incidental: &[5, 6], + }, + Case { + label: "auto-property abstains", + source: "class Service {\n int P { get; set; }\n}\n", + owners: &[], + abstain: &[1, 2], + incidental: &[3], + }, + Case { + label: "event accessors", + source: "class Service {\n event System.Action E {\n add { }\n remove { }\n }\n}\n", + owners: &[(3, "Service.E.add", 3, 3), (4, "Service.E.remove", 4, 4)], + abstain: &[1, 2], + incidental: &[5, 6], + }, + Case { + label: "indexer accessors", + source: "class Service {\n int this[int i] {\n get { return i; }\n set { }\n }\n}\n", + owners: &[(3, "Service.this.get", 3, 3), (4, "Service.this.set", 4, 4)], + abstain: &[1, 2], + incidental: &[5, 6], + }, + Case { + label: "explicit interface method", + source: "interface IFoo { int GetBar(); }\nclass Service : IFoo {\n int IFoo.GetBar() => 7;\n}\n", + owners: &[(3, "Service.IFoo.GetBar", 3, 3)], + abstain: &[1, 2], + incidental: &[4], + }, + Case { + label: "operator", + source: "class Service {\n public static Service operator +(Service a, Service b) => a;\n}\n", + owners: &[(2, "Service.operator +", 2, 2)], + abstain: &[1], + incidental: &[3], + }, + Case { + label: "conversion operators", + source: "class Service {\n public static implicit operator int(Service s) => 1;\n public static explicit operator string(Service s) => \"x\";\n}\n", + owners: &[ + (2, "Service.operator implicit int", 2, 2), + (3, "Service.operator explicit string", 3, 3), + ], + abstain: &[1], + incidental: &[4], + }, + Case { + label: "constructor and destructor", + source: "class Service {\n Service() { }\n ~Service() { }\n}\n", + owners: &[(2, "Service.Service", 2, 2), (3, "Service.Service", 3, 3)], + abstain: &[1], + incidental: &[4], + }, + Case { + label: "local function full path", + source: "class Service {\n void Load() {\n int Parse() { return 1; }\n }\n}\n", + owners: &[(2, "Service.Load", 2, 4), (3, "Service.Load.Parse", 3, 3), (4, "Service.Load", 2, 4)], + abstain: &[1], + incidental: &[5], + }, + Case { + label: "top-level local function abstains", + source: "int TopLocal() => 5;\n", + owners: &[], + abstain: &[1], + incidental: &[], + }, + Case { + label: "lambda barrier", + source: "class Service {\n void Load() {\n System.Func f = () => 42;\n }\n}\n", + owners: &[(2, "Service.Load", 2, 4), (4, "Service.Load", 2, 4)], + abstain: &[3], + incidental: &[5], + }, + Case { + label: "anonymous method barrier", + source: "class Service {\n void Load() {\n System.Action a = delegate { };\n }\n}\n", + owners: &[(2, "Service.Load", 2, 4), (4, "Service.Load", 2, 4)], + abstain: &[3], + incidental: &[5], + }, + Case { + label: "bodyless interface method abstains", + source: "interface IFace {\n void Abs();\n}\n", + owners: &[], + abstain: &[1, 2], + incidental: &[3], + }, + Case { + label: "partial method signature abstains", + source: "partial class P {\n partial void M();\n}\n", + owners: &[], + abstain: &[1, 2], + incidental: &[3], + }, + Case { + label: "malformed degrades", + source: "class Service {\n void Broken() {\n int x = (\n }\n}\n", + owners: &[], + abstain: &[1, 2, 3], + incidental: &[4, 5], + }, + Case { + label: "clean plus malformed partial", + source: "class Service {\n void Good() {\n int x = 1;\n }\n void Broken() {\n int x = (\n }\n}\n", + owners: &[(2, "Service.Good", 2, 4), (3, "Service.Good", 2, 4), (4, "Service.Good", 2, 4)], + abstain: &[6], + incidental: &[5, 7, 8], + }, + ]; + + let mut positives = 0u32; + let mut abstentions = 0u32; + for case in cases { + let (regions, errors) = parse(case.source); + for &(hit_line, name, start, end) in case.owners { + positives += 1; + let owner = csharp_owner_for(®ions, &errors, hit_line); + assert!( + owner.is_some(), + "[{}] line {hit_line}: expected {name}@{start}-{end}, got abstain", + case.label + ); + let owner = owner.unwrap(); + assert_eq!(owner.qualified_name(), name, "[{}] name", case.label); + assert_eq!(owner.start_line, start, "[{}] start", case.label); + assert_eq!(owner.end_line, end, "[{}] end", case.label); + } + for &line in case.abstain { + abstentions += 1; + assert!( + csharp_owner_for(®ions, &errors, line).is_none(), + "[{}] line {line} should abstain", + case.label + ); + } + for &line in case.incidental { + assert!( + csharp_owner_for(®ions, &errors, line).is_none(), + "[{}] incidental line {line} should abstain", + case.label + ); + } + } + assert!( + positives >= 60, + "positive floor: only {positives} assertions" + ); + assert!( + abstentions >= 20, + "intentional-abstention floor: only {abstentions} assertions" + ); + } + + #[test] + fn manifest_gate_verifies_kinds_exist_and_fingerprint_is_pinned() { + let v: serde_json::Value = serde_json::from_str(tree_sitter_c_sharp::NODE_TYPES).unwrap(); + let kinds: HashSet = v + .as_array() + .unwrap() + .iter() + .filter_map(|e| e.get("type").and_then(|t| t.as_str()).map(String::from)) + .collect(); + assert!(!kinds.is_empty(), "NODE_TYPES must declare node kinds"); + for k in CSHARP_EXECUTABLE_CALLABLES + .iter() + .chain(CSHARP_CONTAINER_KINDS) + .chain(CSHARP_BODILESS_OR_BARRIER_KINDS) + { + assert!( + kinds.contains(*k), + "manifest kind {k} missing from NODE_TYPES" + ); + } + let mut all: Vec<&str> = Vec::new(); + all.extend(CSHARP_EXECUTABLE_CALLABLES); + all.extend(CSHARP_CONTAINER_KINDS); + all.extend(CSHARP_BODILESS_OR_BARRIER_KINDS); + let uniq: HashSet<&str> = all.iter().copied().collect(); + assert_eq!( + uniq.len(), + all.len(), + "manifest inventories must be disjoint" + ); + assert_eq!( + fnv1a(tree_sitter_c_sharp::NODE_TYPES.as_bytes()), + CSHARP_NODE_TYPES_FINGERPRINT, + "tree-sitter-c-sharp NODE_TYPES changed; re-audit the manifest" + ); + } +} diff --git a/src/evidence/owners/java.rs b/src/evidence/owners/java.rs new file mode 100644 index 0000000..a623add --- /dev/null +++ b/src/evidence/owners/java.rs @@ -0,0 +1,743 @@ +//! Java owner-region extraction (US-068 Wave 2A). +//! +//! Supported named owners: body-bearing `method_declaration` (its identifier), +//! body-bearing `constructor_declaration` / `compact_constructor_declaration` +//! (the enclosing declared type name), and declared class/interface/enum/ +//! record/annotation-type containers forming a `.` lexical hierarchy +//! (`Service.handle`, `Outer.Inner.handle`, `RecordName.RecordName`). A named +//! local class declared inside a supported method contributes its complete +//! declared-type path (`Service.handle.Local.run`). The owner range is the +//! callable AST node itself; annotations/Javadoc inside that node are owned, +//! those outside it are not. +//! +//! Abstentions/barriers: every `lambda_expression` is an `AnonymousBarrier`; +//! static and instance initializer blocks are identity barriers; an anonymous +//! class body is an identity barrier; a method without a body (interface/ +//! abstract/native signature) is not a named owner; method references, +//! invocations, and object-creation expressions are never promoted to owners. + +use std::path::Path; + +use tree_sitter::Node; + +use crate::evidence::owner_links::OwnerAnchor; +use crate::evidence::owners::{ + attribute_line, collect_error_ranges, degrade_named_on_error, ErrorRange, OwnerRegion, +}; +use crate::lang::outline::outline_language; +use crate::types::Lang; + +/// Version-pinned Java callable manifest (anti-drift contract), holding the +/// pinned tree-sitter-java 0.23.5 callable kinds. +#[cfg(test)] +const JAVA_EXECUTABLE_CALLABLES: &[&str] = &[ + "method_declaration", + "constructor_declaration", + "compact_constructor_declaration", + "lambda_expression", +]; +#[cfg(test)] +const JAVA_CONTAINER_KINDS: &[&str] = &[ + "class_declaration", + "interface_declaration", + "enum_declaration", + "record_declaration", + "annotation_type_declaration", +]; +#[cfg(test)] +const JAVA_BODILESS_OR_BARRIER_KINDS: &[&str] = &[ + "static_initializer", + "class_body", + "object_creation_expression", + "method_reference", + "method_invocation", +]; + +/// FNV-1a-64 fingerprint of the bundled `tree-sitter-java` `NODE_TYPES` JSON +/// (tree-sitter-java 0.23.5). Pinned so any grammar metadata change fails the +/// manifest gate and forces a re-audit. +#[cfg(test)] +const JAVA_NODE_TYPES_FINGERPRINT: u64 = 0x4f88_944f_73e9_4562; + +/// Stable FNV-1a 64-bit hash, dependency-free and reproducible across builds. +#[cfg(test)] +fn fnv1a(bytes: &[u8]) -> u64 { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for &b in bytes { + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x100_0000_01b3); + } + hash +} + +/// Parse a Java file and produce its owner regions and local error ranges. +/// Returns `None` when the file cannot be read, has no tree, or its root node +/// itself is an `ERROR` (preserve raw hits, emit no owner evidence). +pub(crate) fn java_regions( + path: &Path, + content: &str, +) -> Option<(Vec, Vec)> { + let language = outline_language(Lang::Java)?; + let mut parser = tree_sitter::Parser::new(); + if parser.set_language(&language).is_err() { + return None; + } + let tree = parser.parse(content, None)?; + if tree.root_node().kind() == "ERROR" { + return None; + } + let bytes = content.as_bytes(); + let errors = collect_error_ranges(&tree, bytes); + let mut regions = Vec::new(); + let mut containers: Vec = Vec::new(); + walk( + tree.root_node(), + bytes, + path, + false, + &mut containers, + &errors, + &mut regions, + ); + Some((regions, errors)) +} + +/// Whether a node is an anonymous identity barrier regardless of its own kind: +/// an anonymous class body (`class_body` under `object_creation_expression` or +/// `enum_constant`) or an instance initializer (bare `block` directly under a +/// `class_body`). These carry no structural name, so everything crossing them +/// abstains. +fn is_anonymous_identity_barrier(node: Node<'_>) -> bool { + if node.kind() == "class_body" { + return matches!( + node.parent().map(|p| p.kind()), + Some("object_creation_expression" | "enum_constant") + ); + } + if node.kind() == "block" { + return matches!(node.parent().map(|p| p.kind()), Some("class_body")); + } + false +} + +/// Walk a Java tree, emitting `Named` regions for body-bearing callables and +/// `AnonymousBarrier` regions for lambdas, initializers, and anonymous class +/// bodies. `in_anonymous` is true when inside such an identity barrier: nested +/// callables then emit barriers (never `Named`) so they cannot contribute an +/// incomplete identity. +fn walk( + node: Node<'_>, + bytes: &[u8], + path: &Path, + in_anonymous: bool, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + // Anonymous identity barriers (no structural name): lambda, initializer, + // anonymous class body. Emit a full-range barrier and descend in_anonymous. + if node.kind() == "lambda_expression" { + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + walk_children(node, bytes, path, true, containers, errors, regions); + return; + } + if node.kind() == "static_initializer" || is_anonymous_identity_barrier(node) { + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + walk_children(node, bytes, path, true, containers, errors, regions); + return; + } + + match node.kind() { + "method_declaration" | "constructor_declaration" | "compact_constructor_declaration" => { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + // A body is required: interface/abstract/native signatures are not + // named owners. + let has_body = node.child_by_field_name("body").is_some(); + if in_anonymous { + // Inside an anonymous identity barrier: this callable has no + // complete stable identity; make it a barrier too. + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + walk_children(node, bytes, path, true, containers, errors, regions); + } else if has_body { + if let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + let name = name.to_string(); + let qualified = join_containers(containers, &name); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: name.clone(), + receiver_var: None, + receiver_type: None, + package_dir: std::path::PathBuf::from("."), + start_line, + end_line, + language: Lang::Java, + display_name: qualified, + }; + let region = OwnerRegion::Named(anchor); + let region = + degrade_named_on_error(region, errors, node.start_byte(), node.end_byte()); + regions.push(region); + // Push the callable name so a local class inside it receives + // the complete method path (`Service.handle.Local.run`). + containers.push(name); + walk_children(node, bytes, path, false, containers, errors, regions); + containers.pop(); + } else { + // Missing/unreadable identifier: abstain as a barrier. + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + walk_children(node, bytes, path, true, containers, errors, regions); + } + } else { + // Body-less declaration: not an owner, no containers to add. + walk_children(node, bytes, path, in_anonymous, containers, errors, regions); + } + } + "class_declaration" + | "interface_declaration" + | "enum_declaration" + | "record_declaration" + | "annotation_type_declaration" => { + if in_anonymous { + // A declared type inside an anonymous barrier has no complete + // identity; descend as a barrier so its members abstain. + walk_children(node, bytes, path, true, containers, errors, regions); + } else if let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + containers.push(name.to_string()); + walk_children(node, bytes, path, false, containers, errors, regions); + containers.pop(); + } else { + // Unnamed/malformed container: pin a conservative barrier so + // nested malformed regions cannot leak to an outer callable. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + walk_children(node, bytes, path, true, containers, errors, regions); + } + } + _ => walk_children(node, bytes, path, in_anonymous, containers, errors, regions), + } +} + +fn walk_children( + node: Node<'_>, + bytes: &[u8], + path: &Path, + in_anonymous: bool, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + let mut cursor = node.walk(); + for child in node.named_children(&mut cursor) { + walk( + child, + bytes, + path, + in_anonymous, + containers, + errors, + regions, + ); + } +} + +fn join_containers(containers: &[String], name: &str) -> String { + if containers.is_empty() { + name.to_string() + } else { + let mut joined = containers.join("."); + joined.push('.'); + joined.push_str(name); + joined + } +} + +/// Attribute a Java hit line to a named owner, honoring local errors. +pub(crate) fn java_owner_for<'a>( + regions: &'a [OwnerRegion], + errors: &[ErrorRange], + line: u32, +) -> Option<&'a OwnerAnchor> { + attribute_line(regions, errors, line) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + use std::path::PathBuf; + + fn path() -> PathBuf { + PathBuf::from("tests/fixtures/x.java") + } + + fn parse(src: &str) -> (Vec, Vec) { + java_regions(&path(), src).expect("should parse") + } + + fn assert_owner(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32, name: &str) { + let owner = java_owner_for(regions, errors, line); + assert_eq!( + owner.map(OwnerAnchor::qualified_name), + Some(name.to_string()), + "line {line} should attribute to {name}" + ); + } + + fn assert_abstain(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32) { + assert!( + java_owner_for(regions, errors, line).is_none(), + "line {line} should abstain" + ); + } + + #[test] + fn top_level_method_and_nested_class_hierarchy() { + let (r, e) = parse( + "class Service {\n void handle() { int x = 1; }\n class Inner { void go() { int y = 1; } }\n}\n", + ); + assert_owner(&r, &e, 2, "Service.handle"); + assert_owner(&r, &e, 3, "Service.Inner.go"); + } + + #[test] + fn constructor_uses_declared_type_name() { + let (r, e) = parse( + "class Service {\n Service() { int x = 1; }\n void m() { int y = 1; }\n}\n", + ); + assert_owner(&r, &e, 2, "Service.Service"); + assert_owner(&r, &e, 3, "Service.m"); + } + + #[test] + fn record_and_compact_constructor() { + let (r, e) = parse("record Point(int x, int y) {\n Point { int c = 1; }\n void m() { int d = 1; }\n}\n"); + assert_owner(&r, &e, 2, "Point.Point"); + assert_owner(&r, &e, 3, "Point.m"); + } + + #[test] + fn local_class_uses_complete_method_path() { + let (r, e) = parse("class Service {\n void outer() {\n class Local { void run() { int a = 1; } }\n }\n}\n"); + // The local class's method must NOT collapse to Service.run or + // Service.outer.run; it uses the full declared-type path. + assert_owner(&r, &e, 3, "Service.outer.Local.run"); + assert_owner(&r, &e, 2, "Service.outer"); + } + + #[test] + fn lambda_is_anonymous_barrier() { + let (r, e) = parse("class Service {\n void outer() {\n Runnable r = () -> { int a = 1; };\n }\n}\n"); + assert_owner(&r, &e, 2, "Service.outer"); + // The lambda line falls inside the lambda barrier -> abstain. + assert_abstain(&r, &e, 3); + } + + #[test] + fn static_and_instance_initializer_are_identity_barriers() { + let (r, e) = parse("class Service {\n static { int init = 1; }\n { int instance = 1; }\n void m() { int y = 1; }\n}\n"); + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + assert_owner(&r, &e, 4, "Service.m"); + } + + #[test] + fn bodyless_method_is_not_an_owner() { + let (r, e) = parse("interface Iface {\n void noBody();\n}\n"); + assert_abstain(&r, &e, 2); + } + + #[test] + fn anonymous_class_body_is_identity_barrier() { + let (r, e) = parse("class Service {\n void outer() {\n Object o = new Object() {\n void anon() { int b = 1; }\n };\n }\n}\n"); + // The anonymous class method must not be attributed to outer or + // fabricated a class name. + assert_owner(&r, &e, 2, "Service.outer"); + assert_abstain(&r, &e, 4); + } + + #[test] + fn enum_constant_class_body_is_identity_barrier() { + let (r, e) = parse("enum Color {\n RED { void special() { int s = 1; } }\n}\n"); + assert_abstain(&r, &e, 2); + } + + #[test] + fn malformed_local_error_degrades_to_barrier() { + let (r, e) = parse("class Service {\n void broken() {\n int x = (\n }\n}\n"); + assert_abstain(&r, &e, 3); + } + + #[test] + fn local_class_inside_static_initializer_abstains() { + // A named local class declared inside an initializer has no complete + // identity: its lexical path crosses the unnamed initializer context. + // `run` must NOT attribute to `Service.Local.run` (or `Service.run`). + let (r, e) = parse( + "class Service {\n static {\n class Local { void run() { int a = 1; } }\n }\n}\n", + ); + assert_abstain(&r, &e, 3); + assert_abstain(&r, &e, 2); + } + + #[test] + fn local_class_inside_instance_initializer_abstains() { + // Same strict crossing-context invariant for a bare instance initializer. + let (r, e) = parse( + "class Service {\n {\n class Local { void run() { int a = 1; } }\n }\n}\n", + ); + assert_abstain(&r, &e, 3); + assert_abstain(&r, &e, 2); + } + + #[test] + fn clean_callable_elsewhere_in_partial_tree_still_eligible() { + let (r, e) = parse("class Service {\n void good() { int x = 1; }\n void broken() {\n int x = (\n }\n}\n"); + assert_owner(&r, &e, 2, "Service.good"); + assert_abstain(&r, &e, 4); + } + + /// A single independent fixture, parsed on its own with 1-based local line + /// numbers. `owners` lists `(hit_line, name, start_line, end_line)` that + /// must attribute to the exact owner; `abstain` lists lines that must + /// abstain and count toward the intentional-abstention floor; `incidental` + /// lists lines that must abstain but do NOT count. + struct Case { + label: &'static str, + source: &'static str, + owners: &'static [(u32, &'static str, u32, u32)], + abstain: &'static [u32], + incidental: &'static [u32], + } + + /// US-068 curated Java accuracy gate: a table of independent, varied + /// fixtures. Counts assertions programmatically and asserts the floor + /// (`>=60` positive hits, `>=20` intentional abstentions); blank/separator + /// lines never count toward the abstention floor. Every positive row + /// asserts the exact owner (`qualified_name`, `start_line`, `end_line`). + #[test] + fn java_owner_matrix_meets_quality_gates() { + let cases: &[Case] = &[ + Case { + label: "top-level method", + source: "class A {\n void m() {\n int x = 1;\n }\n}\n", + owners: &[(2, "A.m", 2, 4), (3, "A.m", 2, 4), (4, "A.m", 2, 4)], + abstain: &[1], + incidental: &[0], + }, + Case { + label: "two methods", + source: "class B {\n void a() {\n int x = 1;\n }\n void b(int y) {\n return;\n }\n}\n", + owners: &[ + (2, "B.a", 2, 4), + (3, "B.a", 2, 4), + (4, "B.a", 2, 4), + (5, "B.b", 5, 7), + (6, "B.b", 5, 7), + (7, "B.b", 5, 7), + ], + abstain: &[1, 8], + incidental: &[], + }, + Case { + label: "nested declared types", + source: "class Outer {\n class Inner {\n void handle() {\n int x = 1;\n }\n }\n\n}\n", + owners: &[(3, "Outer.Inner.handle", 3, 5), (4, "Outer.Inner.handle", 3, 5)], + abstain: &[1, 2], + incidental: &[6, 7], + }, + Case { + label: "local class full path", + source: "class Service {\n void outer() {\n class Local {\n void run() {\n int a = 1;\n }\n }\n }\n}\n", + owners: &[ + (2, "Service.outer", 2, 8), + (3, "Service.outer", 2, 8), + (4, "Service.outer.Local.run", 4, 6), + (5, "Service.outer.Local.run", 4, 6), + (7, "Service.outer", 2, 8), + (8, "Service.outer", 2, 8), + ], + abstain: &[], + incidental: &[1, 9], + }, + Case { + label: "constructor + method", + source: "class Service {\n Service() {\n int x = 1;\n }\n void handle() {\n int y = 1;\n }\n}\n", + owners: &[ + (2, "Service.Service", 2, 4), + (3, "Service.Service", 2, 4), + (4, "Service.Service", 2, 4), + (5, "Service.handle", 5, 7), + (6, "Service.handle", 5, 7), + (7, "Service.handle", 5, 7), + ], + abstain: &[1], + incidental: &[8], + }, + Case { + label: "record compact constructor", + source: "record Point(int x) {\n Point {\n int c = 1;\n }\n}\n", + owners: &[ + (3, "Point.Point", 2, 4), + (2, "Point.Point", 2, 4), + (4, "Point.Point", 2, 4), + ], + abstain: &[1], + incidental: &[5], + }, + Case { + label: "interface bodyless abstains", + source: "interface Iface {\n void noBody();\n}\n", + owners: &[], + abstain: &[1, 2], + incidental: &[3], + }, + Case { + label: "abstract class bodyless method", + source: "abstract class Base {\n abstract void abs();\n}\n", + owners: &[], + abstain: &[2], + incidental: &[1, 3], + }, + Case { + label: "enum methods", + source: "enum Color {\n RED, GREEN;\n void colorMethod() {\n int d = 1;\n }\n}\n", + owners: &[ + (3, "Color.colorMethod", 3, 5), + (4, "Color.colorMethod", 3, 5), + (5, "Color.colorMethod", 3, 5), + ], + abstain: &[1, 2], + incidental: &[6], + }, + Case { + label: "enum constant class body barrier", + source: "enum Color {\n RED {\n void special() {\n int s = 1;\n }\n }\n}\n", + owners: &[], + abstain: &[2, 3, 4], + incidental: &[1, 5, 6, 7], + }, + Case { + label: "lambda barrier", + source: "class Service {\n void outer() {\n Runnable r = () -> {\n int a = 1;\n };\n }\n}\n", + owners: &[(2, "Service.outer", 2, 6), (6, "Service.outer", 2, 6)], + abstain: &[3, 4], + incidental: &[1, 5, 7], + }, + Case { + label: "static initializer barrier", + source: "class Service {\n static {\n int init = 1;\n }\n void m() {\n int y = 1;\n }\n}\n", + owners: &[(5, "Service.m", 5, 7), (6, "Service.m", 5, 7)], + abstain: &[2, 3], + incidental: &[1, 4, 8], + }, + Case { + label: "instance initializer barrier", + source: "class Service {\n {\n int inst = 1;\n }\n void m() {\n int y = 1;\n }\n}\n", + owners: &[(5, "Service.m", 5, 7), (6, "Service.m", 5, 7)], + abstain: &[2, 3], + incidental: &[1, 4, 8], + }, + Case { + label: "anonymous class body barrier", + source: "class Service {\n void outer() {\n Object o = new Object() {\n void anon() {\n int b = 1;\n }\n };\n }\n}\n", + owners: &[(2, "Service.outer", 2, 8), (8, "Service.outer", 2, 8)], + abstain: &[4, 5], + incidental: &[1, 3, 6, 7, 9], + }, + Case { + label: "annotation type element bodyless", + source: "@interface Ann {\n String value();\n}\n", + owners: &[], + abstain: &[1, 2], + incidental: &[3], + }, + Case { + label: "malformed error degrades", + source: "class Service {\n void broken() {\n int x = (\n int y = 2;\n }\n}\n", + owners: &[], + abstain: &[2, 3, 4], + incidental: &[1, 5, 6], + }, + Case { + label: "clean plus malformed partial", + source: "class Service {\n void good() {\n int x = 1;\n }\n void broken() {\n int x = (\n }\n}\n", + owners: &[(2, "Service.good", 2, 4), (3, "Service.good", 2, 4)], + abstain: &[5, 6], + incidental: &[1, 7, 8, 9], + }, + Case { + label: "method reference not an owner", + source: "class Service {\n void outer() {\n Runnable r = this::m;\n }\n}\n", + owners: &[ + (2, "Service.outer", 2, 4), + (3, "Service.outer", 2, 4), + (4, "Service.outer", 2, 4), + ], + abstain: &[], + // The method reference itself is never promoted to a named owner; + // hits on it fall through to the containing method. + incidental: &[1, 5], + }, + Case { + label: "invocation not promoted", + source: "class Service {\n void a() {\n int x = 1;\n }\n void b() {\n a();\n }\n}\n", + owners: &[ + (2, "Service.a", 2, 4), + (3, "Service.a", 2, 4), + (4, "Service.a", 2, 4), + (5, "Service.b", 5, 7), + (6, "Service.b", 5, 7), + (7, "Service.b", 5, 7), + ], + abstain: &[1], + incidental: &[8], + }, + Case { + label: "nested local class inside method full path", + source: "class Service {\n void outer() {\n class Local {\n void run() {\n class Deep {\n void go() {\n int a = 1;\n }\n }\n }\n }\n }\n}\n", + owners: &[ + (2, "Service.outer", 2, 12), + (3, "Service.outer", 2, 12), + (4, "Service.outer.Local.run", 4, 10), + (5, "Service.outer.Local.run", 4, 10), + (6, "Service.outer.Local.run.Deep.go", 6, 8), + (7, "Service.outer.Local.run.Deep.go", 6, 8), + (8, "Service.outer.Local.run.Deep.go", 6, 8), + (9, "Service.outer.Local.run", 4, 10), + (10, "Service.outer.Local.run", 4, 10), + (11, "Service.outer", 2, 12), + (12, "Service.outer", 2, 12), + ], + abstain: &[], + incidental: &[1, 13], + }, + Case { + label: "qualified generic method", + source: "class Util {\n T identity(T v) {\n return v;\n }\n}\n", + owners: &[ + (2, "Util.identity", 2, 4), + (3, "Util.identity", 2, 4), + (4, "Util.identity", 2, 4), + ], + abstain: &[1], + incidental: &[5], + }, + Case { + label: "empty class no regions", + source: "class Empty {\n}\n", + owners: &[], + abstain: &[1], + incidental: &[2], + }, + ]; + + let mut positives = 0u32; + let mut abstentions = 0u32; + for case in cases { + let (regions, errors) = parse(case.source); + for &(hit_line, name, start, end) in case.owners { + positives += 1; + let owner = java_owner_for(®ions, &errors, hit_line); + assert!( + owner.is_some(), + "[{}] line {hit_line}: expected {name}@{start}-{end}, got abstain", + case.label + ); + let owner = owner.unwrap(); + assert_eq!( + owner.qualified_name(), + name, + "[{}] line {hit_line} name", + case.label + ); + assert_eq!( + owner.start_line, start, + "[{}] line {hit_line} start", + case.label + ); + assert_eq!(owner.end_line, end, "[{}] line {hit_line} end", case.label); + } + for &line in case.abstain { + abstentions += 1; + assert!( + java_owner_for(®ions, &errors, line).is_none(), + "[{}] line {line} should abstain", + case.label + ); + } + for &line in case.incidental { + assert!( + java_owner_for(®ions, &errors, line).is_none(), + "[{}] incidental line {line} should abstain", + case.label + ); + } + } + assert!( + positives >= 60, + "positive floor: only {positives} assertions" + ); + assert!( + abstentions >= 20, + "intentional-abstention floor: only {abstentions} assertions" + ); + } + + #[test] + fn manifest_gate_verifies_kinds_exist_and_fingerprint_is_pinned() { + let v: serde_json::Value = serde_json::from_str(tree_sitter_java::NODE_TYPES).unwrap(); + let kinds: HashSet = v + .as_array() + .unwrap() + .iter() + .filter_map(|e| e.get("type").and_then(|t| t.as_str()).map(String::from)) + .collect(); + assert!(!kinds.is_empty(), "NODE_TYPES must declare node kinds"); + for k in JAVA_EXECUTABLE_CALLABLES + .iter() + .chain(JAVA_CONTAINER_KINDS) + .chain(JAVA_BODILESS_OR_BARRIER_KINDS) + { + assert!( + kinds.contains(*k), + "manifest kind {k} missing from NODE_TYPES" + ); + } + let mut all: Vec<&str> = Vec::new(); + all.extend(JAVA_EXECUTABLE_CALLABLES); + all.extend(JAVA_CONTAINER_KINDS); + all.extend(JAVA_BODILESS_OR_BARRIER_KINDS); + let uniq: HashSet<&str> = all.iter().copied().collect(); + assert_eq!( + uniq.len(), + all.len(), + "manifest inventories must be disjoint" + ); + assert_eq!( + fnv1a(tree_sitter_java::NODE_TYPES.as_bytes()), + JAVA_NODE_TYPES_FINGERPRINT, + "tree-sitter-java NODE_TYPES changed; re-audit the manifest" + ); + } +} diff --git a/src/evidence/owners/js_ts.rs b/src/evidence/owners/js_ts.rs new file mode 100644 index 0000000..3932f2c --- /dev/null +++ b/src/evidence/owners/js_ts.rs @@ -0,0 +1,1575 @@ +//! JavaScript/TypeScript/TSX owner-region extraction (US-067 slices 3B/3C). +//! +//! Supported named owners (`.`-qualified, per spec): +//! * `function_declaration` / `generator_function_declaration` -> `name` +//! (top-level) or `outer.inner` when nested in a function body. +//! * `method_definition` in a structurally named class -> `Class.method` +//! (get/set/async/generator all collapse to this kind; simple/private names +//! only, computed/string/number names barrier). +//! * A directly-bound arrow/function/generator expression: +//! - `const f = () => {}` and `const f = function named(){}` -> `f` +//! (direct simple variable binding wins). +//! - `class A { x = () => {} }` / `class A { x = function named(){} }` -> +//! `A.x` (direct class-field binding in a structurally named class wins; +//! JS uses `field_definition`, TS uses `public_field_definition`). +//! * An explicit internal function/generator name, when no supported direct +//! binding/property owner applies (e.g. a named IIFE) -> that own name. +//! +//! Everything else is an `AnonymousBarrier` (never omission, never a guessed +//! name): anonymous arrows/function expressions/IIFEs, object-literal callables +//! (`method_definition` under `object`, `pair { key: fn }`), anonymous classes +//! (invalid naming container), member/prototype assignments, computed names, +//! and `class_static_block` (a non-callable safety fallthrough guard). +//! +//! Invalid naming containers (anonymous class; unsupported object method/ +//! property callable; computed/unreadable class field or module name) are +//! sticky for descendants whose qualified identity would depend on the +//! missing/unsupported container: traversal recurses exhaustively but every +//! dependent nested callable is classified as a barrier. Anonymous callbacks +//! (arrow/IIFE/member-value) preserve the previously valid outer prefix, so a +//! named declaration inside them may remain eligible per the core barrier rule. +//! Binding/container nodes never emit duplicate callable regions. +//! +//! TypeScript additions (slice 3C): +//! * Body-less callable declarations (`function_signature`, +//! `abstract_method_signature`, `method_signature`, `call_signature`, +//! `construct_signature`) are barriers over their exact node spans; only a +//! body-bearing concrete node emits a `Named` region. +//! * Type-only non-callables (`property_signature`, `index_signature`, +//! `function_type`, `constructor_type`) are transparent: no barrier, no name. +//! * Valid prefix containers add named/abstract classes and TypeScript +//! `namespace`/`internal_module`/`module` (readable identifier or +//! nested-identifier segments only; string/computed module names barrier). +//! * `ambient_declaration`, decorators, export/default and type annotations +//! are transparent wrappers, not labels. Interface/type-alias/enum are +//! traversal containers that never become name prefixes. + +use std::path::Path; + +use tree_sitter::Node; + +use crate::evidence::owner_links::OwnerAnchor; +use crate::evidence::owners::{ + attribute_line, collect_error_ranges, degrade_named_on_error, ErrorRange, OwnerRegion, +}; +use crate::lang::outline::outline_language; +use crate::types::Lang; + +/// Version-pinned JavaScript callable manifest (anti-drift contract). +/// +/// Inventories are kept distinct so a grammar change to one category cannot +/// silently reclassify a node into another: +/// +/// * (a) executable callable kinds that MUST be classified `Named`/`Barrier`; +/// * (b) binding/container/wrapper kinds used only for naming/context; +/// * (c) non-callable safety barriers (fallthrough guard, no callable coverage). +#[cfg(test)] +const JS_EXECUTABLE_CALLABLES: &[&str] = &[ + "function_declaration", + "generator_function_declaration", + "function_expression", + "generator_function", + "arrow_function", + "method_definition", +]; +#[cfg(test)] +const JS_BINDING_CONTAINER_KINDS: &[&str] = &[ + "class_declaration", + "class", + "class_body", + "object", + "pair", + "field_definition", + "variable_declarator", + "statement_block", + "program", + "export_statement", +]; +#[cfg(test)] +const JS_NON_CALLABLE_SAFETY_BARRIERS: &[&str] = &["class_static_block"]; + +/// Version-pinned TypeScript callable manifest (slice 3C). Separate from the +/// JS inventories because the TypeScript grammar reuses JS callable kinds but +/// adds body-less signatures and a distinct class-field node. +#[cfg(test)] +const TS_EXECUTABLE_CALLABLES: &[&str] = &[ + "function_declaration", + "generator_function_declaration", + "function_expression", + "generator_function", + "arrow_function", + "method_definition", +]; +#[cfg(test)] +const TS_BODY_LESS_SIGNATURES: &[&str] = &[ + "abstract_method_signature", + "method_signature", + "function_signature", + "call_signature", + "construct_signature", +]; +#[cfg(test)] +const TS_BINDING_CONTAINER_KINDS: &[&str] = &[ + "class_declaration", + "abstract_class_declaration", + "class", + "class_body", + "object", + "pair", + "public_field_definition", + "variable_declarator", + "statement_block", + "program", + "export_statement", + "internal_module", + "module", + "interface_declaration", + "interface_body", + "type_alias_declaration", + "enum_declaration", + "enum_body", + "ambient_declaration", + "decorator", + "expression_statement", +]; +#[cfg(test)] +const TS_TYPE_ONLY_TRANSPARENT: &[&str] = &[ + "property_signature", + "index_signature", + "function_type", + "constructor_type", +]; +#[cfg(test)] +const TS_NON_CALLABLE_SAFETY_BARRIERS: &[&str] = &["class_static_block"]; + +/// TSX-only routing/wrapper kinds (JSX). These are NOT a callable inventory: +/// they are traversal/wrapper sentinels proving the TSX grammar routes JSX that +/// contains callables. Kept disjoint from the reusable TS callable/signature/ +/// binding/type-only inventories. +#[cfg(test)] +const TSX_ROUTING_WRAPPER_KINDS: &[&str] = &[ + "jsx_element", + "jsx_self_closing_element", + "jsx_expression", + "jsx_attribute", +]; + +/// FNV-1a-64 fingerprints of the bundled grammar `NODE_TYPES` JSON. Pinned so +/// any grammar metadata change fails the manifest gate and forces a re-audit. +#[cfg(test)] +const JS_NODE_TYPES_FINGERPRINT: u64 = 0x372f_ecd5_b5f8_67c2; +#[cfg(test)] +const TYPESCRIPT_NODE_TYPES_FINGERPRINT: u64 = 0x4c9c_a118_1310_63de; +#[cfg(test)] +const TSX_NODE_TYPES_FINGERPRINT: u64 = 0xda35_b73f_4bdc_e75b; + +/// Stable FNV-1a 64-bit hash, dependency-free and reproducible across builds. +#[cfg(test)] +fn fnv1a(bytes: &[u8]) -> u64 { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for &b in bytes { + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x100_0000_01b3); + } + hash +} + +/// Parse a JS/TS/TSX file (grammar selected by `lang`) and produce its owner +/// regions and local error ranges. Returns `None` when the file cannot be +/// read, has no tree, or its root node itself is an `ERROR` (preserve raw +/// hits, emit no owner evidence). +pub(crate) fn regions_for( + lang: Lang, + path: &Path, + content: &str, +) -> Option<(Vec, Vec)> { + let language = outline_language(lang)?; + let mut parser = tree_sitter::Parser::new(); + if parser.set_language(&language).is_err() { + return None; + } + let tree = parser.parse(content, None)?; + if tree.root_node().kind() == "ERROR" { + return None; + } + let bytes = content.as_bytes(); + let errors = collect_error_ranges(&tree, bytes); + let mut regions = Vec::new(); + let mut prefixes: Vec = Vec::new(); + walk( + tree.root_node(), + bytes, + path, + lang, + &mut prefixes, + &errors, + &mut regions, + false, + ); + Some((regions, errors)) +} + +/// Attribute a JS/TS/TSX hit line to a named owner, honoring local errors. +pub(crate) fn owner_for<'a>( + regions: &'a [OwnerRegion], + errors: &[ErrorRange], + line: u32, +) -> Option<&'a OwnerAnchor> { + attribute_line(regions, errors, line) +} + +/// Walk a JS/TS/TSX tree, emitting `Named` regions for supported callables and +/// `AnonymousBarrier` regions for every other callable. `prefixes` carries +/// `.`-suffixed path segments (classes, namespaces, namespaces/modules, +/// binding-backed callables, nested functions) so nested callables get their +/// full qualified name. `lang` sets the `OwnerAnchor.language` identity. +/// +/// `sticky` is true inside an invalid naming container (an anonymous class, an +/// unsupported object method/property callable, a computed/unreadable class +/// field or module name) whose descendants must all be classified as barriers +/// rather than emit a partial/guessed name. Traversal still recurses +/// exhaustively so EVERY callable node is classified. +fn walk( + node: Node<'_>, + bytes: &[u8], + path: &Path, + lang: Lang, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + sticky: bool, +) { + match node.kind() { + "function_declaration" | "generator_function_declaration" => { + walk_declaration(node, bytes, path, lang, prefixes, errors, regions, sticky); + } + "function_expression" | "generator_function" => { + walk_expression(node, bytes, path, lang, prefixes, errors, regions, sticky); + } + "arrow_function" => walk_arrow(node, bytes, path, lang, prefixes, errors, regions, sticky), + "method_definition" => { + walk_method(node, bytes, path, lang, prefixes, errors, regions, sticky); + } + // TS body-less callable declarations: barrier over their exact span. + "function_signature" + | "abstract_method_signature" + | "method_signature" + | "call_signature" + | "construct_signature" => { + walk_bodyless_signature(node, bytes, path, lang, prefixes, errors, regions, sticky); + } + // TS type-only non-callables and traversal-only containers/wrappers: + // transparent (no barrier, no name, never a prefix). + "property_signature" + | "index_signature" + | "function_type" + | "constructor_type" + | "interface_declaration" + | "interface_body" + | "type_alias_declaration" + | "enum_declaration" + | "enum_body" + | "ambient_declaration" + | "decorator" => { + recurse(node, bytes, path, lang, prefixes, errors, regions, sticky); + } + // Named class containers (regular or abstract) -> `.`-prefix. + "class_declaration" | "abstract_class_declaration" => { + walk_class_container(node, bytes, path, lang, prefixes, errors, regions, sticky); + } + "class" => { + // Class expression: an explicitly named class uses its own class + // name; an anonymous class is an invalid naming container (sticky). + if let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + prefixes.push(format!("{}.", name.trim())); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); + prefixes.pop(); + } else { + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); + } + } + "class_static_block" => { + // Non-callable safety barrier: guards fallthrough but does NOT claim + // callable coverage. Recurse preserving the outer naming context so a + // named declaration inside the static block stays eligible. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, sticky); + } + // TS internal_module/module: `.`-prefix containers (readable + // identifier/nested-identifier segments only; string -> sticky barrier). + // (`namespace` is only a keyword token in NODE_TYPES and is never + // visited via named_children traversal.) + "internal_module" | "module" => { + walk_module_container(node, bytes, path, lang, prefixes, errors, regions, sticky); + } + // Binding/container/wrapper nodes: traversal context only, never emit + // duplicate callable regions. Their callable values/children are handled + // by the callable arms above. + _ => recurse(node, bytes, path, lang, prefixes, errors, regions, sticky), + } +} + +/// A `function_declaration` / `generator_function_declaration` is always a +/// named callable (it carries a structural `name`); under a valid context it +/// emits a `Named` region and becomes a `.`-prefix for nested declarations. +fn walk_declaration( + node: Node<'_>, + bytes: &[u8], + path: &Path, + lang: Lang, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + sticky: bool, +) { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + if sticky { + // Descendant of an invalid naming container: barrier, keep classifying. + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); + return; + } + let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + else { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); + return; + }; + let name = name.trim().to_string(); + let qualified = join_prefixes(prefixes, &name); + emit_named(node, path, lang, &name, &qualified, errors, regions); + prefixes.push(format!("{name}.")); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); + prefixes.pop(); +} + +/// A `function_expression` / `generator_function` is classified by binding +/// precedence: (1) direct simple variable binding, (2) direct class-field +/// binding in a structurally named class, (3) explicit internal name, else (4) +/// barrier. An anonymous object-property callable is sticky for descendants. +fn walk_expression( + node: Node<'_>, + bytes: &[u8], + path: &Path, + lang: Lang, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + sticky: bool, +) { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + if sticky { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); + return; + } + // Unsupported direct binding context (computed field, destructuring/ + // pattern declarator): the callable cannot take a valid simple identity, so + // it is a barrier and its descendants are sticky barriers (no partial name). + if unsupported_field_direct_context(node) || unsupported_declarator_direct_context(node) { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); + return; + } + // Rule 1: direct simple variable binding wins. + if let Some(binding) = variable_binding_name(node, bytes) { + let qualified = join_prefixes(prefixes, &binding); + emit_named(node, path, lang, &binding, &qualified, errors, regions); + prefixes.push(format!("{binding}.")); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); + prefixes.pop(); + return; + } + // Rule 2: direct class-field binding in a structurally named class wins. + if let Some(field) = field_binding_name(node, bytes) { + let qualified = join_prefixes(prefixes, &field); + emit_named(node, path, lang, &field, &qualified, errors, regions); + prefixes.push(format!("{field}.")); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); + prefixes.pop(); + return; + } + // Rule 3: explicit internal name may render its own name. + if let Some(own) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + let own = own.trim().to_string(); + let qualified = join_prefixes(prefixes, &own); + emit_named(node, path, lang, &own, &qualified, errors, regions); + prefixes.push(format!("{own}.")); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); + prefixes.pop(); + return; + } + // Rule 4: anonymous. An object-property callable is an unsupported sticky + // container; any other anonymous callable (IIFE, member value, plain expr) + // is a non-sticky barrier preserving the outer prefix. + let object_property = node.parent().is_some_and(|p| p.kind() == "pair"); + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse( + node, + bytes, + path, + lang, + prefixes, + errors, + regions, + sticky || object_property, + ); +} + +/// An `arrow_function` is intrinsically anonymous: it is only `Named` when +/// promoted by a supported direct binding context (rule 1 variable or rule 2 +/// class-field); otherwise it is a barrier. +fn walk_arrow( + node: Node<'_>, + bytes: &[u8], + path: &Path, + lang: Lang, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + sticky: bool, +) { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + if sticky { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); + return; + } + // Unsupported direct binding context (computed field, destructuring/ + // pattern declarator): sticky barrier for the callable and its descendants. + if unsupported_field_direct_context(node) || unsupported_declarator_direct_context(node) { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); + return; + } + if let Some(binding) = variable_binding_name(node, bytes) { + let qualified = join_prefixes(prefixes, &binding); + emit_named(node, path, lang, &binding, &qualified, errors, regions); + prefixes.push(format!("{binding}.")); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); + prefixes.pop(); + return; + } + if let Some(field) = field_binding_name(node, bytes) { + let qualified = join_prefixes(prefixes, &field); + emit_named(node, path, lang, &field, &qualified, errors, regions); + prefixes.push(format!("{field}.")); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); + prefixes.pop(); + return; + } + let object_property = node.parent().is_some_and(|p| p.kind() == "pair"); + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse( + node, + bytes, + path, + lang, + prefixes, + errors, + regions, + sticky || object_property, + ); +} + +/// A `method_definition` in a structurally named class is `Class.method`; in an +/// object literal it is an unsupported sticky barrier; in an anonymous class it +/// is a sticky barrier. Computed/string/number names barrier. +fn walk_method( + node: Node<'_>, + bytes: &[u8], + path: &Path, + lang: Lang, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + sticky: bool, +) { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + if sticky { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); + return; + } + let parent_kind = node.parent().map(|p| p.kind().to_string()); + if parent_kind.as_deref() == Some("object") { + // Object literal method (incl. getters/setters/shorthand): unsupported + // in phase 1. Sticky for descendants. + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); + return; + } + if !in_named_class(node) { + // Anonymous class: invalid naming container, sticky. + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); + return; + } + let Some(name) = simple_member_name(node, bytes) else { + // Computed/string/number method name: incapable of a simple identity. + // Sticky: a nested declaration must not leak a partial `A.` + // name from an unreadable computed method. + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); + return; + }; + let qualified = join_prefixes(prefixes, &name); + emit_named(node, path, lang, &name, &qualified, errors, regions); + prefixes.push(format!("{name}.")); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); + prefixes.pop(); +} + +/// A TS body-less callable declaration is a barrier over its exact node span: +/// it has no runtime body so it can never be a concrete owner, and a nested +/// declaration must not fall through to an enclosing function. +fn walk_bodyless_signature( + node: Node<'_>, + bytes: &[u8], + path: &Path, + lang: Lang, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + sticky: bool, +) { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, sticky); +} + +/// A named `class_declaration` / `abstract_class_declaration` is a valid +/// `.`-prefix container; it is not itself a callable region (a hit on the +/// class header line abstains). +fn walk_class_container( + node: Node<'_>, + bytes: &[u8], + path: &Path, + lang: Lang, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + sticky: bool, +) { + if let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + prefixes.push(format!("{}.", name.trim())); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); + prefixes.pop(); + } else { + recurse(node, bytes, path, lang, prefixes, errors, regions, sticky); + } +} + +/// A TS `namespace`/`internal_module`/`module` is a `.`-prefix container only +/// when its name is a structurally readable identifier or nested-identifier +/// (e.g. `A.B`). String/computed/unreadable module names are sticky barriers. +fn walk_module_container( + node: Node<'_>, + bytes: &[u8], + path: &Path, + lang: Lang, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + sticky: bool, +) { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + if sticky { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); + return; + } + let Some(name_node) = node.child_by_field_name("name") else { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); + return; + }; + let readable = matches!(name_node.kind(), "identifier" | "nested_identifier") + && !name_node + .utf8_text(bytes) + .map_or(true, |t| t.trim().is_empty()); + if readable { + let name = name_node.utf8_text(bytes).unwrap().trim().to_string(); + prefixes.push(format!("{name}.")); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); + prefixes.pop(); + } else { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); + } +} + +/// Whether a class-body member's enclosing class has a structural name. +/// `node` is a `method_definition`, `field_definition`, or +/// `public_field_definition` whose parent is a `class_body`; walk up to the +/// `class_declaration`/`abstract_class_declaration`/`class` and check its name. +fn in_named_class(node: Node<'_>) -> bool { + let Some(body) = node.parent() else { + return false; + }; + if body.kind() != "class_body" { + return false; + } + let Some(class) = body.parent() else { + return false; + }; + class.child_by_field_name("name").is_some() +} + +/// The class-field name node for a JS `field_definition` or TS +/// `public_field_definition` (the two grammars store it under different +/// field names: JS `property`, TS `name`). Returns `None` for other kinds. +fn field_name_node(parent: Node<'_>) -> Option> { + match parent.kind() { + "field_definition" => parent.child_by_field_name("property"), + "public_field_definition" => parent.child_by_field_name("name"), + _ => None, + } +} + +/// Whether `node` is the direct `value` of a `variable_declarator` whose `name` +/// is a simple `identifier` (not a destructuring/pattern). Returns the binding +/// name. +fn variable_binding_name(node: Node<'_>, bytes: &[u8]) -> Option { + let parent = node.parent()?; + if parent.kind() != "variable_declarator" { + return None; + } + if parent.child_by_field_name("value")?.id() != node.id() { + return None; + } + let name = parent.child_by_field_name("name")?; + if name.kind() != "identifier" { + return None; + } + name.utf8_text(bytes).ok().map(|s| s.trim().to_string()) +} + +/// Whether `node` is the direct `value` of a class field (`field_definition` in +/// JS, `public_field_definition` in TS) inside a structurally named class whose +/// field name is a simple/private identifier. Returns the field name (the +/// class prefix is already on the stack). +fn field_binding_name(node: Node<'_>, bytes: &[u8]) -> Option { + let parent = node.parent()?; + if !matches!( + parent.kind(), + "field_definition" | "public_field_definition" + ) { + return None; + } + if parent.child_by_field_name("value")?.id() != node.id() { + return None; + } + if !in_named_class(parent) { + return None; + } + let field = field_name_node(parent)?; + if !matches!( + field.kind(), + "property_identifier" | "private_property_identifier" + ) { + return None; + } + field.utf8_text(bytes).ok().map(|s| s.trim().to_string()) +} + +/// Whether `node` is the direct `value` of a class field (`field_definition` in +/// JS, `public_field_definition` in TS) whose field name is NOT a simple/private +/// identifier (computed/unreadable). Such a direct class-field callable is an +/// unsupported naming context: it is a barrier and its descendants must be +/// sticky barriers rather than leak a partial name. +fn unsupported_field_direct_context(node: Node<'_>) -> bool { + let Some(parent) = node.parent() else { + return false; + }; + if !matches!( + parent.kind(), + "field_definition" | "public_field_definition" + ) { + return false; + } + let Some(value) = parent.child_by_field_name("value") else { + return false; + }; + if value.id() != node.id() { + return false; + } + let Some(field) = field_name_node(parent) else { + return false; + }; + !matches!( + field.kind(), + "property_identifier" | "private_property_identifier" + ) +} + +/// Whether `node` is the direct `value` of a `variable_declarator` whose name +/// is a destructuring/pattern (not a simple `identifier`). Such a direct +/// callable value is an unsupported binding context: it is a barrier and its +/// descendants must be sticky barriers. +fn unsupported_declarator_direct_context(node: Node<'_>) -> bool { + let Some(parent) = node.parent() else { + return false; + }; + if parent.kind() != "variable_declarator" { + return false; + } + let Some(value) = parent.child_by_field_name("value") else { + return false; + }; + if value.id() != node.id() { + return false; + } + let Some(name) = parent.child_by_field_name("name") else { + return false; + }; + name.kind() != "identifier" +} + +/// A simple/private member name for a `method_definition`. Computed, string, +/// and number names return `None` (they barrier). +fn simple_member_name(node: Node<'_>, bytes: &[u8]) -> Option { + let name = node.child_by_field_name("name")?; + if !matches!( + name.kind(), + "property_identifier" | "private_property_identifier" + ) { + return None; + } + name.utf8_text(bytes).ok().map(|s| s.trim().to_string()) +} + +/// Concatenate the `.`-suffixed prefix stack with `name` to form the qualified +/// display name. +fn join_prefixes(prefixes: &[String], name: &str) -> String { + if prefixes.is_empty() { + name.to_string() + } else { + let mut joined = prefixes.concat(); + joined.push_str(name); + joined + } +} + +/// Emit a `Named` region for `node`, degrading to a barrier if its byte span +/// overlaps a local error range. `name` is the simple name; `qualified` is the +/// full `.`-qualified display name; `lang` is the actual source language. +fn emit_named( + node: Node<'_>, + path: &Path, + lang: Lang, + name: &str, + qualified: &str, + errors: &[ErrorRange], + regions: &mut Vec, +) { + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: name.to_string(), + receiver_var: None, + receiver_type: None, + package_dir: std::path::PathBuf::from("."), + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + language: lang, + display_name: qualified.to_string(), + }; + let region = OwnerRegion::Named(anchor); + let region = degrade_named_on_error(region, errors, node.start_byte(), node.end_byte()); + regions.push(region); +} + +#[allow(clippy::too_many_arguments)] +fn recurse( + node: Node<'_>, + bytes: &[u8], + path: &Path, + lang: Lang, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + sticky: bool, +) { + let mut cursor = node.walk(); + for child in node.named_children(&mut cursor) { + walk(child, bytes, path, lang, prefixes, errors, regions, sticky); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + use std::path::PathBuf; + + fn path() -> PathBuf { + PathBuf::from("tests/fixtures/x.ts") + } + + fn parse(lang: Lang, src: &str) -> (Vec, Vec) { + regions_for(lang, &path(), src).expect("should parse") + } + + fn assert_owner_exact( + regions: &[OwnerRegion], + errors: &[ErrorRange], + hit_line: u32, + name: &str, + start: u32, + end: u32, + ) { + let owner = owner_for(regions, errors, hit_line) + .unwrap_or_else(|| panic!("line {hit_line} should attribute to {name}")); + assert_eq!(owner.qualified_name(), name, "line {hit_line} display name"); + assert_eq!(owner.start_line, start, "line {hit_line} start line"); + assert_eq!(owner.end_line, end, "line {hit_line} end line"); + } + + fn assert_abstain(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32) { + assert!( + owner_for(regions, errors, line).is_none(), + "line {line} should abstain" + ); + } + + /// Number of `AnonymousBarrier` regions whose span covers `line`. + fn barrier_regions_at(regions: &[OwnerRegion], line: u32) -> usize { + regions + .iter() + .filter(|r| { + matches!( + r, + OwnerRegion::AnonymousBarrier { start_line, end_line } + if *start_line <= line && line <= *end_line + ) + }) + .count() + } + /// Number of `AnonymousBarrier` regions that occupy exactly the one-line + /// span `(line, line)`. Exact match: an oversized barrier that merely + /// covers `line` does NOT count. + fn exact_one_line_barriers_at(regions: &[OwnerRegion], line: u32) -> usize { + regions + .iter() + .filter(|r| { + matches!( + r, + OwnerRegion::AnonymousBarrier { start_line, end_line } + if *start_line == line && *end_line == line + ) + }) + .count() + } + + /// Total number of `AnonymousBarrier` regions anywhere. + fn total_barrier_regions(regions: &[OwnerRegion]) -> usize { + regions + .iter() + .filter(|r| matches!(r, OwnerRegion::AnonymousBarrier { .. })) + .count() + } + + /// Number of `Named` regions whose span covers `line`. + fn named_regions_at(regions: &[OwnerRegion], line: u32) -> usize { + regions + .iter() + .filter(|r| { + matches!( + r, + OwnerRegion::Named(a) if a.start_line <= line && line <= a.end_line + ) + }) + .count() + } + + #[test] + fn js_manifest_gate_verifies_kinds_exist_and_fingerprint_is_pinned() { + let kinds = node_types(tree_sitter_javascript::NODE_TYPES); + let mut all: Vec<&str> = Vec::new(); + all.extend(JS_EXECUTABLE_CALLABLES); + all.extend(JS_BINDING_CONTAINER_KINDS); + all.extend(JS_NON_CALLABLE_SAFETY_BARRIERS); + assert_kinds_exist(&kinds, &all); + assert_disjoint(&all); + assert_eq!( + fnv1a(tree_sitter_javascript::NODE_TYPES.as_bytes()), + JS_NODE_TYPES_FINGERPRINT, + "tree_sitter_javascript NODE_TYPES changed; re-pin fingerprint and re-verify the matrix" + ); + } + + #[test] + fn ts_manifest_gate_verifies_typescript_kinds_and_fingerprint() { + let kinds = node_types(tree_sitter_typescript::TYPESCRIPT_NODE_TYPES); + let mut all: Vec<&str> = Vec::new(); + all.extend(TS_EXECUTABLE_CALLABLES); + all.extend(TS_BODY_LESS_SIGNATURES); + all.extend(TS_BINDING_CONTAINER_KINDS); + all.extend(TS_TYPE_ONLY_TRANSPARENT); + all.extend(TS_NON_CALLABLE_SAFETY_BARRIERS); + assert_kinds_exist(&kinds, &all); + assert_disjoint(&all); + assert_eq!( + fnv1a(tree_sitter_typescript::TYPESCRIPT_NODE_TYPES.as_bytes()), + TYPESCRIPT_NODE_TYPES_FINGERPRINT, + "typescript NODE_TYPES changed; re-pin fingerprint and re-verify the matrix" + ); + } + + #[test] + fn tsx_manifest_gate_verifies_tsx_kinds_and_fingerprint() { + let kinds = node_types(tree_sitter_typescript::TSX_NODE_TYPES); + // TSX reuses ALL reusable TS inventories (callables, body-less + // signatures, binding/container kinds, type-only transparent, safety + // barriers) and adds its own JSX routing/wrapper sentinels. + let mut all: Vec<&str> = Vec::new(); + all.extend(TS_EXECUTABLE_CALLABLES); + all.extend(TS_BODY_LESS_SIGNATURES); + all.extend(TS_BINDING_CONTAINER_KINDS); + all.extend(TS_TYPE_ONLY_TRANSPARENT); + all.extend(TS_NON_CALLABLE_SAFETY_BARRIERS); + assert_kinds_exist(&kinds, &all); + assert_disjoint(&all); + // JSX routing/wrapper sentinels (not a callable inventory) also exist. + for k in TSX_ROUTING_WRAPPER_KINDS { + assert!(kinds.contains(*k), "tsx kind {k} missing from NODE_TYPES"); + } + // The JSX sentinels must not collide with any reusable TS category. + let mut with_jsx: Vec<&str> = all.clone(); + with_jsx.extend(TSX_ROUTING_WRAPPER_KINDS); + assert_disjoint(&with_jsx); + assert_eq!( + fnv1a(tree_sitter_typescript::TSX_NODE_TYPES.as_bytes()), + TSX_NODE_TYPES_FINGERPRINT, + "tsx NODE_TYPES changed; re-pin fingerprint and re-verify the matrix" + ); + } + + fn node_types(json: &str) -> HashSet { + let v: serde_json::Value = serde_json::from_str(json).unwrap(); + v.as_array() + .unwrap() + .iter() + .filter_map(|e| e.get("type").and_then(|t| t.as_str()).map(String::from)) + .collect() + } + + fn assert_kinds_exist(kinds: &HashSet, all: &[&str]) { + assert!(!kinds.is_empty()); + for k in all { + assert!( + kinds.contains(*k), + "manifest kind {k} missing from NODE_TYPES" + ); + } + } + + fn assert_disjoint(all: &[&str]) { + let uniq: HashSet<&str> = all.iter().copied().collect(); + assert_eq!( + uniq.len(), + all.len(), + "manifest inventories must be disjoint" + ); + } + + #[test] + fn all_six_js_executable_callable_kinds_are_disposed() { + let (r, e) = parse( + Lang::JavaScript, + "function fdecl() {}\n\ + function* gdecl() { yield 1; }\n\ + const fexpr = function() {};\n\ + const gexpr = function* () { yield 1; };\n\ + const arrow = () => {};\n\ + class A { method() {} }\n", + ); + assert_owner_exact(&r, &e, 1, "fdecl", 1, 1); // function_declaration + assert_owner_exact(&r, &e, 2, "gdecl", 2, 2); // generator_function_declaration + assert_owner_exact(&r, &e, 3, "fexpr", 3, 3); // function_expression + assert_owner_exact(&r, &e, 4, "gexpr", 4, 4); // generator_function + assert_owner_exact(&r, &e, 5, "arrow", 5, 5); // arrow_function + assert_owner_exact(&r, &e, 6, "A.method", 6, 6); // method_definition + } + + #[test] + fn all_ts_callable_and_signature_kinds_are_disposed() { + // Every TS executable callable kind is Named; every body-less signature + // kind is a barrier over its exact span. + let (r, e) = parse( + Lang::TypeScript, + "function fdecl() {}\n\ + function* gdecl() { yield 1; }\n\ + const fexpr = function() {};\n\ + const gexpr = function* () { yield 1; };\n\ + const arrow = () => {};\n\ + abstract class A {\n\ + method() {}\n\ + abstract abs(): void;\n\ + sig(): void;\n\ + }\n\ + declare function amb(): void;\n\ + interface I {\n\ + run(): void;\n\ + new (): I;\n\ + (): void;\n\ + }\n", + ); + assert_owner_exact(&r, &e, 1, "fdecl", 1, 1); // function_declaration + assert_owner_exact(&r, &e, 2, "gdecl", 2, 2); // generator_function_declaration + assert_owner_exact(&r, &e, 3, "fexpr", 3, 3); // function_expression + assert_owner_exact(&r, &e, 4, "gexpr", 4, 4); // generator_function + assert_owner_exact(&r, &e, 5, "arrow", 5, 5); // arrow_function + assert_owner_exact(&r, &e, 7, "A.method", 7, 7); // method_definition (Named) + // Body-less signature kinds must emit EXACTLY ONE AnonymousBarrier over + // their exact one-line span and never a Named region (the "exactly one + // region classification" contract; a silent omission or an oversized + // enclosing barrier would not pass). + for (line, kind) in [ + (8, "abstract_method_signature"), + (9, "method_signature"), + (11, "function_signature"), + (13, "method_signature"), + (14, "construct_signature"), + (15, "call_signature"), + ] { + assert_eq!( + exact_one_line_barriers_at(&r, line), + 1, + "{kind} at line {line} must emit exactly one exact (line,line) barrier" + ); + assert_eq!( + named_regions_at(&r, line), + 0, + "{kind} at line {line} must not emit a Named region" + ); + assert_abstain(&r, &e, line); + } + // The whole fixture has exactly six one-line signature barriers and no + // other barrier, so no oversized/extra barrier can hide the omission. + assert_eq!( + total_barrier_regions(&r), + 6, + "this valid fixture must classify exactly the six body-less signatures as barriers" + ); + } + #[test] + fn ts_type_only_kinds_add_zero_regions_and_stay_transparent() { + // property_signature, index_signature, function_type, and + // constructor_type are transparent: they add neither a Named nor a + // Barrier region and never shadow an enclosing owner. They appear + // inside a valid outer callable (`load`) and inside an interface + // (traversal-only) so both transparency directions are proven. + let (r, e) = parse( + Lang::TypeScript, + "interface Config {\n url: string;\n [key: string]: number;\n}\nfunction load(cfg: { url: string; [key: string]: number }, cb: (x: number) => string, ctor: new () => number) {\n return null;\n}\n", + ); + // Exactly one Named region (load) and zero barriers: the type-only + // kinds added no classifications anywhere. + assert_eq!(r.len(), 1, "type-only kinds must add exactly zero regions"); + assert_eq!(named_regions_at(&r, 5), 1); + assert_eq!(barrier_regions_at(&r, 5), 0); + // Hit lines inside `load` resolve to load; the type-only kinds on line + // 5 do not shadow it with a barrier. + assert_owner_exact(&r, &e, 5, "load", 5, 7); + assert_owner_exact(&r, &e, 6, "load", 5, 7); + assert_owner_exact(&r, &e, 7, "load", 5, 7); + // Inside the interface (traversal-only, no owner) the type-only kinds + // are transparent: their lines abstain rather than emit a bogus + // owner/barrier. + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + } + + #[test] + fn family_quality_matrix() { + struct Case { + lang: Lang, + src: &'static str, + owners: &'static [(u32, &'static str, u32, u32)], + abstain: &'static [u32], + } + let cases: &[Case] = &[ + // ---- JavaScript positive cases ---- + Case { + lang: Lang::JavaScript, + src: "function alpha() {\n return 1;\n}\n", + owners: &[(1, "alpha", 1, 3), (2, "alpha", 1, 3)], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "function* gen() {\n yield 1;\n}\n", + owners: &[(1, "gen", 1, 3), (2, "gen", 1, 3)], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "function outer() {\n function inner() {\n let x = 1;\n }\n}\n", + owners: &[ + (1, "outer", 1, 5), + (2, "outer.inner", 2, 4), + (3, "outer.inner", 2, 4), + (4, "outer.inner", 2, 4), + ], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "class A {\n foo() {\n return 1;\n }\n static bar() {}\n}\n", + owners: &[ + (2, "A.foo", 2, 4), + (3, "A.foo", 2, 4), + (4, "A.foo", 2, 4), + (5, "A.bar", 5, 5), + ], + abstain: &[1], + }, + Case { + lang: Lang::JavaScript, + src: "class A {\n get x() { return 1; }\n set x(v) { this._x = v; }\n}\n", + owners: &[(2, "A.x", 2, 2), (3, "A.x", 3, 3)], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "class A {\n #priv() {\n return 1;\n }\n}\n", + owners: &[ + (2, "A.#priv", 2, 4), + (3, "A.#priv", 2, 4), + (4, "A.#priv", 2, 4), + ], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "const f = () => {\n return 1;\n};\n", + owners: &[(1, "f", 1, 3), (2, "f", 1, 3)], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "const g = function() {\n return 2;\n};\n", + owners: &[(1, "g", 1, 3), (2, "g", 1, 3)], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "const h = function* () {\n yield 1;\n};\n", + owners: &[(1, "h", 1, 3), (2, "h", 1, 3)], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "const f = function named() {\n return 1;\n};\n", + owners: &[(1, "f", 1, 3), (2, "f", 1, 3)], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "class A {\n x = () => {\n return 1;\n };\n}\n", + owners: &[(2, "A.x", 2, 4), (3, "A.x", 2, 4), (4, "A.x", 2, 4)], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "class A {\n y = function named() {\n return 2;\n };\n}\n", + owners: &[(2, "A.y", 2, 4), (3, "A.y", 2, 4)], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "(function named() {\n return 1;\n})();\n", + owners: &[(1, "named", 1, 3), (2, "named", 1, 3)], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "(function* gen() {\n yield 1;\n})();\n", + owners: &[(1, "gen", 1, 3), (2, "gen", 1, 3)], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "const f = () => {\n function inner() {\n return 1;\n }\n};\n", + owners: &[ + (1, "f", 1, 5), + (2, "f.inner", 2, 4), + (3, "f.inner", 2, 4), + (4, "f.inner", 2, 4), + ], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "(function() {\n function helper() {\n return 1;\n }\n})();\n", + owners: &[(2, "helper", 2, 4), (3, "helper", 2, 4), (4, "helper", 2, 4)], + abstain: &[1], + }, + Case { + lang: Lang::JavaScript, + src: "function outer() {\n const f = () => {\n return 1;\n };\n}\n", + owners: &[ + (1, "outer", 1, 5), + (2, "outer.f", 2, 4), + (3, "outer.f", 2, 4), + (4, "outer.f", 2, 4), + ], + abstain: &[], + }, + Case { + lang: Lang::JavaScript, + src: "const o = {\n bar: function named() {\n return 1;\n },\n};\n", + owners: &[(2, "named", 2, 4), (3, "named", 2, 4)], + abstain: &[], + }, + // ---- JavaScript intentional abstentions ---- + Case { + lang: Lang::JavaScript, + src: "const o = {\n foo() {\n return 1;\n },\n};\n", + owners: &[], + abstain: &[2, 3], + }, + Case { + lang: Lang::JavaScript, + src: "const o = {\n bar: function() {\n return 1;\n },\n};\n", + owners: &[], + abstain: &[2, 3], + }, + Case { + lang: Lang::JavaScript, + src: "const A = class {\n foo() {\n return 1;\n }\n};\n", + owners: &[], + abstain: &[2, 3], + }, + Case { + lang: Lang::JavaScript, + src: "(function() {\n let x = 1;\n})();\n", + owners: &[], + abstain: &[1, 2], + }, + Case { + lang: Lang::JavaScript, + src: "Foo.prototype.bar = function() {\n return 1;\n};\n", + owners: &[], + abstain: &[1, 2], + }, + Case { + lang: Lang::JavaScript, + src: "button.onClick = () => {\n handle();\n};\n", + owners: &[], + abstain: &[1, 2], + }, + Case { + lang: Lang::JavaScript, + src: "class A {\n ['foo']() {\n return 1;\n }\n}\n", + owners: &[], + abstain: &[2, 3], + }, + Case { + lang: Lang::JavaScript, + src: "class A {\n static {\n let x = 1;\n }\n}\n", + owners: &[], + abstain: &[2, 3], + }, + // ---- TypeScript positive cases ---- + Case { + lang: Lang::TypeScript, + src: "namespace A.B {\n export function foo() {}\n export class C {\n bar() {}\n }\n}\n", + owners: &[(2, "A.B.foo", 2, 2), (4, "A.B.C.bar", 4, 4)], + abstain: &[], + }, + Case { + lang: Lang::TypeScript, + src: "abstract class Shape {\n abstract area(): number;\n area() {}\n abstract name(): string;\n describe() {}\n}\n", + owners: &[(3, "Shape.area", 3, 3), (5, "Shape.describe", 5, 5)], + abstain: &[2, 4], + }, + Case { + lang: Lang::TypeScript, + src: "class Fmt {\n format(): string;\n format(x: number): string;\n format(): string { return \"\"; }\n}\n", + owners: &[(4, "Fmt.format", 4, 4)], + abstain: &[2, 3], + }, + Case { + lang: Lang::TypeScript, + src: "function transform(cb: (x: number) => string, ctor: new () => number) {\n return null;\n}\n", + owners: &[(1, "transform", 1, 3), (2, "transform", 1, 3), (3, "transform", 1, 3)], + abstain: &[], + }, + Case { + lang: Lang::TypeScript, + src: "class A {\n x = () => {};\n private y = function() {};\n static z = () => {};\n}\n", + owners: &[(2, "A.x", 2, 2), (3, "A.y", 3, 3), (4, "A.z", 4, 4)], + abstain: &[], + }, + Case { + lang: Lang::TypeScript, + src: "function good() {\n return 1;\n}\n", + owners: &[(1, "good", 1, 3), (2, "good", 1, 3)], + abstain: &[], + }, + // ---- TypeScript intentional abstentions ---- + Case { + lang: Lang::TypeScript, + src: "declare function fetch(): void;\ndeclare class Store {\n get(): string;\n}\n", + owners: &[], + abstain: &[1, 3], + }, + Case { + lang: Lang::TypeScript, + src: "interface I {\n run(): void;\n new (): I;\n (): void;\n}\n", + owners: &[], + abstain: &[2, 3, 4], + }, + Case { + lang: Lang::TypeScript, + src: "class A {\n ['x'] = () => {\n function inner() {}\n };\n}\nconst { a } = function() {\n function inner() {}\n};\n", + owners: &[], + abstain: &[2, 3, 6, 7], + }, + Case { + lang: Lang::TypeScript, + src: "function bad() {\n const x: number = ;\n return 1;\n}\nfunction good() {\n return 1;\n}\n", + owners: &[(5, "good", 5, 7), (6, "good", 5, 7)], + abstain: &[1, 2, 3, 4], + }, + ]; + + let mut positives = 0usize; + let mut abstentions = 0usize; + for c in cases { + let (r, e) = parse(c.lang, c.src); + for &(line, name, start, end) in c.owners { + assert_owner_exact(&r, &e, line, name, start, end); + positives += 1; + } + for &line in c.abstain { + assert_abstain(&r, &e, line); + abstentions += 1; + } + } + // Combined JS+TS family gate (substantial, not padded). + assert!( + positives >= 60, + "need >=60 combined positive owner checks, got {positives}" + ); + assert!( + abstentions >= 20, + "need >=20 combined intentional abstention lines, got {abstentions}" + ); + } + + #[test] + fn ts_invalid_naming_contexts_are_sticky_for_nested_declarations() { + // Computed class method: recurse sticky so a nested fn cannot leak as + // `A.inner`. + let (r, e) = parse( + Lang::TypeScript, + "abstract class A {\n ['foo'](): void {\n function inner() {}\n }\n}\n", + ); + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + assert_abstain(&r, &e, 4); + + // Computed public field: sticky. + let (r, e) = parse( + Lang::TypeScript, + "class A {\n ['x'] = () => {\n function inner() {}\n };\n}\n", + ); + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + assert_abstain(&r, &e, 4); + + // Destructuring declarator: sticky. + let (r, e) = parse( + Lang::TypeScript, + "const { a } = function() {\n function inner() {}\n};\n", + ); + assert_abstain(&r, &e, 1); + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + } + + #[test] + fn ts_string_module_name_is_sticky_barrier() { + // A string-named ambient module cannot be a readable prefix: descendants + // are sticky barriers, and a nested named declaration does not leak. + let (r, e) = parse( + Lang::TypeScript, + "declare module \"x\" {\n export function inner() {}\n}\n", + ); + assert_abstain(&r, &e, 1); + assert_abstain(&r, &e, 2); + } + + #[test] + fn ts_module_prefix_joins_with_dots() { + let (r, e) = parse( + Lang::TypeScript, + "namespace A {\n export namespace B {\n export function foo() {}\n }\n}\n", + ); + assert_owner_exact(&r, &e, 3, "A.B.foo", 3, 3); + } + + #[test] + fn tsx_jsx_callback_keeps_nested_declarations_eligible() { + // TSX routes through the TSX grammar; an inline JSX arrow callback is an + // ordinary non-sticky barrier, so a named declaration inside stays + // eligible, and the component itself is a Named owner. + let (r, e) = parse( + Lang::Tsx, + "function App() {\n return
{ inner(); }}>x
;\n}\nfunction inner() {\n return 1;\n}\n", + ); + assert_owner_exact(&r, &e, 1, "App", 1, 3); + assert_owner_exact(&r, &e, 4, "inner", 4, 6); + assert_owner_exact(&r, &e, 5, "inner", 4, 6); + } + + #[test] + fn invalid_naming_contexts_are_sticky_for_nested_declarations_js() { + let (r, e) = parse( + Lang::JavaScript, + "class A {\n ['foo']() {\n function inner() { return 1; }\n }\n}\n", + ); + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + assert_abstain(&r, &e, 4); + + let (r, e) = parse( + Lang::JavaScript, + "class A {\n ['x'] = () => {\n function inner() { return 1; }\n };\n}\n", + ); + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + assert_abstain(&r, &e, 4); + + let (r, e) = parse( + Lang::JavaScript, + "const { a } = function() {\n function inner() { return 1; }\n};\n", + ); + assert_abstain(&r, &e, 1); + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + } + + #[test] + fn ordinary_anonymous_callback_keeps_nested_declarations_eligible() { + let (r, e) = parse( + Lang::JavaScript, + "const xs = [1].map(() => {\n function inner() { return 1; }\n return inner();\n});\n", + ); + assert_owner_exact(&r, &e, 2, "inner", 2, 2); + assert_abstain(&r, &e, 3); + } + + #[test] + fn object_get_set_are_barriers_but_named_container_allows_binding() { + let (r, e) = parse( + Lang::JavaScript, + "const o = {\n get x() { return 1; }\n};\n", + ); + assert_abstain(&r, &e, 2); + } + + #[test] + fn malformed_callable_full_region_barrier_but_clean_adjacent_eligible() { + let (r, e) = parse( + Lang::JavaScript, + "function bad() {\n const x = ;\n return 1;\n}\nfunction good() {\n return 1;\n}\n", + ); + assert_abstain(&r, &e, 1); + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + assert_owner_exact(&r, &e, 5, "good", 5, 7); + assert_owner_exact(&r, &e, 6, "good", 5, 7); + } + + #[test] + fn owner_anchor_qualified_name_uses_display_name() { + let a = OwnerAnchor { + path: path(), + name: "inner".into(), + receiver_var: None, + receiver_type: None, + package_dir: PathBuf::from("pkg"), + start_line: 1, + end_line: 1, + language: crate::types::Lang::TypeScript, + display_name: "outer.inner".into(), + }; + assert_eq!(a.qualified_name(), "outer.inner"); + } +} diff --git a/src/evidence/owners/kotlin.rs b/src/evidence/owners/kotlin.rs new file mode 100644 index 0000000..31349b5 --- /dev/null +++ b/src/evidence/owners/kotlin.rs @@ -0,0 +1,886 @@ +//! Kotlin owner-region extraction (US-068 Wave 2A). +//! +//! Supported named owners: body-bearing `function_declaration` (its declared +//! name), class/interface/named-object/nested type containers appended with `.` +//! (`Outer.Inner.load`), a companion object as an explicit lexical container +//! (its declared name or the stable language name `Companion`), extension +//! functions prefixed by the structurally spelled receiver type +//! (`String.slug`, `Helpers.String.slug`), body-bearing secondary constructors +//! (the enclosing declared type name), property accessors +//! (`Container.property.get`/`.set`), and supported local named functions +//! appended to the complete lexical callable path (`outer.inner`). +//! +//! Abstentions/barriers: every `lambda_literal`, `annotated_lambda`, and +//! `anonymous_function` is an `AnonymousBarrier`; every `anonymous_initializer` +//! (`init {}`) and `object_literal` is an identity barrier; a function or +//! constructor without a body is not a named owner; a primary constructor +//! without a body-bearing callable range abstains; `.kts` wrappers are never +//! synthesized. + +use std::path::Path; + +use tree_sitter::Node; + +use crate::evidence::owner_links::OwnerAnchor; +use crate::evidence::owners::{ + attribute_line, collect_error_ranges, degrade_named_on_error, ErrorRange, OwnerRegion, +}; +use crate::lang::outline::outline_language; +use crate::types::Lang; + +/// Version-pinned Kotlin callable manifest (anti-drift contract), holding the +/// pinned tree-sitter-kotlin-ng 1.1.0 callable kinds. +#[cfg(test)] +const KOTLIN_EXECUTABLE_CALLABLES: &[&str] = &[ + "function_declaration", + "secondary_constructor", + "property_declaration", + "getter", + "setter", + "lambda_literal", + "annotated_lambda", + "anonymous_function", +]; +#[cfg(test)] +const KOTLIN_CONTAINER_KINDS: &[&str] = &[ + "class_declaration", + "object_declaration", + "companion_object", + "class_body", +]; +#[cfg(test)] +const KOTLIN_BODILESS_OR_BARRIER_KINDS: &[&str] = &[ + "primary_constructor", + "anonymous_initializer", + "object_literal", +]; + +/// FNV-1a-64 fingerprint of the bundled `tree-sitter-kotlin-ng` `NODE_TYPES` +/// JSON (tree-sitter-kotlin-ng 1.1.0). Pinned so any grammar metadata change +/// fails the manifest gate and forces a re-audit. +#[cfg(test)] +const KOTLIN_NODE_TYPES_FINGERPRINT: u64 = 0xf23c_3a3e_303d_b7e; + +/// Stable FNV-1a 64-bit hash, dependency-free and reproducible across builds. +#[cfg(test)] +fn fnv1a(bytes: &[u8]) -> u64 { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for &b in bytes { + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x100_0000_01b3); + } + hash +} + +/// Collapse runs of ASCII whitespace to one space and trim, per the extension +/// receiver spelling rule. Preserves the source spelling otherwise. +fn collapse_whitespace(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut in_space = false; + for c in s.chars() { + if c.is_whitespace() { + if !in_space { + out.push(' '); + in_space = true; + } + } else { + out.push(c); + in_space = false; + } + } + out.trim().to_string() +} + +/// Parse a Kotlin file and produce its owner regions and local error ranges. +/// Returns `None` when the file cannot be read, has no tree, or its root node +/// itself is an `ERROR` (preserve raw hits, emit no owner evidence). +pub(crate) fn kotlin_regions( + path: &Path, + content: &str, +) -> Option<(Vec, Vec)> { + let language = outline_language(Lang::Kotlin)?; + let mut parser = tree_sitter::Parser::new(); + if parser.set_language(&language).is_err() { + return None; + } + let tree = parser.parse(content, None)?; + if tree.root_node().kind() == "ERROR" { + return None; + } + let bytes = content.as_bytes(); + let errors = collect_error_ranges(&tree, bytes); + let mut regions = Vec::new(); + let mut containers: Vec = Vec::new(); + walk( + tree.root_node(), + bytes, + path, + false, + &mut containers, + &errors, + &mut regions, + ); + Some((regions, errors)) +} + +/// Emit a full-range `AnonymousBarrier` for a node and descend `in_anonymous`. +fn barrier_and_descend( + node: Node<'_>, + bytes: &[u8], + path: &Path, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + walk_children(node, bytes, path, true, containers, errors, regions); +} + +/// Walk a Kotlin tree, emitting `Named` regions for body-bearing callables and +/// `AnonymousBarrier` regions for lambdas, anonymous initializers, and object +/// literals. `in_anonymous` is true when inside such an identity barrier. +fn walk( + node: Node<'_>, + bytes: &[u8], + path: &Path, + in_anonymous: bool, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + // Anonymous identity barriers (no structural name). + if matches!( + node.kind(), + "lambda_literal" | "annotated_lambda" | "anonymous_function" + ) { + barrier_and_descend(node, bytes, path, containers, errors, regions); + return; + } + if matches!(node.kind(), "anonymous_initializer" | "object_literal") { + barrier_and_descend(node, bytes, path, containers, errors, regions); + return; + } + // A primary constructor carries no body-bearing callable range; descend + // without emitting an owner (never a container). + if node.kind() == "primary_constructor" { + walk_children(node, bytes, path, in_anonymous, containers, errors, regions); + return; + } + + match node.kind() { + "function_declaration" => { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + let has_body = node + .named_children(&mut node.walk()) + .any(|c| c.kind() == "function_body"); + if in_anonymous { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + walk_children(node, bytes, path, true, containers, errors, regions); + } else if has_body { + if let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + let name = name.to_string(); + // Extension receiver: the named child immediately before the + // name field, spelled structurally (e.g. `String`). + let receiver = receiver_of(node, bytes); + let segment = match &receiver { + Some(r) => format!("{r}.{name}"), + None => name.clone(), + }; + let qualified = join_containers(containers, &segment); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: name.clone(), + receiver_var: None, + receiver_type: None, + package_dir: std::path::PathBuf::from("."), + start_line, + end_line, + language: Lang::Kotlin, + display_name: qualified, + }; + let region = OwnerRegion::Named(anchor); + let region = + degrade_named_on_error(region, errors, node.start_byte(), node.end_byte()); + regions.push(region); + // Push the display segment so nested local functions append + // to the complete lexical callable path (`outer.inner`). + containers.push(segment); + walk_children(node, bytes, path, false, containers, errors, regions); + containers.pop(); + } else { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + walk_children(node, bytes, path, true, containers, errors, regions); + } + } else { + // Body-less function (interface/abstract): not an owner. + walk_children(node, bytes, path, in_anonymous, containers, errors, regions); + } + } + "secondary_constructor" => { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + let has_body = node + .named_children(&mut node.walk()) + .any(|c| c.kind() == "block"); + if in_anonymous { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + walk_children(node, bytes, path, true, containers, errors, regions); + } else if has_body { + // Uses the enclosing declared type name. + if let Some(type_name) = containers.last() { + let type_name = type_name.clone(); + let qualified = join_containers(containers, &type_name); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: type_name.clone(), + receiver_var: None, + receiver_type: None, + package_dir: std::path::PathBuf::from("."), + start_line, + end_line, + language: Lang::Kotlin, + display_name: qualified, + }; + let region = OwnerRegion::Named(anchor); + let region = + degrade_named_on_error(region, errors, node.start_byte(), node.end_byte()); + regions.push(region); + } + walk_children(node, bytes, path, false, containers, errors, regions); + } else { + walk_children(node, bytes, path, in_anonymous, containers, errors, regions); + } + } + "property_declaration" => { + // Extract the property name from the variable_declaration child, + // then emit getter/setter owners with their accessor kind. + let prop_name = node + .named_children(&mut node.walk()) + .find(|c| c.kind() == "variable_declaration") + .and_then(|v| v.named_children(&mut v.walk()).next()) + .and_then(|id| id.utf8_text(bytes).ok()) + .map(String::from); + let mut cur = node.walk(); + for child in node.named_children(&mut cur) { + if matches!(child.kind(), "getter" | "setter") { + let start_line = child.start_position().row as u32 + 1; + let end_line = child.end_position().row as u32 + 1; + let has_body = child + .named_children(&mut child.walk()) + .any(|c| c.kind() == "function_body"); + // Grammar kind is `getter`/`setter`; display uses `get`/`set`. + let kind = if child.kind() == "setter" { + "set" + } else { + "get" + }; + if in_anonymous { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + } else if has_body { + if let Some(prop) = &prop_name { + let segment = format!("{prop}.{kind}"); + let qualified = join_containers(containers, &segment); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: segment.clone(), + receiver_var: None, + receiver_type: None, + package_dir: std::path::PathBuf::from("."), + start_line, + end_line, + language: Lang::Kotlin, + display_name: qualified, + }; + let region = OwnerRegion::Named(anchor); + let region = degrade_named_on_error( + region, + errors, + child.start_byte(), + child.end_byte(), + ); + regions.push(region); + } + } + } else { + walk( + child, + bytes, + path, + in_anonymous, + containers, + errors, + regions, + ); + } + } + } + "class_declaration" | "object_declaration" | "companion_object" => { + if in_anonymous { + walk_children(node, bytes, path, true, containers, errors, regions); + } else { + let name = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + .map(String::from) + // A companion object without a declared name uses the stable + // language name `Companion`. + .or_else(|| { + (node.kind() == "companion_object").then(|| "Companion".to_string()) + }); + if let Some(name) = name { + containers.push(name); + walk_children(node, bytes, path, false, containers, errors, regions); + containers.pop(); + } else { + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + walk_children(node, bytes, path, true, containers, errors, regions); + } + } + } + _ => walk_children(node, bytes, path, in_anonymous, containers, errors, regions), + } +} + +/// The structurally spelled receiver type of an extension function, if any: the +/// type node immediately preceding the name field. Non-type nodes (for example +/// `type_parameters`) are not receivers, so the child must be a type kind. +fn receiver_of(node: Node<'_>, bytes: &[u8]) -> Option { + let name = node.child_by_field_name("name")?; + let mut cur = node.walk(); + let kids: Vec = node.named_children(&mut cur).collect(); + for (i, k) in kids.iter().enumerate() { + if k.id() == name.id() && i > 0 { + let prev = &kids[i - 1]; + if !matches!( + prev.kind(), + "user_type" + | "nullable_type" + | "parenthesized_type" + | "function_type" + | "dynamic_type" + ) { + return None; + } + let text = prev.utf8_text(bytes).ok()?; + return Some(collapse_whitespace(text)); + } + } + None +} + +fn walk_children( + node: Node<'_>, + bytes: &[u8], + path: &Path, + in_anonymous: bool, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + let mut cursor = node.walk(); + for child in node.named_children(&mut cursor) { + walk( + child, + bytes, + path, + in_anonymous, + containers, + errors, + regions, + ); + } +} + +fn join_containers(containers: &[String], name: &str) -> String { + if containers.is_empty() { + name.to_string() + } else { + let mut joined = containers.join("."); + joined.push('.'); + joined.push_str(name); + joined + } +} + +/// Attribute a Kotlin hit line to a named owner, honoring local errors. +pub(crate) fn kotlin_owner_for<'a>( + regions: &'a [OwnerRegion], + errors: &[ErrorRange], + line: u32, +) -> Option<&'a OwnerAnchor> { + attribute_line(regions, errors, line) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + use std::path::PathBuf; + + fn path() -> PathBuf { + PathBuf::from("tests/fixtures/x.kt") + } + + fn parse(src: &str) -> (Vec, Vec) { + kotlin_regions(&path(), src).expect("should parse") + } + + fn assert_owner(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32, name: &str) { + let owner = kotlin_owner_for(regions, errors, line); + assert_eq!( + owner.map(OwnerAnchor::qualified_name), + Some(name.to_string()), + "line {line} should attribute to {name}" + ); + } + + fn assert_abstain(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32) { + assert!( + kotlin_owner_for(regions, errors, line).is_none(), + "line {line} should abstain" + ); + } + + #[test] + fn top_level_function_and_class_method() { + let (r, e) = parse( + "fun topLevel() {\n val x = 1\n}\nclass Service {\n fun load() {\n }\n}\n", + ); + assert_owner(&r, &e, 1, "topLevel"); + assert_owner(&r, &e, 5, "Service.load"); + } + + #[test] + fn nested_types_and_named_object() { + let (r, e) = parse("class Outer {\n class Inner {\n fun handle() {\n }\n }\n object Named {\n fun go() {\n }\n }\n}\n"); + assert_owner(&r, &e, 3, "Outer.Inner.handle"); + assert_owner(&r, &e, 7, "Outer.Named.go"); + } + + #[test] + fn companion_object_default_and_named() { + let (r, e) = parse("class Service {\n companion object {\n fun factory() {\n }\n }\n companion object Factory {\n fun make() {\n }\n }\n}\n"); + assert_owner(&r, &e, 3, "Service.Companion.factory"); + assert_owner(&r, &e, 7, "Service.Factory.make"); + } + + #[test] + fn extension_function_receiver_prefix() { + let (r, e) = parse("fun String.slug() {\n return 1\n}\n"); + assert_owner(&r, &e, 1, "String.slug"); + assert_owner(&r, &e, 2, "String.slug"); + } + + #[test] + fn extension_function_with_lexical_container() { + let (r, e) = + parse("class Helpers {\n fun String.slug() {\n return 1\n }\n}\n"); + assert_owner(&r, &e, 2, "Helpers.String.slug"); + } + + #[test] + fn secondary_constructor_uses_declared_type_name() { + let (r, e) = + parse("class WithCtor(val x: Int) {\n constructor(s: String) {\n }\n}\n"); + assert_owner(&r, &e, 2, "WithCtor.WithCtor"); + } + + #[test] + fn property_accessors_get_set() { + let (r, e) = parse("class Registry {\n var prop: Int = 0\n get() =\n 1\n set(value) {\n }\n}\n"); + assert_owner(&r, &e, 3, "Registry.prop.get"); + assert_owner(&r, &e, 5, "Registry.prop.set"); + } + + #[test] + fn local_function_appends_to_callable_path() { + let (r, e) = parse("fun outer() {\n fun inner() {\n }\n}\n"); + assert_owner(&r, &e, 1, "outer"); + assert_owner(&r, &e, 2, "outer.inner"); + } + + #[test] + fn lambda_and_anonymous_function_are_barriers() { + let (r, e) = parse( + "fun outer() {\n val l = { x: Int -> x + 1 }\n val ef = fun(x: Int) = x\n}\n", + ); + assert_owner(&r, &e, 1, "outer"); + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + } + + #[test] + fn anonymous_initializer_and_object_literal_are_identity_barriers() { + let (r, e) = parse("class A {\n init {\n val x = 1\n }\n val o = object {\n fun anon() {\n }\n }\n}\n"); + assert_abstain(&r, &e, 3); + assert_abstain(&r, &e, 6); + } + + #[test] + fn local_function_inside_initializer_abstains() { + // A named local function declared inside an init block has no complete + // identity: its lexical path crosses the unnamed initializer context. + // Hits inside `local` must NOT attribute to `A.local`. + let (r, e) = parse("class A {\n init {\n fun local() {\n val x = 1\n }\n }\n}\n"); + assert_abstain(&r, &e, 3); + assert_abstain(&r, &e, 4); + } + + #[test] + fn generic_function_has_no_receiver() { + let (r, e) = parse("fun foo(x: T) {\n return x\n}\n"); + assert_owner(&r, &e, 1, "foo"); + assert_owner(&r, &e, 2, "foo"); + } + + #[test] + fn generic_extension_function_reader() { + let (r, e) = parse("fun List.first(): T {\n return this[0]\n}\n"); + assert_owner(&r, &e, 1, "List.first"); + } + + #[test] + fn bodyless_function_abstains() { + let (r, e) = parse("interface Iface {\n fun abs()\n}\n"); + assert_abstain(&r, &e, 2); + } + + #[test] + fn primary_constructor_abstains() { + let (r, e) = parse("class C(val x: Int) {\n}\n"); + assert_abstain(&r, &e, 1); + } + + #[test] + fn malformed_local_error_degrades_to_barrier() { + let (r, e) = parse("fun broken() {\n val x = (\n}\n"); + assert_abstain(&r, &e, 2); + } + + #[test] + fn clean_callable_elsewhere_in_partial_tree_still_eligible() { + let (r, e) = parse("fun good() {\n val x = 1\n}\nfun broken() {\n val x = (\n}\n"); + assert_owner(&r, &e, 1, "good"); + assert_abstain(&r, &e, 4); + } + + /// A single independent fixture, parsed on its own with 1-based local line + /// numbers. `owners` lists `(hit_line, name, start_line, end_line)` that + /// must attribute to the exact owner; `abstain` lists lines that must + /// abstain and count toward the intentional-abstention floor; `incidental` + /// lists lines that must abstain but do NOT count. + struct Case { + label: &'static str, + source: &'static str, + owners: &'static [(u32, &'static str, u32, u32)], + abstain: &'static [u32], + incidental: &'static [u32], + } + + /// US-068 curated Kotlin accuracy gate. + #[test] + fn kotlin_owner_matrix_meets_quality_gates() { + let cases: &[Case] = &[ + Case { + label: "top-level function", + source: "fun alpha() {\n val x = 1\n}\n", + owners: &[(1, "alpha", 1, 3), (2, "alpha", 1, 3), (3, "alpha", 1, 3)], + abstain: &[], + incidental: &[], + }, + Case { + label: "two top-level functions", + source: "fun a() {\n val x = 1\n}\nfun b() {\n val y = 2\n}\n", + owners: &[ + (1, "a", 1, 3), + (2, "a", 1, 3), + (3, "a", 1, 3), + (4, "b", 4, 6), + (5, "b", 4, 6), + (6, "b", 4, 6), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "class method", + source: "class Service {\n fun load() {\n return 1\n }\n}\n", + owners: &[ + (2, "Service.load", 2, 4), + (3, "Service.load", 2, 4), + (4, "Service.load", 2, 4), + ], + abstain: &[1], + incidental: &[5], + }, + Case { + label: "nested declared types", + source: "class Outer {\n class Inner {\n fun handle() {\n return 1\n }\n }\n}\n", + owners: &[((3, "Outer.Inner.handle", 3, 5)), ((4, "Outer.Inner.handle", 3, 5)), ((5, "Outer.Inner.handle", 3, 5))], + abstain: &[1, 2], + incidental: &[6, 7], + }, + Case { + label: "named object", + source: "class Service {\n object Named {\n fun go() {\n }\n }\n}\n", + owners: &[((3, "Service.Named.go", 3, 4)), ((4, "Service.Named.go", 3, 4))], + abstain: &[1, 2], + incidental: &[5, 6], + }, + Case { + label: "default companion object", + source: "class Service {\n companion object {\n fun factory() {\n }\n }\n}\n", + owners: &[(3, "Service.Companion.factory", 3, 4), (4, "Service.Companion.factory", 3, 4)], + abstain: &[1, 2], + incidental: &[5, 6], + }, + Case { + label: "named companion object", + source: "class Service {\n companion object Factory {\n fun make() {\n }\n }\n}\n", + owners: &[(3, "Service.Factory.make", 3, 4), (4, "Service.Factory.make", 3, 4)], + abstain: &[1, 2], + incidental: &[5, 6], + }, + Case { + label: "extension function receiver", + source: "fun String.slug() {\n return 1\n}\n", + owners: &[(1, "String.slug", 1, 3), (2, "String.slug", 1, 3), (3, "String.slug", 1, 3)], + abstain: &[], + incidental: &[], + }, + Case { + label: "extension with container", + source: "class Helpers {\n fun String.slug() {\n return 1\n }\n}\n", + owners: &[(2, "Helpers.String.slug", 2, 4), (3, "Helpers.String.slug", 2, 4), (4, "Helpers.String.slug", 2, 4)], + abstain: &[1], + incidental: &[5], + }, + Case { + label: "generic receiver spelling", + source: "fun List.firstOrNullSafe() {\n return null\n}\n", + owners: &[(1, "List.firstOrNullSafe", 1, 3), (2, "List.firstOrNullSafe", 1, 3), (3, "List.firstOrNullSafe", 1, 3)], + abstain: &[], + incidental: &[], + }, + Case { + label: "secondary constructor", + source: "class WithCtor(val x: Int) {\n constructor(s: String) {\n }\n}\n", + owners: &[(2, "WithCtor.WithCtor", 2, 3), (3, "WithCtor.WithCtor", 2, 3)], + abstain: &[1], + incidental: &[4], + }, + Case { + label: "property getter", + source: "class Registry {\n val prop: Int\n get() =\n 1\n}\n", + owners: &[(3, "Registry.prop.get", 3, 4), (4, "Registry.prop.get", 3, 4)], + abstain: &[1, 2], + incidental: &[5], + }, + Case { + label: "property setter", + source: "class Registry {\n var prop: Int = 0\n set(value) {\n }\n}\n", + owners: &[(3, "Registry.prop.set", 3, 4), (4, "Registry.prop.set", 3, 4)], + abstain: &[1, 2], + incidental: &[5], + }, + Case { + label: "local function full path", + source: "fun outer() {\n fun inner() {\n return 1\n }\n}\n", + owners: &[ + (1, "outer", 1, 5), + (2, "outer.inner", 2, 4), + (3, "outer.inner", 2, 4), + (4, "outer.inner", 2, 4), + (5, "outer", 1, 5), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "deep local nesting", + source: "fun a() {\n fun b() {\n fun c() {\n }\n }\n}\n", + owners: &[(1, "a", 1, 6), (2, "a.b", 2, 5), (3, "a.b.c", 3, 4), (4, "a.b.c", 3, 4), (5, "a.b", 2, 5), (6, "a", 1, 6)], + abstain: &[], + incidental: &[], + }, + Case { + label: "lambda barrier", + source: "fun outer() {\n val l = { x: Int -> x + 1 }\n return l\n}\n", + owners: &[(1, "outer", 1, 4), (3, "outer", 1, 4), (4, "outer", 1, 4)], + abstain: &[2], + incidental: &[], + }, + Case { + label: "annotated lambda barrier", + source: "fun outer() {\n call {\n val x = 1\n }\n}\n", + owners: &[(1, "outer", 1, 5), (5, "outer", 1, 5)], + abstain: &[2, 3], + incidental: &[4], + }, + Case { + label: "anonymous function barrier", + source: "fun outer() {\n val ef = fun(x: Int) = x\n}\n", + owners: &[(1, "outer", 1, 3), (3, "outer", 1, 3)], + abstain: &[2], + incidental: &[], + }, + Case { + label: "interface default method", + source: "interface Iface {\n fun defaultImpl() {\n }\n}\n", + owners: &[(2, "Iface.defaultImpl", 2, 3), (3, "Iface.defaultImpl", 2, 3)], + abstain: &[1], + incidental: &[4], + }, + Case { + label: "nested object with member", + source: "class Holder {\n object Conf {\n fun load() {\n }\n }\n}\n", + owners: &[(3, "Holder.Conf.load", 3, 4), (4, "Holder.Conf.load", 3, 4)], + abstain: &[1, 2], + incidental: &[5, 6], + }, + Case { + label: "anonymous initializer barrier", + source: "class A {\n init {\n val x = 1\n }\n}\n", + owners: &[], + abstain: &[2, 3], + incidental: &[1, 4, 5], + }, + Case { + label: "object literal barrier", + source: "class A {\n val o = object {\n fun anon() {\n }\n }\n}\n", + owners: &[], + abstain: &[3, 4], + incidental: &[1, 2, 5, 6, 7], + }, + Case { + label: "bodyless interface abstains", + source: "interface Iface {\n fun abs()\n}\n", + owners: &[], + abstain: &[1, 2], + incidental: &[3], + }, + Case { + label: "primary constructor abstains", + source: "class C(val x: Int) {\n}\n", + owners: &[], + abstain: &[1], + incidental: &[2], + }, + Case { + label: "malformed error degrades", + source: "fun broken() {\n val x = (\n val y = 2\n}\n", + owners: &[], + abstain: &[1, 2, 3], + incidental: &[4], + }, + Case { + label: "clean plus malformed partial", + source: "fun good() {\n val x = 1\n}\nfun broken() {\n val x = (\n}\n", + owners: &[(1, "good", 1, 3), (2, "good", 1, 3), (3, "good", 1, 3)], + abstain: &[4, 5], + incidental: &[6], + }, + ]; + + let mut positives = 0u32; + let mut abstentions = 0u32; + for case in cases { + let (regions, errors) = parse(case.source); + for &(hit_line, name, start, end) in case.owners { + positives += 1; + let owner = kotlin_owner_for(®ions, &errors, hit_line); + assert!( + owner.is_some(), + "[{}] line {hit_line}: expected {name}@{start}-{end}, got abstain", + case.label + ); + let owner = owner.unwrap(); + assert_eq!(owner.qualified_name(), name, "[{}] name", case.label); + assert_eq!(owner.start_line, start, "[{}] start", case.label); + assert_eq!(owner.end_line, end, "[{}] end", case.label); + } + for &line in case.abstain { + abstentions += 1; + assert!( + kotlin_owner_for(®ions, &errors, line).is_none(), + "[{}] line {line} should abstain", + case.label + ); + } + for &line in case.incidental { + assert!( + kotlin_owner_for(®ions, &errors, line).is_none(), + "[{}] incidental line {line} should abstain", + case.label + ); + } + } + assert!( + positives >= 60, + "positive floor: only {positives} assertions" + ); + assert!( + abstentions >= 20, + "intentional-abstention floor: only {abstentions} assertions" + ); + } + + #[test] + fn manifest_gate_verifies_kinds_exist_and_fingerprint_is_pinned() { + let v: serde_json::Value = serde_json::from_str(tree_sitter_kotlin_ng::NODE_TYPES).unwrap(); + let kinds: HashSet = v + .as_array() + .unwrap() + .iter() + .filter_map(|e| e.get("type").and_then(|t| t.as_str()).map(String::from)) + .collect(); + assert!(!kinds.is_empty(), "NODE_TYPES must declare node kinds"); + for k in KOTLIN_EXECUTABLE_CALLABLES + .iter() + .chain(KOTLIN_CONTAINER_KINDS) + .chain(KOTLIN_BODILESS_OR_BARRIER_KINDS) + { + assert!( + kinds.contains(*k), + "manifest kind {k} missing from NODE_TYPES" + ); + } + let mut all: Vec<&str> = Vec::new(); + all.extend(KOTLIN_EXECUTABLE_CALLABLES); + all.extend(KOTLIN_CONTAINER_KINDS); + all.extend(KOTLIN_BODILESS_OR_BARRIER_KINDS); + let uniq: HashSet<&str> = all.iter().copied().collect(); + assert_eq!( + uniq.len(), + all.len(), + "manifest inventories must be disjoint" + ); + assert_eq!( + fnv1a(tree_sitter_kotlin_ng::NODE_TYPES.as_bytes()), + KOTLIN_NODE_TYPES_FINGERPRINT, + "tree-sitter-kotlin-ng NODE_TYPES changed; re-audit the manifest" + ); + } +} diff --git a/src/evidence/owners/mod.rs b/src/evidence/owners/mod.rs new file mode 100644 index 0000000..5c634a3 --- /dev/null +++ b/src/evidence/owners/mod.rs @@ -0,0 +1,326 @@ +//! Shared owner-region model and selection semantics for multilanguage owner +//! attribution (US-067 phase 1). +//! +//! Each supported language adapter parses a file into a flat list of nested +//! callable `OwnerRegion`s. A region is either a `Named` owner (an `OwnerAnchor`) +//! or an `AnonymousBarrier` (an anonymous callable that must not let a hit fall +//! through to an enclosing named owner). For a given hit line, the shared +//! `narrowest_named_owner` selects the unique narrowest containing region and +//! returns its anchor only when that region is `Named`; a barrier or an +//! equal-width tie abstains. +//! +//! Language-specific traversal and container logic stay in each adapter +//! (`python.rs`, `rust.rs`, `js_ts.rs`); this module owns only the shared region +//! model, the unique-narrowest selection, and local-`ERROR` primitives. + +pub(crate) mod csharp; +pub(crate) mod java; +pub(crate) mod js_ts; +pub(crate) mod kotlin; +pub(crate) mod php; +pub(crate) mod python; +pub(crate) mod rust; + +use crate::evidence::owner_links::OwnerAnchor; + +/// A callable region in a source file. `Named` regions carry an owner anchor +/// (a supported named callable); `AnonymousBarrier` regions are anonymous +/// callables that must abstain so a hit inside them never falls through to an +/// enclosing named owner. +#[derive(Debug, Clone)] +pub(crate) enum OwnerRegion { + Named(OwnerAnchor), + AnonymousBarrier { start_line: u32, end_line: u32 }, +} + +impl OwnerRegion { + pub(crate) fn start_line(&self) -> u32 { + match self { + OwnerRegion::Named(a) => a.start_line, + OwnerRegion::AnonymousBarrier { start_line, .. } => *start_line, + } + } + + pub(crate) fn end_line(&self) -> u32 { + match self { + OwnerRegion::Named(a) => a.end_line, + OwnerRegion::AnonymousBarrier { end_line, .. } => *end_line, + } + } + + fn contains(&self, line: u32) -> bool { + self.start_line() <= line && line <= self.end_line() + } + + fn span(&self) -> u32 { + self.end_line().saturating_sub(self.start_line()) + } +} + +/// Select the unique narrowest containing region for `line` and return its +/// anchor only when that region is `Named`. Abstains when no region contains +/// the line, when two or more regions tie for the narrowest span, or when the +/// narrowest region is an `AnonymousBarrier`. +pub(crate) fn narrowest_named_owner(regions: &[OwnerRegion], line: u32) -> Option<&OwnerAnchor> { + let containing = regions + .iter() + .filter(|region| region.contains(line)) + .collect::>(); + let min_span = containing.iter().map(|region| region.span()).min()?; + let mut narrowest = containing.iter().filter(|region| region.span() == min_span); + let first = narrowest.next()?; + if narrowest.next().is_some() { + return None; + } + match first { + OwnerRegion::Named(anchor) => Some(anchor), + OwnerRegion::AnonymousBarrier { .. } => None, + } +} + +/// A byte span plus its inclusive 1-indexed line span, used to record a parser +/// `ERROR` node or a zero-width missing token so attribution can abstain around +/// it. `is_point` marks a zero-width missing token; its byte overlap semantics +/// are boundary-inclusive (see [`ErrorRange::overlaps_bytes`]). +#[derive(Debug, Clone, Copy)] +pub(crate) struct ErrorRange { + pub(crate) start_byte: usize, + pub(crate) end_byte: usize, + pub(crate) start_line: u32, + pub(crate) end_line: u32, + /// `true` for a zero-width missing token (a single byte position). + pub(crate) is_point: bool, +} + +impl ErrorRange { + /// `true` when this error range overlaps `[byte_start, byte_end)`. + /// + /// For a non-empty `ERROR` span this is the standard half-open overlap. + /// For a zero-width missing token (`is_point`) it is boundary-inclusive + /// (`start_byte <= byte_start..=byte_end`), so a missing token sitting at a + /// callable's end/EOF boundary still degrades that callable rather than + /// slipping just outside its byte span. + pub(crate) fn overlaps_bytes(&self, byte_start: usize, byte_end: usize) -> bool { + if self.is_point { + self.start_byte >= byte_start && self.start_byte <= byte_end + } else { + self.start_byte < byte_end && byte_start < self.end_byte + } + } + + /// `true` when this error range's inclusive line range contains `line`. + pub(crate) fn contains_line(&self, line: u32) -> bool { + self.start_line <= line && line <= self.end_line + } +} + +/// Convert a tree-sitter node's exclusive end position into an inclusive, +/// 1-indexed end line. tree-sitter end positions are exclusive, so an end +/// column of `0` means the node ends at the start of a row and its last content +/// line is the previous row; this must not accidentally claim the next line. +fn inclusive_end_line(node: tree_sitter::Node<'_>) -> u32 { + let pos = node.end_position(); + if pos.column == 0 { + pos.row as u32 + } else { + pos.row as u32 + 1 + } +} + +/// Collect every `ERROR` or missing node's byte + line span in a tree. +/// Line numbers are 1-indexed and inclusive. +/// +/// Walks ALL children (named and unnamed), because tree-sitter missing tokens +/// are frequently unnamed and zero-width (e.g. a missing `)`). A zero-width +/// missing token is recorded as a single-line point with `is_point = true`. +/// Non-empty `ERROR` spans clamp their end byte to the content length and +/// compute their inclusive end line via [`inclusive_end_line`]. +pub(crate) fn collect_error_ranges(tree: &tree_sitter::Tree, content: &[u8]) -> Vec { + let mut ranges = Vec::new(); + let mut stack: Vec = vec![tree.root_node()]; + while let Some(node) = stack.pop() { + let mut cursor = node.walk(); + let children: Vec = node.children(&mut cursor).collect(); + stack.extend(children.into_iter().rev()); + if node.kind() == "ERROR" || node.is_missing() { + let start = node.start_byte(); + let end = node.end_byte(); + let start_line = node.start_position().row as u32 + 1; + if node.is_missing() { + // Zero-width missing token: a single-line point. `end` equals + // `start`; the line is the missing token's own line. + ranges.push(ErrorRange { + start_byte: start, + end_byte: end, + start_line, + end_line: start_line, + is_point: true, + }); + } else if end > start { + ranges.push(ErrorRange { + start_byte: start, + end_byte: end.min(content.len()), + start_line, + end_line: inclusive_end_line(node), + is_point: false, + }); + } + } + } + ranges +} + +/// Whether any error range overlaps the given byte span. +pub(crate) fn any_error_overlaps_bytes( + ranges: &[ErrorRange], + byte_start: usize, + byte_end: usize, +) -> bool { + ranges + .iter() + .any(|range| range.overlaps_bytes(byte_start, byte_end)) +} + +/// Whether any error range's inclusive line range contains `line`. +pub(crate) fn any_error_contains_line(ranges: &[ErrorRange], line: u32) -> bool { + ranges.iter().any(|range| range.contains_line(line)) +} + +/// Attribute a hit line: abstain if it intersects a local error range (line +/// inputs cannot be narrowed by parser columns), otherwise select the unique +/// narrowest named owner. +pub(crate) fn attribute_line<'a>( + regions: &'a [OwnerRegion], + errors: &[ErrorRange], + line: u32, +) -> Option<&'a OwnerAnchor> { + if any_error_contains_line(errors, line) { + return None; + } + narrowest_named_owner(regions, line) +} + +/// A `Named` region whose byte span overlaps an error range is degraded to an +/// `AnonymousBarrier` covering the full callable, per the local-error contract. +pub(crate) fn degrade_named_on_error( + region: OwnerRegion, + errors: &[ErrorRange], + byte_start: usize, + byte_end: usize, +) -> OwnerRegion { + match region { + OwnerRegion::Named(anchor) if any_error_overlaps_bytes(errors, byte_start, byte_end) => { + OwnerRegion::AnonymousBarrier { + start_line: anchor.start_line, + end_line: anchor.end_line, + } + } + other => other, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn named(name: &str, s: u32, e: u32) -> OwnerRegion { + let anchor = crate::evidence::owner_links::OwnerAnchor { + path: std::path::PathBuf::from("x.py"), + name: name.to_string(), + receiver_var: None, + receiver_type: None, + package_dir: std::path::PathBuf::from("."), + start_line: s, + end_line: e, + language: crate::types::Lang::Python, + display_name: name.to_string(), + }; + OwnerRegion::Named(anchor) + } + + fn barrier(s: u32, e: u32) -> OwnerRegion { + OwnerRegion::AnonymousBarrier { + start_line: s, + end_line: e, + } + } + + #[test] + fn picks_unique_narrowest_named_region() { + let regions = vec![named("outer", 1, 10), named("inner", 3, 5)]; + let owner = narrowest_named_owner(®ions, 4).unwrap(); + assert_eq!(owner.name, "inner"); + } + + #[test] + fn barrier_abstains_instead_of_falling_through_to_outer_named() { + // A lambda (barrier) nested inside a named function: a hit inside the + // lambda must not fall through to the enclosing named owner. + let regions = vec![named("outer", 1, 10), barrier(3, 5)]; + assert!(narrowest_named_owner(®ions, 4).is_none()); + } + + #[test] + fn equal_span_tie_abstains() { + let regions = vec![named("a", 1, 4), named("b", 2, 5)]; + // Both span 3; a hit on line 3 is contained by both -> tie -> abstain. + assert!(narrowest_named_owner(®ions, 3).is_none()); + } + + #[test] + fn named_inside_barrier_still_eligible() { + // A named def nested inside a lambda remains eligible within its own + // narrower range. + let regions = vec![named("outer", 1, 20), barrier(3, 10), named("inner", 4, 6)]; + let owner = narrowest_named_owner(®ions, 5).unwrap(); + assert_eq!(owner.name, "inner"); + } + + #[test] + fn error_range_lines_abstain_and_overlapping_named_degrades() { + let tree_less = vec![ErrorRange { + start_byte: 0, + end_byte: 10, + start_line: 2, + end_line: 2, + is_point: false, + }]; + assert!(any_error_contains_line(&tree_less, 2)); + assert!(!any_error_contains_line(&tree_less, 3)); + assert!(any_error_overlaps_bytes(&tree_less, 5, 6)); + let degraded = degrade_named_on_error(named("f", 1, 5), &tree_less, 0, 10); + assert!(matches!(degraded, OwnerRegion::AnonymousBarrier { .. })); + let kept = degrade_named_on_error(named("f", 1, 5), &tree_less, 20, 30); + assert!(matches!(kept, OwnerRegion::Named(_))); + } + + #[test] + fn missing_point_overlap_is_boundary_inclusive() { + // A zero-width missing token at a callable's exact end/EOF byte must + // still overlap it (boundary-inclusive), so it degrades rather than + // slipping just outside the half-open span. + let point = ErrorRange { + start_byte: 6, + end_byte: 6, + start_line: 1, + end_line: 1, + is_point: true, + }; + // Callable [0,6) => point at 6 == end -> overlap. + assert!(point.overlaps_bytes(0, 6)); + // Callable [0,5) => point 6 outside -> no overlap. + assert!(!point.overlaps_bytes(0, 5)); + // Callable [6,10) => point 6 == start -> overlap (boundary-inclusive). + assert!(point.overlaps_bytes(6, 10)); + // A non-point ERROR span uses strict half-open overlap (end exclusive). + let span = ErrorRange { + start_byte: 0, + end_byte: 6, + start_line: 1, + end_line: 1, + is_point: false, + }; + assert!(span.overlaps_bytes(3, 4)); + assert!(!span.overlaps_bytes(6, 7)); + } +} diff --git a/src/evidence/owners/php.rs b/src/evidence/owners/php.rs new file mode 100644 index 0000000..9eb1b6e --- /dev/null +++ b/src/evidence/owners/php.rs @@ -0,0 +1,1051 @@ +//! PHP owner-region extraction (US-068 Wave 2A). +//! +//! Supported named owners: a body-bearing `function_definition` (its declared +//! name), a body-bearing `method_declaration` under its class/interface/trait/ +//! enum container (`Service::load`), a declared namespace as a structural +//! lexical container using PHP `\` spelling (`Acme\Api\load`, +//! `Acme\Api\Service::load`; braced and unbraced forms yield the same +//! identity), and a body-bearing named property hook (`Container::$prop::get` +//! / `.set`) when the pinned grammar exposes a complete property + hook +//! identity. The owner range is the callable declaration node itself; +//! attributes/docblocks outside it are not owned. +//! +//! Abstentions/barriers: every `anonymous_function` (closure) and +//! `arrow_function` is an `AnonymousBarrier`; an `anonymous_class` is an +//! identity barrier whose methods/hooks abstain; a named function declared +//! lexically inside another callable body (`in_function`) is an identity +//! barrier and abstains (PHP registers it under its global name at execution; +//! neither `outer::inner` nor `outer.inner` is honest); interface/abstract/ +//! otherwise body-less methods and hooks are not owners; a callable with a +//! missing/unreadable name/container abstains. `.phtml` inline text and +//! top-level statements remain raw hits without a synthesized owner. + +use std::path::Path; + +use tree_sitter::Node; + +use crate::evidence::owner_links::OwnerAnchor; +use crate::evidence::owners::{ + attribute_line, collect_error_ranges, degrade_named_on_error, ErrorRange, OwnerRegion, +}; +use crate::lang::outline::outline_language; +use crate::types::Lang; + +/// Version-pinned PHP callable manifest (anti-drift contract), holding the +/// pinned tree-sitter-php 0.24.2 (`php` grammar) callable kinds. +#[cfg(test)] +const PHP_EXECUTABLE_CALLABLES: &[&str] = + &["function_definition", "method_declaration", "property_hook"]; +#[cfg(test)] +const PHP_CONTAINER_KINDS: &[&str] = &[ + "class_declaration", + "interface_declaration", + "trait_declaration", + "enum_declaration", + "namespace_definition", +]; +#[cfg(test)] +const PHP_ANONYMOUS_OR_BARRIER_KINDS: &[&str] = + &["anonymous_function", "arrow_function", "anonymous_class"]; + +/// FNV-1a-64 fingerprint of the bundled `tree-sitter-php` `PHP_NODE_TYPES` JSON +/// (tree-sitter-php 0.24.2, `php` grammar). Pinned so any grammar metadata +/// change fails the manifest gate and forces a re-audit. +#[cfg(test)] +const PHP_NODE_TYPES_FINGERPRINT: u64 = 0x1297_dd3f_8fd2_f5d3; + +/// Stable FNV-1a 64-bit hash, dependency-free and reproducible across builds. +#[cfg(test)] +fn fnv1a(bytes: &[u8]) -> u64 { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for &b in bytes { + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x100_0000_01b3); + } + hash +} + +/// Parse a PHP file and produce its owner regions and local error ranges. +/// Returns `None` when the file cannot be read, has no tree, or its root node +/// itself is an `ERROR` (preserve raw hits, emit no owner evidence). +pub(crate) fn php_regions( + path: &Path, + content: &str, +) -> Option<(Vec, Vec)> { + let language = outline_language(Lang::Php)?; + let mut parser = tree_sitter::Parser::new(); + if parser.set_language(&language).is_err() { + return None; + } + let tree = parser.parse(content, None)?; + if tree.root_node().kind() == "ERROR" { + return None; + } + let bytes = content.as_bytes(); + let errors = collect_error_ranges(&tree, bytes); + let mut regions = Vec::new(); + let mut namespace: Option = None; + let mut containers: Vec = Vec::new(); + walk_children( + tree.root_node(), + bytes, + path, + false, + false, + &mut namespace, + &mut containers, + &errors, + &mut regions, + ); + Some((regions, errors)) +} + +/// Read a node field's trimmed source text, returning `None` when the field is +/// missing, unreadable, or empty after trimming. This is fail-closed: an empty +/// structural name must never become an owner or a nameless container that a +/// nested callable could fall through. +fn field_nonempty<'a>(node: Node<'_>, field: &str, bytes: &'a [u8]) -> Option<&'a str> { + node.child_by_field_name(field)? + .utf8_text(bytes) + .ok() + .map(str::trim) + .filter(|s| !s.is_empty()) +} + +/// Emit a full-range `AnonymousBarrier` for a node and descend `in_anonymous`. +fn barrier_and_descend( + node: Node<'_>, + bytes: &[u8], + path: &Path, + in_function: bool, + namespace: &mut Option, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + walk_children( + node, + bytes, + path, + true, + in_function, + namespace, + containers, + errors, + regions, + ); +} + +/// Walk a PHP tree, emitting `Named` regions for body-bearing callables and +/// `AnonymousBarrier` regions for anonymous/identity barriers. `in_anonymous` +/// is true inside an anonymous identity barrier (closure, arrow function, +/// anonymous class); `in_function` is true inside a callable body, so a nested +/// named function becomes an identity barrier rather than a dishonest owner. +fn walk( + node: Node<'_>, + bytes: &[u8], + path: &Path, + in_anonymous: bool, + in_function: bool, + namespace: &mut Option, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + // Anonymous identity barriers (no structural name). + if matches!(node.kind(), "anonymous_function" | "arrow_function") { + barrier_and_descend( + node, bytes, path, true, namespace, containers, errors, regions, + ); + return; + } + if node.kind() == "anonymous_class" { + barrier_and_descend( + node, bytes, path, true, namespace, containers, errors, regions, + ); + return; + } + + match node.kind() { + "function_definition" => { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + if in_anonymous || in_function { + // Anonymous context, or a named function nested inside another + // callable body: an identity barrier, never `outer::inner` or + // `outer.inner`. + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + walk_children( + node, bytes, path, true, true, namespace, containers, errors, regions, + ); + } else if let Some(name) = field_nonempty(node, "name", bytes) { + let name = name.to_string(); + let qualified = join_qualified(namespace.as_deref(), containers, &name); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name, + receiver_var: None, + receiver_type: None, + package_dir: std::path::PathBuf::from("."), + start_line, + end_line, + language: Lang::Php, + display_name: qualified, + }; + let region = OwnerRegion::Named(anchor); + let region = + degrade_named_on_error(region, errors, node.start_byte(), node.end_byte()); + regions.push(region); + // A function is a callable body: nested named functions must + // become identity barriers, so descend with in_function = true. + // Functions are never lexical containers in PHP. + walk_children( + node, bytes, path, false, true, namespace, containers, errors, regions, + ); + } else { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + walk_children( + node, bytes, path, true, true, namespace, containers, errors, regions, + ); + } + } + "method_declaration" => { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + let has_body = node.child_by_field_name("body").is_some(); + if in_anonymous { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + walk_children( + node, bytes, path, true, true, namespace, containers, errors, regions, + ); + } else if has_body { + if let Some(name) = field_nonempty(node, "name", bytes) { + let name = name.to_string(); + let qualified = join_qualified(namespace.as_deref(), containers, &name); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: name.clone(), + receiver_var: None, + receiver_type: None, + package_dir: std::path::PathBuf::from("."), + start_line, + end_line, + language: Lang::Php, + display_name: qualified, + }; + let region = OwnerRegion::Named(anchor); + let region = + degrade_named_on_error(region, errors, node.start_byte(), node.end_byte()); + regions.push(region); + walk_children( + node, bytes, path, false, true, namespace, containers, errors, regions, + ); + } else { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + walk_children( + node, bytes, path, true, true, namespace, containers, errors, regions, + ); + } + } else { + // Body-less method (interface/abstract): not an owner. + walk_children( + node, + bytes, + path, + in_anonymous, + in_function, + namespace, + containers, + errors, + regions, + ); + } + } + "class_declaration" + | "interface_declaration" + | "trait_declaration" + | "enum_declaration" => { + if in_anonymous { + walk_children( + node, + bytes, + path, + true, + in_function, + namespace, + containers, + errors, + regions, + ); + } else if let Some(name) = field_nonempty(node, "name", bytes) { + containers.push(name.to_string()); + walk_children( + node, + bytes, + path, + false, + in_function, + namespace, + containers, + errors, + regions, + ); + containers.pop(); + } else { + // Unnamed/malformed container: conservative barrier so nested + // regions cannot leak to an outer callable. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + walk_children( + node, + bytes, + path, + true, + in_function, + namespace, + containers, + errors, + regions, + ); + } + } + "property_declaration" => { + let mut cur = node.walk(); + let kids: Vec = node.named_children(&mut cur).collect(); + let prop_names: Vec = kids + .iter() + .filter(|c| c.kind() == "property_element") + .filter_map(|pe| field_nonempty(*pe, "name", bytes).map(String::from)) + .collect(); + // A property hook owner requires a unique structural property + // identity. When several properties share one hook list their + // physical ranges coincide, so the per-property readings would + // form an equal-width tie and violate the unique-narrowest rule; + // that ambiguous form abstains instead. + let single_prop = (prop_names.len() == 1).then(|| prop_names[0].clone()); + if let (Some(hl), Some(prop)) = ( + kids.iter().find(|c| c.kind() == "property_hook_list"), + single_prop.as_ref(), + ) { + let prop = prop.as_str(); + let mut hc = hl.walk(); + for hook in hl + .named_children(&mut hc) + .filter(|h| h.kind() == "property_hook") + { + let start_line = hook.start_position().row as u32 + 1; + let end_line = hook.end_position().row as u32 + 1; + let hook_name = { + let mut hcur = hook.walk(); + let found = hook + .named_children(&mut hcur) + .find(|c| c.kind() == "name") + .and_then(|n| n.utf8_text(bytes).ok()) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(String::from); + found + }; + let has_body = hook.child_by_field_name("body").is_some(); + if in_anonymous { + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + } else if has_body { + if let Some(hname) = &hook_name { + let segment = format!("{prop}::{hname}"); + let qualified = + join_qualified(namespace.as_deref(), containers, &segment); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: segment.clone(), + receiver_var: None, + receiver_type: None, + package_dir: std::path::PathBuf::from("."), + start_line, + end_line, + language: Lang::Php, + display_name: qualified, + }; + let region = OwnerRegion::Named(anchor); + let region = degrade_named_on_error( + region, + errors, + hook.start_byte(), + hook.end_byte(), + ); + regions.push(region); + } + } + } + } + // Hook bodies are callable bodies; descend with in_function = true + // so nested named functions inside them become barriers. + walk_children( + node, + bytes, + path, + in_anonymous, + true, + namespace, + containers, + errors, + regions, + ); + } + _ => walk_children( + node, + bytes, + path, + in_anonymous, + in_function, + namespace, + containers, + errors, + regions, + ), + } +} + +fn walk_children( + node: Node<'_>, + bytes: &[u8], + path: &Path, + in_anonymous: bool, + in_function: bool, + namespace: &mut Option, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + let mut cursor = node.walk(); + let children: Vec = node.named_children(&mut cursor).collect(); + for child in children { + // Namespace declarations are handled at the sibling level because the + // unbraced form (`namespace Acme\Api;`) is a scope directive whose + // declarations are siblings, while the braced form is a container. + if child.kind() == "namespace_definition" { + let name_field = child.child_by_field_name("name"); + let has_body = child.child_by_field_name("body").is_some(); + // A missing name field is a valid global namespace (braced + // `namespace { ... }`); a name field that is present but unreadable + // or empty is malformed and becomes a fail-closed barrier. + let name = name_field + .and_then(|n| n.utf8_text(bytes).ok()) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(String::from); + if name_field.is_some() && name.is_none() { + regions.push(OwnerRegion::AnonymousBarrier { + start_line: child.start_position().row as u32 + 1, + end_line: child.end_position().row as u32 + 1, + }); + walk_children( + child, + bytes, + path, + true, + in_function, + namespace, + containers, + errors, + regions, + ); + continue; + } + if has_body { + // Braced namespace: a lexical container for its body. + let prev = namespace.take(); + *namespace = name; + walk_children( + child, + bytes, + path, + in_anonymous, + in_function, + namespace, + containers, + errors, + regions, + ); + *namespace = prev; + } else { + // Unbraced namespace: applies to the following siblings. + *namespace = name; + } + continue; + } + walk( + child, + bytes, + path, + in_anonymous, + in_function, + namespace, + containers, + errors, + regions, + ); + } +} + +/// Build the display-qualified identity: an optional namespace prefix spelled +/// with `\`, then the lexical `::`-joined class containers, then the callable +/// segment. Examples: `load`, `Acme\Api\load`, `Service::load`, +/// `Acme\Api\Service::load`, `Service::$name::get`. +fn join_qualified(namespace: Option<&str>, containers: &[String], segment: &str) -> String { + let mut out = String::new(); + if let Some(ns) = namespace { + out.push_str(ns); + out.push('\\'); + } + if !containers.is_empty() { + out.push_str(&containers.join("::")); + out.push_str("::"); + } + out.push_str(segment); + out +} + +/// Attribute a PHP hit line to a named owner, honoring local errors. +pub(crate) fn php_owner_for<'a>( + regions: &'a [OwnerRegion], + errors: &[ErrorRange], + line: u32, +) -> Option<&'a OwnerAnchor> { + attribute_line(regions, errors, line) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + use std::path::PathBuf; + + fn path() -> PathBuf { + PathBuf::from("tests/fixtures/x.php") + } + + fn parse(src: &str) -> (Vec, Vec) { + php_regions(&path(), src).expect("should parse") + } + + fn assert_owner(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32, name: &str) { + let owner = php_owner_for(regions, errors, line); + assert_eq!( + owner.map(OwnerAnchor::qualified_name), + Some(name.to_string()), + "line {line} should attribute to {name}" + ); + } + + fn assert_abstain(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32) { + assert!( + php_owner_for(regions, errors, line).is_none(), + "line {line} should abstain" + ); + } + + #[test] + fn top_level_function_and_namespace() { + let (r, e) = parse( + " $x + 1;\n $o = new class { public function m() { return 2; } };\n}\n", + ); + assert_owner(&r, &e, 2, "outer"); + assert_abstain(&r, &e, 3); + assert_abstain(&r, &e, 4); + // The anonymous class method must not attribute to outer or be fabricated. + assert_abstain(&r, &e, 5); + } + + #[test] + fn nested_named_function_is_identity_barrier() { + let (r, e) = parse( + " $this->name;\n set { $this->name = $value; }\n }\n}\n", + ); + assert_owner(&r, &e, 4, "C::$name::get"); + assert_owner(&r, &e, 5, "C::$name::set"); + } + + #[test] + fn bodyless_property_hook_abstains() { + let (r, e) = parse( + " 1;\n }\n}\n", + owners: &[(4, "C::$value::get", 4, 4)], + abstain: &[1, 2, 3], + incidental: &[5, 6], + }, + Case { + label: "property hook set", + source: "value = $v; }\n }\n}\n", + owners: &[(4, "C::$value::set", 4, 4)], + abstain: &[1, 2, 3], + incidental: &[5, 6], + }, + Case { + label: "multi-property hooks abstain", + source: " 1;\n set { $this->a = $v; }\n }\n}\n", + owners: &[], + // A shared hook list has no unique property identity; the + // per-property readings would tie on an equal range, so it + // abstains instead. + abstain: &[3, 4, 5], + incidental: &[1, 2, 6, 7], + }, + Case { + label: "class inside function global identity", + source: " $x + 1;\n}\n", + owners: &[(2, "outer", 2, 4), (4, "outer", 2, 4)], + abstain: &[3], + incidental: &[1, 5], + }, + Case { + label: "anonymous class barrier", + source: "= 60, + "positive floor: only {positives} assertions" + ); + assert!( + abstentions >= 20, + "intentional-abstention floor: only {abstentions} assertions" + ); + } + + #[test] + fn manifest_gate_verifies_kinds_exist_and_fingerprint_is_pinned() { + let v: serde_json::Value = serde_json::from_str(tree_sitter_php::PHP_NODE_TYPES).unwrap(); + let kinds: HashSet = v + .as_array() + .unwrap() + .iter() + .filter_map(|e| e.get("type").and_then(|t| t.as_str()).map(String::from)) + .collect(); + assert!(!kinds.is_empty(), "NODE_TYPES must declare node kinds"); + for k in PHP_EXECUTABLE_CALLABLES + .iter() + .chain(PHP_CONTAINER_KINDS) + .chain(PHP_ANONYMOUS_OR_BARRIER_KINDS) + { + assert!( + kinds.contains(*k), + "manifest kind {k} missing from NODE_TYPES" + ); + } + let mut all: Vec<&str> = Vec::new(); + all.extend(PHP_EXECUTABLE_CALLABLES); + all.extend(PHP_CONTAINER_KINDS); + all.extend(PHP_ANONYMOUS_OR_BARRIER_KINDS); + let uniq: HashSet<&str> = all.iter().copied().collect(); + assert_eq!( + uniq.len(), + all.len(), + "manifest inventories must be disjoint" + ); + assert_eq!( + fnv1a(tree_sitter_php::PHP_NODE_TYPES.as_bytes()), + PHP_NODE_TYPES_FINGERPRINT, + "tree-sitter-php NODE_TYPES changed; re-audit the manifest" + ); + } +} diff --git a/src/evidence/owners/python.rs b/src/evidence/owners/python.rs new file mode 100644 index 0000000..7b305c1 --- /dev/null +++ b/src/evidence/owners/python.rs @@ -0,0 +1,684 @@ +//! Python owner-region extraction (US-067 phase 1). +//! +//! Supported named owners: synchronous and asynchronous `function_definition` +//! nodes, class methods, and nested classes/functions using their complete +//! lexical hierarchy with `.` (`Outer.Inner.handle`, `outer.inner`). The anchor +//! range starts at the `def`/`async def` node and ends at its body; a +//! `decorated_definition` wrapper is transparent, so decorator lines are not +//! inside the owner range and a hit in a decorator is not attributed to the +//! decorated function. +//! +//! Abstractions/barriers: every `lambda` is an `AnonymousBarrier`; a callable +//! with no structural name and an unnamed class container each emit a +//! full-callable `AnonymousBarrier` so a hit inside never falls through to an +//! enclosing named owner. + +use std::path::Path; + +use tree_sitter::Node; + +use crate::evidence::owner_links::OwnerAnchor; +use crate::evidence::owners::{ + attribute_line, collect_error_ranges, degrade_named_on_error, ErrorRange, OwnerRegion, +}; +use crate::lang::outline::outline_language; +use crate::types::Lang; + +/// Version-pinned Python callable manifest (anti-drift contract). +/// +/// Inventories are kept distinct so a grammar change to one category cannot +/// silently reclassify a node into another: +/// +/// * (a) executable callable kinds that MUST be classified `Named`/`Barrier`; +/// * (b) binding/container/wrapper kinds used only for naming/context; +/// * (c) body-less declaration kinds that abstain/barrier (no owner region). +/// +/// The `manifest_gate_*` tests verify every kind exists in the bundled +/// `NODE_TYPES` and pin an FNV-1a fingerprint so any grammar metadata change +/// fails the gate and forces a re-audit. +/// ACTIVE for normal builds only when referenced; the manifest inventories, +/// fingerprint, and FNV-1a helper are exercised by the test-time manifest gate. +#[cfg(test)] +const PYTHON_EXECUTABLE_CALLABLES: &[&str] = &["function_definition", "lambda"]; +#[cfg(test)] +const PYTHON_CONTAINER_KINDS: &[&str] = &["class_definition", "decorated_definition"]; +#[cfg(test)] +const PYTHON_BODILESS_DECLARATIONS: &[&str] = &[]; + +/// FNV-1a-64 fingerprint of the bundled `tree-sitter-python` `NODE_TYPES` JSON +/// (tree-sitter-python 0.23.6). Pinned so any grammar metadata change fails the +/// manifest gate and forces a re-audit of the inventories above. +#[cfg(test)] +const PYTHON_NODE_TYPES_FINGERPRINT: u64 = 0x1dd4_c1a2_e4a9_1aeb; + +/// Stable FNV-1a 64-bit hash, dependency-free and reproducible across builds. +#[cfg(test)] +fn fnv1a(bytes: &[u8]) -> u64 { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for &b in bytes { + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x100_0000_01b3); + } + hash +} + +/// Parse a Python file and produce its owner regions and local error ranges. +/// Returns `None` when the file cannot be read, has no tree, or its root node +/// itself is an `ERROR` (preserve raw hits, emit no owner evidence). +pub(crate) fn python_regions( + path: &Path, + content: &str, +) -> Option<(Vec, Vec)> { + let language = outline_language(Lang::Python)?; + let mut parser = tree_sitter::Parser::new(); + if parser.set_language(&language).is_err() { + return None; + } + let tree = parser.parse(content, None)?; + if tree.root_node().kind() == "ERROR" { + return None; + } + let bytes = content.as_bytes(); + let errors = collect_error_ranges(&tree, bytes); + let mut regions = Vec::new(); + let mut containers: Vec = Vec::new(); + walk( + tree.root_node(), + bytes, + path, + &mut containers, + &errors, + &mut regions, + ); + Some((regions, errors)) +} + +/// Walk a Python tree, emitting `Named` regions for body-bearing +/// `function_definition` nodes and `AnonymousBarrier` regions for lambdas. +/// Class and function names push onto the lexical container stack so nested +/// callables receive their full `.`-qualified name. +fn walk( + node: Node<'_>, + bytes: &[u8], + path: &Path, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + match node.kind() { + "function_definition" => { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + if let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + let name = name.to_string(); + let qualified = join_containers(containers, &name); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: name.clone(), + receiver_var: None, + receiver_type: None, + package_dir: std::path::PathBuf::from("."), + start_line, + end_line, + language: Lang::Python, + display_name: qualified, + }; + let region = OwnerRegion::Named(anchor); + let region = + degrade_named_on_error(region, errors, node.start_byte(), node.end_byte()); + regions.push(region); + containers.push(name); + recurse(node, bytes, path, containers, errors, regions); + containers.pop(); + } else { + // No structural name: emit a full-callable AnonymousBarrier and + // recurse WITHOUT a name container, so a hit inside this callable + // cannot fall through to an enclosing named owner. + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, containers, errors, regions); + } + } + "class_definition" => { + // Class is a lexical container for naming, not itself a callable. + if let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + containers.push(name.to_string()); + recurse(node, bytes, path, containers, errors, regions); + containers.pop(); + } else { + // Unnamed class container: pin a conservative barrier over the + // whole class so nested malformed regions cannot leak to an + // outer function. Recurse (without a name container). + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, containers, errors, regions); + } + } + "lambda" => { + // Anonymous barrier: a hit inside a lambda must not fall through to + // an enclosing named owner. Recurse so a named def nested inside a + // lambda remains eligible within its own narrower range. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, containers, errors, regions); + } + // `decorated_definition` is a transparent wrapper: recurse into its + // inner callable rather than treating the decoration as a callable. A + // malformed decoration collapses to an ERROR node, which the error + // ranges use to degrade any overlapping named callable. + _ => recurse(node, bytes, path, containers, errors, regions), + } +} + +fn recurse( + node: Node<'_>, + bytes: &[u8], + path: &Path, + containers: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, +) { + let mut cursor = node.walk(); + for child in node.named_children(&mut cursor) { + walk(child, bytes, path, containers, errors, regions); + } +} + +fn join_containers(containers: &[String], name: &str) -> String { + if containers.is_empty() { + name.to_string() + } else { + let mut joined = containers.join("."); + joined.push('.'); + joined.push_str(name); + joined + } +} + +/// Attribute a Python hit line to a named owner, honoring local errors. +pub(crate) fn python_owner_for<'a>( + regions: &'a [OwnerRegion], + errors: &[ErrorRange], + line: u32, +) -> Option<&'a OwnerAnchor> { + attribute_line(regions, errors, line) +} +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + use std::path::PathBuf; + + /// Stable synthetic path; `python_regions` never reads the file, so no + /// temp dir is needed and nothing must be cleaned up. + fn path() -> PathBuf { + PathBuf::from("tests/fixtures/x.py") + } + + fn parse(src: &str) -> (Vec, Vec) { + python_regions(&path(), src).expect("should parse") + } + + fn assert_owner(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32, name: &str) { + let owner = python_owner_for(regions, errors, line); + assert_eq!( + owner.map(OwnerAnchor::qualified_name), + Some(name.to_string()), + "line {line} should attribute to {name}" + ); + } + + fn assert_abstain(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32) { + assert!( + python_owner_for(regions, errors, line).is_none(), + "line {line} should abstain" + ); + } + + #[test] + fn top_level_function_and_class_method() { + let (r, e) = + parse("def load():\n pass\nclass Service:\n def handle(self):\n pass\n"); + assert_owner(&r, &e, 1, "load"); + assert_owner(&r, &e, 4, "Service.handle"); + // Outside any callable abstains. + assert_abstain(&r, &e, 3); // class header line + } + + #[test] + fn nested_class_and_def_hierarchy() { + let (r, e) = parse("class Outer:\n class Inner:\n def handle(self):\n pass\n def method(self):\n def inner(self):\n pass\n"); + assert_owner(&r, &e, 3, "Outer.Inner.handle"); + assert_owner(&r, &e, 5, "Outer.method"); + assert_owner(&r, &e, 6, "Outer.method.inner"); + } + + #[test] + fn async_function_and_decorator_range_excludes_decorator() { + let (r, e) = + parse("@decorator\ndef sync():\n pass\n@decorator\nasync def go():\n pass\n"); + // Decorator line is not inside the owner range and is not attributed. + assert_abstain(&r, &e, 1); + assert_owner(&r, &e, 2, "sync"); + assert_abstain(&r, &e, 4); + assert_owner(&r, &e, 5, "go"); + } + + #[test] + fn lambda_is_barrier_preventing_outer_fallthrough() { + let (r, e) = parse("def outer():\n f = lambda: 1\n return f\n"); + // lambda line abstains (barrier), not attributed to outer. + assert_owner(&r, &e, 1, "outer"); + assert_abstain(&r, &e, 2); + } + + #[test] + fn nested_lambda_abstains_without_named_def() { + let (r, e) = parse("def outer():\n return lambda: (lambda: None)\n"); + // The inner line is inside the lambda; abstains (no named def). + assert_owner(&r, &e, 1, "outer"); + assert_abstain(&r, &e, 2); + } + + #[test] + fn local_error_degrades_overlapping_callable_to_barrier() { + let (r, e) = parse("def broken():\n x = (\n return x\n"); + // The function spans the malformed line; it must abstain, not attribute. + assert_abstain(&r, &e, 2); + } + + #[test] + fn clean_callable_elsewhere_in_partial_tree_still_eligible() { + let (r, e) = parse("def good():\n pass\ndef broken():\n x = (\n return x\n"); + assert_owner(&r, &e, 1, "good"); + // The `broken` callable overlaps the error range, so it degrades to an + // AnonymousBarrier covering the full callable (def line included). + assert_abstain(&r, &e, 3); + assert_abstain(&r, &e, 4); + } + + #[test] + fn distinct_top_level_functions_each_unique_narrowest() { + let (r, e) = parse("def a():\n pass\ndef b():\n pass\n"); + assert_owner(&r, &e, 1, "a"); + assert_owner(&r, &e, 3, "b"); + } + + #[test] + fn empty_content_yields_no_regions() { + let (r, e) = parse("x = 1\n"); + assert!(r.is_empty()); + assert!(e.is_empty()); + } + + #[test] + fn missing_node_fixture_is_recorded_point_and_abstains() { + // `def f(:` has a zero-width MISSING `)` node (unnamed token) at byte 6. + // Walk-all-children must record it as a point that abstains that line. + let (_r, e) = parse("def f(:"); + // The missing `)` point is recorded (zero-width, is_point) on line 1. + assert!( + e.iter() + .any(|er| er.is_point && er.start_byte == er.end_byte), + "{e:?}" + ); + assert!(e.iter().any(|er| er.contains_line(1)), "{e:?}"); + // A synthetic named region on line 1 must abstain due to the point. + let anchor = OwnerAnchor { + path: path(), + name: "f".into(), + receiver_var: None, + receiver_type: None, + package_dir: PathBuf::from("."), + start_line: 1, + end_line: 1, + language: Lang::Python, + display_name: "f".into(), + }; + assert!(attribute_line(&[OwnerRegion::Named(anchor)], &e, 1).is_none()); + } + + #[test] + fn malformed_unnamed_class_does_not_leak_to_outer_function() { + // `def outer()` containing a malformed `class :` — the class collapses + // to an ERROR spanning `outer`'s body, so `outer` degrades to a barrier + // and a hit inside must abstain (never attribute to outer). + let (r, e) = parse("def outer():\n class :\n pass\n"); + assert_abstain(&r, &e, 1); // outer def line + assert_abstain(&r, &e, 2); // class line + assert_abstain(&r, &e, 3); + } + + /// A single independent fixture, parsed on its own with 1-based local line + /// numbers. `owners` lists `(hit_line, name, start_line, end_line)` that + /// must attribute to the exact owner; `abstain` lists lines that must + /// abstain and count toward the intentional-abstention floor; `incidental` + /// lists lines that must abstain but do NOT count (module-level blanks). + struct Case { + label: &'static str, + source: &'static str, + owners: &'static [(u32, &'static str, u32, u32)], + abstain: &'static [u32], + incidental: &'static [u32], + } + + /// Slice-1 binding quality gate: a table of independent, varied fixtures. + /// Each case is parsed separately with local line numbers (no shared buffer, + /// no offset math). Counts assertions programmatically and asserts the floor + /// (`>=60` positive hits, `>=20` intentional abstentions); mechanically repeated + /// `blank`/`separator` lines never count toward the abstention floor. Every + /// positive row asserts the exact owner (`qualified_name`, `start_line`, + /// `end_line`); every abstention row asserts no attribution (0 mismatches). + #[test] + fn python_owner_matrix_meets_quality_gates() { + let cases: &[Case] = &[ + Case { + label: "top-level sync multiline", + source: "def alpha():\n return 1\n", + owners: &[(1, "alpha", 1, 2), (2, "alpha", 1, 2)], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level params + body", + source: "def beta(a, b):\n c = a + b\n return c\n", + owners: &[(1, "beta", 1, 3), (2, "beta", 1, 3), (3, "beta", 1, 3)], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level defaults + branch", + source: "def gamma(x=1, y=None):\n if x:\n return y\n return x\n", + owners: &[ + (1, "gamma", 1, 4), + (2, "gamma", 1, 4), + (3, "gamma", 1, 4), + (4, "gamma", 1, 4), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level annotated", + source: "def parse(text: str) -> int:\n return len(text)\n", + owners: &[(1, "parse", 1, 2), (2, "parse", 1, 2)], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level loop body", + source: "def transform(items):\n out = []\n for it in items:\n out.append(it)\n return out\n", + owners: &[ + (1, "transform", 1, 5), + (2, "transform", 1, 5), + (3, "transform", 1, 5), + (4, "transform", 1, 5), + (5, "transform", 1, 5), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level async", + source: "async def fetch():\n data = load()\n return data\n", + owners: &[(1, "fetch", 1, 3), (2, "fetch", 1, 3), (3, "fetch", 1, 3)], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level async loop", + source: "async def poll():\n while True:\n item = await next_item()\n if item:\n return item\n", + owners: &[ + (1, "poll", 1, 5), + (2, "poll", 1, 5), + (3, "poll", 1, 5), + (4, "poll", 1, 5), + (5, "poll", 1, 5), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "decorated sync", + source: "@app.route(\"/\")\ndef home():\n return render()\n", + owners: &[(2, "home", 2, 3), (3, "home", 2, 3)], + abstain: &[1], + incidental: &[], + }, + Case { + label: "decorated async", + source: "@decorator\nasync def go():\n await step1()\n await step2()\n", + owners: &[(2, "go", 2, 4), (3, "go", 2, 4), (4, "go", 2, 4)], + abstain: &[1], + incidental: &[], + }, + Case { + label: "class methods", + source: "class Service:\n def start(self):\n self.running = True\n def stop(self):\n self.running = False\n\n", + owners: &[ + (2, "Service.start", 2, 3), + (3, "Service.start", 2, 3), + (4, "Service.stop", 4, 5), + (5, "Service.stop", 4, 5), + ], + abstain: &[1], + incidental: &[6], + }, + Case { + label: "async class methods", + source: "class AsyncService:\n async def run(self):\n await self._prep()\n await self._exec()\n async def cancel(self):\n await self._stop()\n", + owners: &[ + (2, "AsyncService.run", 2, 4), + (3, "AsyncService.run", 2, 4), + (4, "AsyncService.run", 2, 4), + (5, "AsyncService.cancel", 5, 6), + (6, "AsyncService.cancel", 5, 6), + ], + abstain: &[1], + incidental: &[], + }, + Case { + label: "repository methods", + source: "class Repository:\n def find(self, pk):\n return self._rows[pk]\n def insert(self, row):\n self._rows.append(row)\n return len(self._rows)\n def count(self):\n return len(self._rows)\n", + owners: &[ + (2, "Repository.find", 2, 3), + (3, "Repository.find", 2, 3), + (4, "Repository.insert", 4, 6), + (5, "Repository.insert", 4, 6), + (6, "Repository.insert", 4, 6), + (7, "Repository.count", 7, 8), + (8, "Repository.count", 7, 8), + ], + abstain: &[1], + incidental: &[], + }, + Case { + label: "nested class + method hierarchy", + source: "class Outer:\n class Inner:\n def handle(self):\n return self\n def method(self):\n def inner(self):\n return self\n return inner\n", + owners: &[ + (3, "Outer.Inner.handle", 3, 4), + (4, "Outer.Inner.handle", 3, 4), + (5, "Outer.method", 5, 8), + (6, "Outer.method.inner", 6, 7), + (7, "Outer.method.inner", 6, 7), + (8, "Outer.method", 5, 8), + ], + abstain: &[1, 2], + incidental: &[], + }, + Case { + label: "nested def inside def", + source: "def factory():\n def make():\n return object()\n return make\n", + owners: &[ + (1, "factory", 1, 4), + (2, "factory.make", 2, 3), + (3, "factory.make", 2, 3), + (4, "factory", 1, 4), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "deep triple nesting", + source: "class A:\n class B:\n class C:\n def deep(self):\n return self\n\n", + owners: &[(4, "A.B.C.deep", 4, 5), (5, "A.B.C.deep", 4, 5)], + abstain: &[1, 2, 3], + incidental: &[6], + }, + Case { + label: "lambda placement", + source: "def outer():\n f = lambda x: x + 1\n return f\n", + owners: &[(1, "outer", 1, 3), (3, "outer", 1, 3)], + abstain: &[2], + incidental: &[], + }, + Case { + label: "nested lambda", + source: "def outer2():\n g = lambda: (lambda: None)\n return g\n", + owners: &[(1, "outer2", 1, 3), (3, "outer2", 1, 3)], + abstain: &[2], + incidental: &[], + }, + Case { + label: "class-level statement outside method", + source: "class Logger:\n level = \"info\"\n def log(self, msg):\n print(msg)\n", + owners: &[(3, "Logger.log", 3, 4), (4, "Logger.log", 3, 4)], + abstain: &[1, 2], + incidental: &[], + }, + Case { + label: "module-level statement outside callables", + source: "def one():\n pass\nx = 1\n\ndef two():\n pass\n", + owners: &[(1, "one", 1, 2), (2, "one", 1, 2), (5, "two", 5, 6), (6, "two", 5, 6)], + abstain: &[3], + incidental: &[4], + }, + Case { + label: "comment outside callable", + source: "# comment\ndef three():\n pass\n", + owners: &[(2, "three", 2, 3), (3, "three", 2, 3)], + abstain: &[1], + incidental: &[], + }, + Case { + label: "malformed callable degrades to barrier", + source: "def broken():\n x = (\n return x\n", + owners: &[], + abstain: &[1, 2, 3], + incidental: &[], + }, + Case { + label: "malformed unnamed class hierarchy", + source: "def outer():\n class :\n pass\n", + owners: &[], + abstain: &[1, 2, 3], + incidental: &[], + }, + Case { + label: "missing token point", + source: "def f(:", + owners: &[], + abstain: &[1], + incidental: &[], + }, + ]; + + let mut positives = 0u32; + let mut abstentions = 0u32; + for case in cases { + let (regions, errors) = parse(case.source); + for &(hit_line, name, start, end) in case.owners { + positives += 1; + let owner = python_owner_for(®ions, &errors, hit_line); + assert!( + owner.is_some(), + "[{}] line {hit_line}: expected {name}@{start}-{end}, got abstain", + case.label + ); + let owner = owner.unwrap(); + assert_eq!( + owner.qualified_name(), + name, + "[{}] line {hit_line} name", + case.label + ); + assert_eq!( + owner.start_line, start, + "[{}] line {hit_line} start", + case.label + ); + assert_eq!(owner.end_line, end, "[{}] line {hit_line} end", case.label); + } + for &line in case.abstain { + abstentions += 1; + assert_abstain(®ions, &errors, line); + } + for &line in case.incidental { + assert_abstain(®ions, &errors, line); + } + } + // Binding quality floor; cannot silently regress. Separation/blank lines + // live in `incidental` and never count toward the abstention floor. + assert!( + positives >= 60, + "positive floor: only {positives} assertions" + ); + assert!( + abstentions >= 20, + "intentional-abstention floor: only {abstentions} assertions" + ); + } + + #[test] + fn manifest_gate_verifies_kinds_exist_and_fingerprint_is_pinned() { + // Parse the bundled NODE_TYPES and collect every declared node kind. + let v: serde_json::Value = serde_json::from_str(tree_sitter_python::NODE_TYPES).unwrap(); + let kinds: HashSet = v + .as_array() + .unwrap() + .iter() + .filter_map(|e| e.get("type").and_then(|t| t.as_str()).map(String::from)) + .collect(); + // Every executable/config/bodyless kind must exist in the grammar. + assert!(!kinds.is_empty(), "NODE_TYPES must declare node kinds"); + for k in PYTHON_EXECUTABLE_CALLABLES + .iter() + .chain(PYTHON_CONTAINER_KINDS) + .chain(PYTHON_BODILESS_DECLARATIONS) + { + assert!( + kinds.contains(*k), + "manifest kind {k} missing from NODE_TYPES" + ); + } + // Inventories must be disjoint (a node cannot be two categories). + let mut all: Vec<&str> = Vec::new(); + all.extend(PYTHON_EXECUTABLE_CALLABLES); + all.extend(PYTHON_CONTAINER_KINDS); + all.extend(PYTHON_BODILESS_DECLARATIONS); + let uniq: HashSet<&str> = all.iter().copied().collect(); + assert_eq!( + uniq.len(), + all.len(), + "manifest inventories must be disjoint" + ); + // Fingerprint is pinned so grammar metadata changes fail here. + assert_eq!( + fnv1a(tree_sitter_python::NODE_TYPES.as_bytes()), + PYTHON_NODE_TYPES_FINGERPRINT, + "tree-sitter-python NODE_TYPES changed; re-audit the manifest" + ); + } +} diff --git a/src/evidence/owners/rust.rs b/src/evidence/owners/rust.rs new file mode 100644 index 0000000..5263373 --- /dev/null +++ b/src/evidence/owners/rust.rs @@ -0,0 +1,1142 @@ +//! Rust owner-region extraction (US-067 phase 2). +//! +//! Supported named owners: top-level and body-bearing `function_item` nodes, +//! nested module/function `::` paths, inherent `Type::method`, trait default +//! `Trait::method`, and trait impl exactly `::method`. +//! +//! Abstractions/barriers: every `closure_expression` is an `AnonymousBarrier`; +//! body-less `function_signature_item` (trait/extern declarations) abstain so +//! they cannot fall through; an `impl_item` whose identity is missing/unreadable +//! is a full-callable `AnonymousBarrier` (never an unqualified fallback); a +//! `mod_item` with no structural name, and any callable reached through an +//! anonymous collapsed-module block, barrier so guessed child names never leak; +//! `macro_definition` regions barrier so macro-generated owners are not guessed. + +use std::path::Path; + +use tree_sitter::Node; + +use crate::evidence::owner_links::OwnerAnchor; +use crate::evidence::owners::{ + any_error_overlaps_bytes, attribute_line, collect_error_ranges, degrade_named_on_error, + ErrorRange, OwnerRegion, +}; +use crate::lang::outline::outline_language; +use crate::types::Lang; + +/// Version-pinned Rust callable manifest (anti-drift contract). +/// +/// Inventories are kept distinct so a grammar change to one category cannot +/// silently reclassify a node into another: +/// +/// * (a) executable callable kinds that MUST be classified `Named`/`Barrier`; +/// * (b) binding/container/wrapper kinds used only for naming/context; +/// * (c) body-less declaration kinds that abstain/barrier (no owner region). +#[cfg(test)] +const RUST_EXECUTABLE_CALLABLES: &[&str] = &["function_item", "closure_expression"]; +#[cfg(test)] +const RUST_CONTAINER_KINDS: &[&str] = &["mod_item", "impl_item", "trait_item", "foreign_mod_item"]; +#[cfg(test)] +const RUST_BODILESS_DECLARATIONS: &[&str] = &["function_signature_item"]; + +/// FNV-1a-64 fingerprint of the bundled `tree-sitter-rust` `NODE_TYPES` JSON +/// (tree-sitter-rust 0.24.2). Pinned so any grammar metadata change fails the +/// manifest gate and forces a re-audit of the inventories above. +#[cfg(test)] +const RUST_NODE_TYPES_FINGERPRINT: u64 = 0x50a2_cce6_3015_8590; + +/// Stable FNV-1a 64-bit hash, dependency-free and reproducible across builds. +#[cfg(test)] +fn fnv1a(bytes: &[u8]) -> u64 { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for &b in bytes { + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x100_0000_01b3); + } + hash +} + +/// Parse a Rust file and produce its owner regions and local error ranges. +/// Returns `None` when the file cannot be read, has no tree, or its root node +/// itself is an `ERROR` (preserve raw hits, emit no owner evidence). +pub(crate) fn rust_regions( + path: &Path, + content: &str, +) -> Option<(Vec, Vec)> { + let language = outline_language(Lang::Rust)?; + let mut parser = tree_sitter::Parser::new(); + if parser.set_language(&language).is_err() { + return None; + } + let tree = parser.parse(content, None)?; + if tree.root_node().kind() == "ERROR" { + return None; + } + let bytes = content.as_bytes(); + let errors = collect_error_ranges(&tree, bytes); + let mut regions = Vec::new(); + let mut prefixes: Vec = Vec::new(); + walk( + tree.root_node(), + bytes, + path, + &mut prefixes, + &errors, + &mut regions, + false, + ); + Some((regions, errors)) +} + +/// Walk a Rust tree, emitting `Named` regions for body-bearing `function_item` +/// nodes and `AnonymousBarrier` regions for every other callable (closures, +/// body-less signatures, and callables whose enclosing container identity is +/// unknown). A `prefixes` stack carries `::`-suffixed path segments (modules, +/// functions, inherent/trait impls, traits) so nested callables get their full +/// qualified name. `impl` identity text is preserved from source tokens with +/// whitespace collapsed; an unreadable impl becomes a full-callable barrier. +/// +/// `recovery` is true when walking inside a collapsed malformed container +/// (`mod {`, `impl {`, pointer-less `trait {`), +/// which tree-sitter recovers as an `expression_statement`-wrapped block with +/// an immediately-preceding ERROR sibling. Under `recovery` every contained +/// callable is classified as an `AnonymousBarrier` (never a guessed name), but +/// traversal still continues so EVERY callable node is classified — omission +/// is a contract violation. A structurally named callable inside an ordinary +/// anonymous closure barrier remains eligible when its naming context is valid. +fn walk( + node: Node<'_>, + bytes: &[u8], + path: &Path, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + recovery: bool, +) { + match node.kind() { + "function_item" => walk_function(node, bytes, path, prefixes, errors, regions, recovery), + "closure_expression" => { + // Anonymous barrier: a hit inside a closure must not fall through + // to an enclosing named owner. Recurse so a named item nested + // inside a closure still gets classified; under a valid naming + // context it remains eligible within its narrower range. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, recovery); + } + "function_signature_item" => { + // Body-less trait/extern signature: abstain so it cannot fall + // through to an enclosing owner. No body to recurse into. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + } + "impl_item" => walk_impl(node, bytes, path, prefixes, errors, regions, recovery), + "trait_item" => { + if recovery { + // Invalid-identity context: barrier the whole trait and keep + // traversing so every contained callable is classified. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + } else if let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + prefixes.push(format!("{}::", name.trim())); + recurse(node, bytes, path, prefixes, errors, regions, false); + prefixes.pop(); + } else { + // Nameless trait: unknown lexical container identity. + // Barrier and continue so contained callables (usually + // signatures) are classified, never guessed. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + } + } + "mod_item" => { + if recovery { + // Invalid-identity context: barrier the whole module and keep + // traversing so every contained callable is classified. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + } else if let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + prefixes.push(format!("{}::", name.trim())); + recurse(node, bytes, path, prefixes, errors, regions, false); + prefixes.pop(); + } else { + // Nameless module: unknown lexical container identity. + // Barrier and continue so every contained callable is + // classified, never exposed with a guessed name. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + } + } + "foreign_mod_item" => { + // Extern block: body-less signatures inside are barriers; the + // block itself is a transparent container (no name to qualify). + recurse(node, bytes, path, prefixes, errors, regions, recovery); + } + "macro_definition" => { + // macro_rules! is not a callable; its rule bodies are not code to + // recurse into. Barrier so generated-owner lines never leak. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + } + "expression_statement" => { + if is_recovery_wrapper(node) { + // A collapsed malformed container (mod/impl/trait with no valid + // identity) recovers here: an expression_statement wrapping a + // block of declarations with an immediately-preceding ERROR. Its + // contained callables have unknown identity, so the whole block + // is a barrier and traversal continues under `recovery`. + if let Some(block) = node.named_child(0) { + regions.push(OwnerRegion::AnonymousBarrier { + start_line: block.start_position().row as u32 + 1, + end_line: block.end_position().row as u32 + 1, + }); + } + recurse(node, bytes, path, prefixes, errors, regions, true); + } else { + recurse(node, bytes, path, prefixes, errors, regions, recovery); + } + } + // `macro_invocation` is a statement/expression, not a callable; do not + // guess owners from its generated token tree. Skip (enclosing owner + // still owns the line). + _ => recurse(node, bytes, path, prefixes, errors, regions, recovery), + } +} + +/// Whether `node` is the recovery wrapper of a collapsed malformed container: +/// an `expression_statement` whose first named child is a `block` and which has +/// an immediately-preceding ERROR sibling. This is the structural fingerprint +/// of `mod {`, an unreadable `impl {`, or name-less `trait +/// {` (tree-sitter parses the stray `{ ... }` as a statement block). It is NOT +/// a valid nested block: those (standalone block, if/loop/match bodies) have no +/// ERROR sibling, so a lexically nested `function_item` inside them stays +/// eligible. The preceding ERROR must itself announce a collapsed mod/impl/trait +/// container (its subtree contains the relevant item-introducer keyword token), +/// so an unrelated local ERROR before a valid standalone block is rejected. +/// +/// NOTE: the keyword may be an unnamed token, so all ERROR children are walked. +fn is_recovery_wrapper(node: Node<'_>) -> bool { + if node.kind() != "expression_statement" { + return false; + } + if node + .named_child(0) + .is_none_or(|first| first.kind() != "block") + { + return false; + } + let Some(parent) = node.parent() else { + return false; + }; + let mut cursor = parent.walk(); + let siblings: Vec> = parent.named_children(&mut cursor).collect(); + let Some(idx) = siblings.iter().position(|s| s.id() == node.id()) else { + return false; + }; + idx > 0 + && siblings[idx - 1].kind() == "ERROR" + && error_is_collapsed_container(siblings[idx - 1]) +} + +/// Whether an ERROR node announces a collapsed `mod`/`impl`/`trait` container: +/// its subtree contains an anonymous grammar token of kind `mod`, `impl`, or +/// `trait`. Traversal is purely structural (`Node::kind()`, no source text/bytes, +/// no whole-ERROR fallback) and recurses through ALL children because the token +/// may sit below the immediate child. This rejects unrelated local ERRORs (e.g. +/// a stray `struct`/`enum`/`foo(`) that happen to be immediately followed by a +/// valid standalone block, so a clean nested `function_item` with no ERROR +/// overlap stays eligible. +fn error_is_collapsed_container(error: Node<'_>) -> bool { + fn contains_item_keyword(node: Node<'_>) -> bool { + let mut cursor = node.walk(); + for child in node.children(&mut cursor) { + if !child.is_named() && matches!(child.kind(), "mod" | "impl" | "trait") { + return true; + } + if contains_item_keyword(child) { + return true; + } + } + false + } + contains_item_keyword(error) +} + +/// Emit a `Named` region for a body-bearing callable, or a full-callable +/// `AnonymousBarrier` when the callable is under an invalid-identity/recovery +/// context or has no structural name. Traversal always continues so every +/// nested callable is classified (never omitted). +fn walk_function( + node: Node<'_>, + bytes: &[u8], + path: &Path, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + recovery: bool, +) { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + if recovery { + // Under a collapsed malformed container the enclosing identity is + // unknown; classify this callable as a barrier and keep traversing so + // deeper callables are also classified (never a guessed partial name). + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + return; + } + if let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + let name = name.to_string(); + let qualified = join_prefixes(prefixes, &name); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: name.clone(), + receiver_var: None, + receiver_type: None, + package_dir: std::path::PathBuf::from("."), + start_line, + end_line, + language: Lang::Rust, + display_name: qualified, + }; + let region = OwnerRegion::Named(anchor); + let region = degrade_named_on_error(region, errors, node.start_byte(), node.end_byte()); + regions.push(region); + prefixes.push(format!("{name}::")); + recurse(node, bytes, path, prefixes, errors, regions, false); + prefixes.pop(); + } else { + // Nameless function: unknown identity; barrier and keep traversing so + // deeper callables are classified (never guessed). + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + } +} + +/// Walk an `impl_item`: inherent (`impl Type`) or trait (`impl Trait for +/// Type`). Pushes the correctly-qualified prefix so methods become +/// `Type::method` or `::method`. An unreadable/missing impl +/// identity becomes a full-callable barrier over the whole impl (never an +/// unqualified fallback) while traversal continues under an invalid-identity +/// context so every contained callable is classified. +fn walk_impl( + node: Node<'_>, + bytes: &[u8], + path: &Path, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + recovery: bool, +) { + let body_byte = node + .child_by_field_name("body") + .map_or(node.end_byte(), |b| b.start_byte()); + // The signature region is from the `impl` keyword to the body. An ERROR + // there means the identity text is unreadable -> full barrier. + let identity_unreadable = any_error_overlaps_bytes(errors, node.start_byte(), body_byte); + let type_text = node + .child_by_field_name("type") + .and_then(|n| n.utf8_text(bytes).ok()) + .map(normalize_impl_text); + let trait_text = node + .child_by_field_name("trait") + .and_then(|n| n.utf8_text(bytes).ok()) + .map(normalize_impl_text); + let prefix = match (&type_text, &trait_text) { + (Some(ty), None) => Some(format!("{ty}::")), + (Some(ty), Some(tr)) => Some(format!("<{ty} as {tr}>::")), + _ => None, + }; + if recovery { + // Under a collapsed malformed container: barrier the whole impl and + // keep traversing so every contained callable is classified. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + return; + } + if let (Some(prefix), false) = (prefix, identity_unreadable) { + prefixes.push(prefix); + recurse(node, bytes, path, prefixes, errors, regions, false); + prefixes.pop(); + } else { + // Unreadable/missing impl identity: full-callable barrier; do not + // emit unqualified method names, but keep traversing so every + // contained callable is classified (never omitted). + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + } +} + +#[allow(clippy::too_many_arguments)] +fn recurse( + node: Node<'_>, + bytes: &[u8], + path: &Path, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + recovery: bool, +) { + let mut cursor = node.walk(); + for child in node.named_children(&mut cursor) { + walk(child, bytes, path, prefixes, errors, regions, recovery); + } +} +fn join_prefixes(prefixes: &[String], name: &str) -> String { + if prefixes.is_empty() { + name.to_string() + } else { + let mut joined = prefixes.concat(); + joined.push_str(name); + joined + } +} + +/// Preserve an impl type/trait node's source tokens and punctuation, trimming +/// and collapsing each `split_whitespace` run to one ASCII space. No semantic +/// resolution (e.g. `Foo` stays `Foo`, `Vec < T >` collapses to +/// `Vec < T >`). +fn normalize_impl_text(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +/// Attribute a Rust hit line to a named owner, honoring local errors. +pub(crate) fn rust_owner_for<'a>( + regions: &'a [OwnerRegion], + errors: &[ErrorRange], + line: u32, +) -> Option<&'a OwnerAnchor> { + attribute_line(regions, errors, line) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + use std::path::PathBuf; + + fn path() -> PathBuf { + PathBuf::from("tests/fixtures/x.rs") + } + + fn parse(src: &str) -> (Vec, Vec) { + rust_regions(&path(), src).expect("should parse") + } + + fn assert_owner(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32, name: &str) { + let owner = rust_owner_for(regions, errors, line); + assert_eq!( + owner.map(OwnerAnchor::qualified_name), + Some(name.to_string()), + "line {line} should attribute to {name}" + ); + } + + fn assert_abstain(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32) { + assert!( + rust_owner_for(regions, errors, line).is_none(), + "line {line} should abstain" + ); + } + + #[test] + fn top_level_function_and_inherent_method() { + let (r, e) = parse("struct Foo {}\nimpl Foo {\n fn a() {}\n fn b(&self) {}\n}\n"); + assert_owner(&r, &e, 3, "Foo::a"); + assert_owner(&r, &e, 4, "Foo::b"); + assert_abstain(&r, &e, 2); // impl header line + } + + #[test] + fn trait_impl_uses_type_as_trait_identity() { + let (r, e) = parse("impl Display for Foo {\n fn fmt(&self) {}\n}\n"); + assert_owner(&r, &e, 2, "::fmt"); + assert_abstain(&r, &e, 1); // impl header line + } + + #[test] + fn trait_default_body_some_and_body_less_signature_barriers() { + let (r, e) = + parse("trait Greet {\n fn hi();\n fn bye() {\n let x = 1;\n }\n}\n"); + assert_owner(&r, &e, 3, "Greet::bye"); + assert_abstain(&r, &e, 2); // body-less signature + assert_abstain(&r, &e, 1); // trait header line + } + + #[test] + fn nested_module_and_function_scopes_qualify_with_double_colon() { + let (r, e) = parse( + "mod a {\n mod b {\n fn f() {\n let x = 1;\n }\n }\n}\n", + ); + assert_owner(&r, &e, 3, "a::b::f"); + assert_abstain(&r, &e, 1); // mod a header + assert_abstain(&r, &e, 2); // mod b header + } + + #[test] + fn nested_function_inside_function_qualifies() { + let (r, e) = + parse("fn outer() {\n fn inner() {\n let x = 1;\n }\n inner();\n}\n"); + assert_owner(&r, &e, 1, "outer"); + assert_owner(&r, &e, 2, "outer::inner"); + assert_owner(&r, &e, 5, "outer"); + } + + #[test] + fn closure_expression_is_barrier_preventing_outer_fallthrough() { + let (r, e) = parse("fn outer() {\n let f = |x| {\n x + 1\n };\n}\n"); + assert_owner(&r, &e, 1, "outer"); + assert_abstain(&r, &e, 2); // closure line + assert_abstain(&r, &e, 3); // closure body + } + + #[test] + fn nested_closure_abstains_without_named_item() { + let (r, e) = parse("fn factory() {\n || {\n |x| x + 1\n }\n}\n"); + assert_owner(&r, &e, 1, "factory"); + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + } + + #[test] + fn generic_inherent_impl_whitespace_normalized() { + // `Stack` keeps its tokens; the identity is `Stack::push`. + let (r, e) = parse( + "impl Stack {\n fn push(self) {\n let x = 1;\n }\n}\n", + ); + assert_owner(&r, &e, 2, "Stack::push"); + assert_abstain(&r, &e, 1); + } + + #[test] + fn impl_identity_whitespace_runs_collapsed_to_single_space() { + let (r, e) = parse( + "impl Foo < T > for Bar {\n fn m() {\n let x = 1;\n }\n}\n", + ); + // Source tokens preserved with whitespace collapsed: `>::m`. + assert_owner(&r, &e, 2, ">::m"); + assert_abstain(&r, &e, 1); + } + + #[test] + fn missing_impl_identity_is_full_barrier_never_unqualified() { + // `impl Foo for {` has an ERROR in its signature region: the whole + // impl becomes a barrier; `m` must NOT fall back to an unqualified name. + let (r, e) = parse("impl Foo for {\n fn m() {\n let x = 1;\n }\n}\n"); + assert_abstain(&r, &e, 1); + assert_abstain(&r, &e, 2); // method inside unreadable impl + } + + #[test] + fn collapsed_impl_no_type_is_barrier_not_unqualified() { + // Bare `impl {` collapses to ERROR + statement block; the re-parsed + // `fn m` must not leak as an unqualified owner. + let (r, e) = parse("impl {\n fn m() {\n let x = 1;\n }\n}\n"); + assert_abstain(&r, &e, 1); + assert_abstain(&r, &e, 2); + } + + #[test] + fn malformed_module_no_name_is_barrier_not_leaking_to_outer() { + // `mod {` has no structural module name; tree-sitter collapses it to an + // ERROR plus an `expression_statement`-wrapped anonymous block. Nested + // inside a named function, the contained fn must NOT leak as an + // outer-qualified owner (`outer::inner`); the collapsed module's ERROR + // also degrades the enclosing function, so nothing inside may attribute. + let (r, e) = parse( + "fn outer() {\n mod {\n fn inner() {\n let x = 1;\n }\n }\n}\n", + ); + assert_abstain(&r, &e, 1); // outer def: degraded by the collapsed-mod ERROR + assert_abstain(&r, &e, 2); // collapsed mod header (ERROR) + assert_abstain(&r, &e, 3); // inner def: no `outer::inner` leak + assert_abstain(&r, &e, 4); // inner body + } + + #[test] + fn malformed_module_top_level_is_barrier() { + let (r, e) = parse("mod {\n fn inner() {\n let x = 1;\n }\n}\n"); + assert_abstain(&r, &e, 1); // collapsed mod header (ERROR) + assert_abstain(&r, &e, 2); // inner def line + assert_abstain(&r, &e, 3); // inner body + } + + #[test] + fn malformed_module_nested_function_does_not_leak_at_depth() { + // A function nested deeper inside the collapsed module must also not + // leak: no guessed child owner is emitted at any depth. + let (r, e) = parse( + "fn outer() {\n mod {\n fn a() {\n fn b() {\n let x = 1;\n }\n }\n }\n}\n", + ); + assert_abstain(&r, &e, 1); // outer degraded by the collapsed-mod ERROR + assert_abstain(&r, &e, 3); // a (collapsed) def line + assert_abstain(&r, &e, 4); // b def line: no deeper leak + assert_abstain(&r, &e, 5); // b body + } + + #[test] + fn nested_function_in_clean_blocks_stays_eligible() { + // Valid lexically nested function items inside clean control-flow/standalone + // blocks remain eligible: the enclosing named function is a valid naming + // context, so they are `outer::inner` (NOT mistaken for collapsed-mod artifacts). + let (r, e) = parse( + "fn outer() {\n { fn in_block() { let x = 1; } }\n if cond { fn in_if() { } }\n loop { fn in_loop() { } }\n match x { _ => { fn in_match() { } } }\n}\n", + ); + assert_owner(&r, &e, 2, "outer::in_block"); + assert_owner(&r, &e, 3, "outer::in_if"); + assert_owner(&r, &e, 4, "outer::in_loop"); + assert_owner(&r, &e, 5, "outer::in_match"); + } + + #[test] + fn malformed_container_nested_callables_classified_as_barriers() { + // Exhaustive extraction: every callable nested under a collapsed malformed + // mod/impl/trait must be individually classified as an AnonymousBarrier + // (never omitted, never given a guessed name). Prove classification by + // asserting a barrier region exists covering each nested function. + let (r, _) = parse( + "fn outer() {\n mod {\n fn a() {\n let x = 1;\n }\n fn b() {\n let y = 2;\n }\n }\n}\n", + ); + let barriers = r + .iter() + .filter_map(|region| match region { + OwnerRegion::AnonymousBarrier { + start_line, + end_line, + } => Some((*start_line, *end_line)), + OwnerRegion::Named(_) => None, + }) + .collect::>(); + assert!( + barriers.contains(&(3, 5)), + "fn a must be individually barriered, got {barriers:?}" + ); + assert!( + barriers.contains(&(6, 8)), + "fn b must be individually barriered, got {barriers:?}" + ); + // No named owner may leak from the malformed module. + assert!(r + .iter() + .all(|region| !matches!(region, OwnerRegion::Named(_)))); + } + + #[test] + fn malformed_impl_and_trait_nested_callables_classified_as_barriers() { + // `impl {` and `trait {` (no valid identity) recover to the same kind of + // statement-level block; their contained methods must barrier, not leak. + let (r1, _) = parse("impl {\n fn m() {\n let x = 1;\n }\n}\n"); + let b1 = r1 + .iter() + .filter_map(|region| match region { + OwnerRegion::AnonymousBarrier { + start_line, + end_line, + } => Some((*start_line, *end_line)), + OwnerRegion::Named(_) => None, + }) + .collect::>(); + assert!( + b1.contains(&(2, 4)), + "impl fn m must be barriered, got {b1:?}" + ); + assert!(r1 + .iter() + .all(|region| !matches!(region, OwnerRegion::Named(_)))); + + let (r2, _) = parse("trait {\n fn t() {\n let x = 1;\n }\n}\n"); + let b2 = r2 + .iter() + .filter_map(|region| match region { + OwnerRegion::AnonymousBarrier { + start_line, + end_line, + } => Some((*start_line, *end_line)), + OwnerRegion::Named(_) => None, + }) + .collect::>(); + assert!( + b2.contains(&(2, 4)), + "trait fn t must be barriered, got {b2:?}" + ); + assert!(r2 + .iter() + .all(|region| !matches!(region, OwnerRegion::Named(_)))); + } + + #[test] + fn unrelated_local_error_followed_by_clean_block_keeps_inner_eligible() { + // `foo(;` is an unrelated local ERROR (its ERROR is nested inside its own + // expression_statement, not a sibling of the block). The following valid + // standalone block is preserved, so `fn inner` (no ERROR overlap) stays + // eligible as `outer::inner` even though `outer` degrades from the local + // ERROR — the pinned local-error rule must not be contradicted. + let (r, e) = + parse("fn outer() {\n foo(;\n { fn inner() {\n let x = 1;\n } }\n}\n"); + assert_abstain(&r, &e, 1); // outer def degrades (local ERROR overlaps) + assert_owner(&r, &e, 3, "outer::inner"); + assert_owner(&r, &e, 4, "outer::inner"); + } + + #[test] + fn struct_error_is_not_recovery_leaves_nested_fn_eligible() { + // `struct {` has the SAME ERROR-sibling shape as a collapsed mod/impl/trait + // but its keyword is not a mod/impl/trait item-introducer. The keyword gate + // must reject it, so the clean nested `fn a` stays eligible as `outer::a` + // (rather than incorrectly abstaining as recovery-invalid). + let (r, e) = parse( + "fn outer() {\n struct {\n fn a() {\n let x = 1;\n }\n }\n}\n", + ); + assert_abstain(&r, &e, 1); // outer degrades from the struct ERROR + assert_owner(&r, &e, 3, "outer::a"); + assert_owner(&r, &e, 4, "outer::a"); + } + + #[test] + fn error_is_collapsed_container_accepts_only_item_introducers() { + // Direct proof of the keyword gate: a collapsed mod/impl/trait ERROR is + // accepted, but a stray struct/enum ERROR (same shape, different keyword) + // is rejected. + fn check(src: &str) -> bool { + fn find(n: tree_sitter::Node, found: &mut bool) { + if n.is_error() { + *found = error_is_collapsed_container(n); + return; + } + let mut c = n.walk(); + for ch in n.named_children(&mut c) { + find(ch, found); + } + } + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&outline_language(Lang::Rust).unwrap()) + .unwrap(); + let tree = parser.parse(src, None).unwrap(); + let mut found = false; + find(tree.root_node(), &mut found); + found + } + assert!(check( + "fn outer() {\n mod {\n fn a() {}\n }\n}\n" + )); + assert!(check( + "fn outer() {\n impl {\n fn m() {}\n }\n}\n" + )); + assert!(check( + "fn outer() {\n trait {\n fn t() {}\n }\n}\n" + )); + assert!(!check( + "fn outer() {\n struct {\n fn a() {}\n }\n}\n" + )); + assert!(!check( + "fn outer() {\n enum {\n fn a() {}\n }\n}\n" + )); + } + + #[test] + fn extern_body_less_signatures_barrier() { + let (r, e) = parse("extern \"C\" {\n fn c_func(x: i32);\n fn d_func() -> i32;\n}\n"); + assert_abstain(&r, &e, 1); + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + } + + #[test] + fn macro_definition_barriers_and_macro_invocation_not_guessed() { + let (r, e) = parse("macro_rules! make {\n () => { fn generated() {} };\n}\nfn real() {\n make!();\n}\n"); + // The macro-rules body must not produce a named `generated` owner. + assert_abstain(&r, &e, 1); + assert_abstain(&r, &e, 2); + assert_owner(&r, &e, 4, "real"); + assert_owner(&r, &e, 5, "real"); // macro invocation line still owned by `real` + } + + #[test] + fn local_error_degrades_overlapping_callable_and_clean_elsewhere_eligible() { + let (r, e) = parse("fn good() {\n}\nfn bad() {\n x = (\n ;\n}\n"); + assert_owner(&r, &e, 1, "good"); + assert_abstain(&r, &e, 3); // bad def line degrades + assert_abstain(&r, &e, 4); + } + + #[test] + fn distinct_top_level_functions_each_unique_narrowest() { + let (r, e) = parse("fn a() {\n let x = 1;\n}\nfn b() {\n}\n"); + assert_owner(&r, &e, 1, "a"); + assert_owner(&r, &e, 4, "b"); + } + + #[test] + fn empty_content_yields_no_regions() { + let (r, e) = parse("let x = 1;\n"); + assert!(r.is_empty()); + assert!(e.is_empty()); + } + + #[test] + fn module_level_statement_and_comment_abstain() { + let (r, e) = parse("fn one() {\n}\nlet x = 1;\n// c\nfn two() {\n}\n"); + assert_owner(&r, &e, 1, "one"); + assert_abstain(&r, &e, 3); // module-level let + assert_abstain(&r, &e, 4); // comment + assert_owner(&r, &e, 5, "two"); + } + + /// A single independent fixture, parsed on its own with 1-based local line + /// numbers. `owners` lists `(hit_line, name, start_line, end_line)` that + /// must attribute to the exact owner; `abstain` lists lines that must + /// abstain and count toward the intentional-abstention floor; `incidental` + /// lists lines that must abstain but do NOT count (module-level blanks). + struct Case { + label: &'static str, + source: &'static str, + owners: &'static [(u32, &'static str, u32, u32)], + abstain: &'static [u32], + incidental: &'static [u32], + } + + /// Slice-2 binding quality gate: a table of independent, varied fixtures. + /// Each case is parsed separately with local line numbers (no shared buffer, + /// no offset math). Counts assertions programmatically and asserts the floor + /// (`>=60` positive hits, `>=20` intentional abstentions); mechanically repeated + /// `blank`/`separator` lines never count toward the abstention floor. Every + /// positive row asserts the exact owner (`qualified_name`, `start_line`, + /// `end_line`); every abstention row asserts no attribution (0 mismatches). + + #[test] + fn rust_owner_matrix_meets_quality_gates() { + let cases: &[Case] = &[ + Case { + label: "top-level simple", + source: "fn alpha() {\n let x = 1;\n x\n}\n", + owners: &[ + (1, "alpha", 1, 4), + (2, "alpha", 1, 4), + (3, "alpha", 1, 4), + (4, "alpha", 1, 4), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level params + return", + source: "fn beta(a: i32, b: i32) -> i32 {\n a + b\n}\n", + owners: &[(1, "beta", 1, 3), (2, "beta", 1, 3), (3, "beta", 1, 3)], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level multiline body", + source: "fn gamma() {\n let s = String::new();\n for c in s.chars() {\n s.push(c);\n }\n s\n}\n", + owners: &[ + (1, "gamma", 1, 7), + (2, "gamma", 1, 7), + (3, "gamma", 1, 7), + (4, "gamma", 1, 7), + (5, "gamma", 1, 7), + (6, "gamma", 1, 7), + (7, "gamma", 1, 7), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "nested function", + source: "fn outer() {\n fn inner() {\n let x = 1;\n }\n inner()\n}\n", + owners: &[ + (1, "outer", 1, 6), + (2, "outer::inner", 2, 4), + (3, "outer::inner", 2, 4), + (4, "outer::inner", 2, 4), + (5, "outer", 1, 6), + (6, "outer", 1, 6), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level async", + source: "async fn fetch() {\n let data = load().await;\n data\n}\n", + owners: &[ + (1, "fetch", 1, 4), + (2, "fetch", 1, 4), + (3, "fetch", 1, 4), + (4, "fetch", 1, 4), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level unsafe", + source: "unsafe fn raw() {\n let x = 1;\n}\n", + owners: &[(1, "raw", 1, 3), (2, "raw", 1, 3), (3, "raw", 1, 3)], + abstain: &[], + incidental: &[], + }, + Case { + label: "inherent impl methods", + source: "struct Foo {}\nimpl Foo {\n fn a() {\n let x = 1;\n }\n fn b(&self) {\n let y = 2;\n }\n}\n\n", + owners: &[ + (3, "Foo::a", 3, 5), + (4, "Foo::a", 3, 5), + (5, "Foo::a", 3, 5), + (6, "Foo::b", 6, 8), + (7, "Foo::b", 6, 8), + (8, "Foo::b", 6, 8), + ], + abstain: &[1, 2], + incidental: &[10], + }, + Case { + label: "trait impl", + source: "impl Display for Foo {\n fn fmt(&self) {\n let x = 1;\n }\n}\n", + owners: &[(2, "::fmt", 2, 4), (3, "::fmt", 2, 4), (4, "::fmt", 2, 4)], + abstain: &[1], + incidental: &[], + }, + Case { + label: "trait default + body-less signature", + source: "trait Greet {\n fn hi();\n fn bye() {\n let x = 1;\n }\n}\n", + owners: &[(3, "Greet::bye", 3, 5), (4, "Greet::bye", 3, 5), (5, "Greet::bye", 3, 5)], + abstain: &[1, 2], + incidental: &[], + }, + Case { + label: "nested modules", + source: "mod a {\n mod b {\n fn f() {\n let x = 1;\n }\n }\n}\n", + owners: &[(3, "a::b::f", 3, 5), (4, "a::b::f", 3, 5), (5, "a::b::f", 3, 5)], + abstain: &[1, 2], + incidental: &[], + }, + Case { + label: "closure barrier", + source: "fn outer() {\n let f = |x| {\n x + 1\n };\n}\n", + owners: &[(1, "outer", 1, 5), (5, "outer", 1, 5)], + abstain: &[2, 3, 4], + incidental: &[], + }, + Case { + label: "nested closure abstains", + source: "fn factory() {\n || {\n |x| x + 1\n }\n}\n", + owners: &[(1, "factory", 1, 5), (5, "factory", 1, 5)], + abstain: &[2, 3, 4], + incidental: &[], + }, + Case { + label: "generic inherent impl", + source: "impl Stack {\n fn push(self) {\n let x = 1;\n }\n}\n", + owners: &[(2, "Stack::push", 2, 4), (3, "Stack::push", 2, 4), (4, "Stack::push", 2, 4)], + abstain: &[1], + incidental: &[], + }, + Case { + label: "extern body-less signatures", + source: "extern \"C\" {\n fn c_func(x: i32);\n fn d_func() -> i32;\n}\n", + owners: &[], + abstain: &[1, 2, 3], + incidental: &[], + }, + Case { + label: "macro_definition barrier + macro_invocation owned", + source: "macro_rules! make {\n () => { fn generated() {} };\n}\nfn real() {\n make!();\n}\n", + owners: &[(4, "real", 4, 6), (5, "real", 4, 6), (6, "real", 4, 6)], + abstain: &[1, 2], + incidental: &[], + }, + Case { + label: "module-level statement + comment", + source: "fn one() {\n}\nlet x = 1;\n// c\nfn two() {\n}\n", + owners: &[(1, "one", 1, 2), (2, "one", 1, 2), (5, "two", 5, 6), (6, "two", 5, 6)], + abstain: &[3, 4], + incidental: &[], + }, + Case { + label: "module-level blank separation", + source: "fn one() {\n}\n\nfn two() {\n}\n", + owners: &[(1, "one", 1, 2), (2, "one", 1, 2), (4, "two", 4, 5), (5, "two", 4, 5)], + abstain: &[], + incidental: &[3], + }, + Case { + label: "top-level match body", + source: "fn classify(n: i32) -> &'static str {\n match n {\n 0 => \"zero\",\n _ => \"other\",\n }\n}\n", + owners: &[ + (1, "classify", 1, 6), + (2, "classify", 1, 6), + (3, "classify", 1, 6), + (4, "classify", 1, 6), + (5, "classify", 1, 6), + (6, "classify", 1, 6), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level generic fn", + source: "fn identity(v: T) -> T {\n v\n}\n", + owners: &[(1, "identity", 1, 3), (2, "identity", 1, 3), (3, "identity", 1, 3)], + abstain: &[], + incidental: &[], + }, + Case { + label: "local error degrades callable", + source: "fn broken() {\n x = (\n return x;\n}\n", + owners: &[], + abstain: &[1, 2, 3], + incidental: &[], + }, + Case { + label: "clean callable elsewhere in partial tree", + source: "fn good() {\n}\nfn bad() {\n x = (\n ;\n}\n", + owners: &[(1, "good", 1, 2), (2, "good", 1, 2)], + abstain: &[3, 4], + incidental: &[], + }, + Case { + label: "missing impl identity is full barrier", + source: "impl Foo for {\n fn m() {\n let x = 1;\n }\n}\n", + owners: &[], + abstain: &[1, 2, 3], + incidental: &[], + }, + Case { + label: "collapsed impl no type is barrier", + source: "impl {\n fn m() {\n let x = 1;\n }\n}\n", + owners: &[], + abstain: &[1, 2, 3], + incidental: &[], + }, + Case { + label: "malformed module no name is barrier", + source: "fn outer() {\n mod {\n fn inner() {\n let x = 1;\n }\n }\n}\n", + owners: &[], + abstain: &[1, 2, 3, 4, 5, 6], + incidental: &[], + }, + ]; + + let mut positives = 0u32; + let mut abstentions = 0u32; + for case in cases { + let (regions, errors) = parse(case.source); + for &(hit_line, name, start, end) in case.owners { + positives += 1; + let owner = rust_owner_for(®ions, &errors, hit_line); + assert!( + owner.is_some(), + "[{}] line {hit_line}: expected {name}@{start}-{end}, got abstain", + case.label + ); + let owner = owner.unwrap(); + assert_eq!( + owner.qualified_name(), + name, + "[{}] line {hit_line} name", + case.label + ); + assert_eq!( + owner.start_line, start, + "[{}] line {hit_line} start", + case.label + ); + assert_eq!(owner.end_line, end, "[{}] line {hit_line} end", case.label); + } + for &line in case.abstain { + abstentions += 1; + assert_abstain(®ions, &errors, line); + } + for &line in case.incidental { + assert_abstain(®ions, &errors, line); + } + } + // Binding quality floor; cannot silently regress. Separation/blank lines + // live in `incidental` and never count toward the abstention floor. + assert!( + positives >= 60, + "positive floor: only {positives} assertions" + ); + assert!( + abstentions >= 20, + "intentional-abstention floor: only {abstentions} assertions" + ); + } + + #[test] + fn manifest_gate_verifies_kinds_exist_and_fingerprint_is_pinned() { + let v: serde_json::Value = serde_json::from_str(tree_sitter_rust::NODE_TYPES).unwrap(); + let kinds: HashSet = v + .as_array() + .unwrap() + .iter() + .filter_map(|e| e.get("type").and_then(|t| t.as_str()).map(String::from)) + .collect(); + assert!(!kinds.is_empty(), "NODE_TYPES must declare node kinds"); + // Every executable/config/bodyless kind must exist in the grammar. + for k in RUST_EXECUTABLE_CALLABLES + .iter() + .chain(RUST_CONTAINER_KINDS) + .chain(RUST_BODILESS_DECLARATIONS) + { + assert!( + kinds.contains(*k), + "manifest kind {k} missing from NODE_TYPES" + ); + } + // Inventories must be disjoint (a node cannot be two categories). + let mut all: Vec<&str> = Vec::new(); + all.extend(RUST_EXECUTABLE_CALLABLES); + all.extend(RUST_CONTAINER_KINDS); + all.extend(RUST_BODILESS_DECLARATIONS); + let uniq: HashSet<&str> = all.iter().copied().collect(); + assert_eq!( + uniq.len(), + all.len(), + "manifest inventories must be disjoint" + ); + // Fingerprint is pinned so grammar metadata changes fail here. + assert_eq!( + fnv1a(tree_sitter_rust::NODE_TYPES.as_bytes()), + RUST_NODE_TYPES_FINGERPRINT, + "tree-sitter-rust NODE_TYPES changed; re-audit the manifest" + ); + } +} diff --git a/src/lang/mod.rs b/src/lang/mod.rs index f484342..831b9c4 100644 --- a/src/lang/mod.rs +++ b/src/lang/mod.rs @@ -4,6 +4,7 @@ pub mod detection; pub(crate) mod document; pub(crate) mod js_imports; pub mod outline; +pub(crate) mod qualified; pub(crate) mod ruby; pub(crate) mod scoped_occurrences; pub mod treesitter; diff --git a/src/lang/qualified.rs b/src/lang/qualified.rs new file mode 100644 index 0000000..d4f804c --- /dev/null +++ b/src/lang/qualified.rs @@ -0,0 +1,198 @@ +//! US-064 shared qualified-symbol primitives and outline resolution. +//! +//! `Type.method` (exactly one dot with both sides non-empty) resolves a +//! member `method` defined under container / on receiver `Type`. These rules +//! are shared between the search pipeline (`src/search/symbol/definitions.rs`) +//! and the `--section` reader (`src/read/section.rs`) so receiver/container +//! interpretation never diverges between discovery and read. + +use crate::types::{Lang, OutlineEntry, OutlineKind}; + +/// Split a `Q.N` symbol query — exactly one dot, both sides non-empty. +/// Multi-dot queries (`a.b.c`) and trailing/leading dots return `None`. +pub(crate) fn split_dot_symbol_query(query: &str) -> Option<(&str, &str)> { + let mut parts = query.split('.'); + let qualifier = parts.next()?; + let plain = parts.next()?; + if parts.next().is_some() || qualifier.is_empty() || plain.is_empty() { + return None; + } + Some((qualifier, plain)) +} + +/// Normalize a Go receiver type — strip leading `*` and generic params: +/// `*Batch` -> `Batch`, `syncQueue[T]` -> `syncQueue`. Single source of truth +/// shared by search and the `--section` reader. +pub(crate) fn normalize_receiver_type(receiver: &str) -> String { + let stripped = receiver.trim().trim_start_matches('*').trim(); + stripped + .chars() + .take_while(|&c| c != '[') + .collect::() + .trim() + .to_string() +} + +/// Normalize an outline container name — Rust `impl X` entries count as `X`. +pub(crate) fn normalize_outline_container(name: &str) -> String { + name.strip_prefix("impl ") + .unwrap_or(name) + .trim() + .to_string() +} + +/// Is this outline kind a container that qualifies its members? +pub(crate) fn outline_container_kind(kind: OutlineKind) -> bool { + matches!( + kind, + OutlineKind::Class + | OutlineKind::Struct + | OutlineKind::Module + | OutlineKind::Interface + | OutlineKind::Enum + ) +} + +/// Extract a Go receiver type from a method's outline signature. Signatures +/// look like `func (b *Batch) Set(...)`. Only real methods (receiver group +/// immediately after `func`) qualify; a plain `func Set(...)` returns `None`. +/// Normalization (pointer/value/generic) flows through `normalize_receiver_type`. +fn go_receiver_from_signature(signature: &str) -> Option { + let sig = signature.trim().strip_prefix("func")?.trim_start(); + if !sig.starts_with('(') { + return None; + } + let close = sig.find(')')?; + let receiver = &sig[1..close]; + let type_text = receiver.split_whitespace().last()?; + Some(normalize_receiver_type(type_text)) +} + +/// Resolve a symbol selector (bare name or `Q.N`) against a file's outline +/// entries, returning the first matching `(start_line, end_line)` inclusive. +/// +/// Exact dotted-name precedence is preserved: a legitimate exact entry.name / +/// signature / CSS / document dotted name is resolved before `Q.N` is +/// interpreted as qualifier + plain name. Bare names resolve through the exact +/// path only. +pub(crate) fn resolve_selector_first( + entries: &[OutlineEntry], + lang: Option, + selector: &str, +) -> Option<(u32, u32)> { + if let Some((start, end)) = find_exact_in_entries(entries, selector) { + return Some((start, end)); + } + if let Some((qualifier, plain)) = split_dot_symbol_query(selector) { + if let Some((start, end)) = qualified_outline_ranges(entries, lang, qualifier, plain) + .into_iter() + .next() + { + return Some((start, end)); + } + } + None +} + +/// Recursively find an exact entry.name / signature / CSS / document match. +fn find_exact_in_entries(entries: &[OutlineEntry], symbol: &str) -> Option<(u32, u32)> { + for entry in entries { + if entry.name == symbol + || entry.signature.as_deref() == Some(symbol) + || crate::lang::css::outline_name_matches(entry.kind, &entry.name, symbol) + || crate::lang::document::outline_name_matches(entry.kind, &entry.name, symbol) + { + return Some((entry.start_line, entry.end_line)); + } + if let Some((start, end)) = find_exact_in_entries(&entry.children, symbol) { + return Some((start, end)); + } + } + None +} + +/// Resolve `Q.N` against outline entries, threading container names down into +/// children (class/struct/module/interface/enum) and matching Go methods by +/// receiver type parsed from the signature. Returns every matching range. +fn qualified_outline_ranges( + entries: &[OutlineEntry], + lang: Option, + qualifier: &str, + plain: &str, +) -> Vec<(u32, u32)> { + let mut out = Vec::new(); + collect_qualified(entries, lang, qualifier, plain, None, &mut out); + out +} + +fn collect_qualified( + entries: &[OutlineEntry], + lang: Option, + qualifier: &str, + plain: &str, + container: Option<&str>, + out: &mut Vec<(u32, u32)>, +) { + for entry in entries { + if entry.name == plain { + let container_match = container == Some(qualifier); + let receiver_match = lang == Some(Lang::Go) + && entry.kind == OutlineKind::Function + && entry + .signature + .as_deref() + .and_then(go_receiver_from_signature) + .as_deref() + == Some(qualifier); + if container_match || receiver_match { + out.push((entry.start_line, entry.end_line)); + } + } + let child_container = if outline_container_kind(entry.kind) { + Some(normalize_outline_container(&entry.name)) + } else { + container.map(str::to_string) + }; + collect_qualified( + &entry.children, + lang, + qualifier, + plain, + child_container.as_deref(), + out, + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn receiver_normalization_covers_pointer_value_and_generic() { + assert_eq!(normalize_receiver_type("*Batch"), "Batch"); + assert_eq!(normalize_receiver_type("*syncQueue[T]"), "syncQueue"); + assert_eq!(normalize_receiver_type("syncQueue[T]"), "syncQueue"); + assert_eq!(normalize_receiver_type("Queue"), "Queue"); + assert_eq!(normalize_receiver_type("*pkg[K,V]"), "pkg"); + assert_eq!(normalize_receiver_type(" *Batch "), "Batch"); + } + + #[test] + fn go_receiver_from_signature_distinguishes_method_from_function() { + assert_eq!( + go_receiver_from_signature("func (b *Batch) Set(v int)"), + Some("Batch".to_string()) + ); + assert_eq!( + go_receiver_from_signature("func (b Batch) Value()"), + Some("Batch".to_string()) + ); + assert_eq!( + go_receiver_from_signature("func (q *syncQueue[T]) Push(x T)"), + Some("syncQueue".to_string()) + ); + // A plain function has no receiver group right after `func`. + assert_eq!(go_receiver_from_signature("func Set(x int) int"), None); + } +} diff --git a/src/read/section.rs b/src/read/section.rs index 059572a..510187f 100644 --- a/src/read/section.rs +++ b/src/read/section.rs @@ -1044,7 +1044,10 @@ fn resolve_symbol(buf: &[u8], path: &Path, symbol: &str) -> Option<(usize, usize let content = std::str::from_utf8(buf).ok()?; let lang = detect_file_type(path).structural_lang()?; let entries = lang_get_outline_entries(content, lang); - find_symbol_in_entries(&entries, symbol) + // Shared US-064 resolver: exact dotted-name precedence first, then `Q.N` + // qualifier + plain-name interpretation (container / Go receiver). + crate::lang::qualified::resolve_selector_first(&entries, Some(lang), symbol) + .map(|(start, end)| (start as usize, end as usize)) } /// Collect symbol names from outline entries (recursively) with their line ranges, @@ -1094,24 +1097,6 @@ fn collect_symbol_names<'a>(entries: &'a [OutlineEntry], out: &mut Vec<(&'a str, } } -/// Recursively search for a symbol in outline entries. -fn find_symbol_in_entries(entries: &[OutlineEntry], symbol: &str) -> Option<(usize, usize)> { - for entry in entries { - if entry.name == symbol - || entry.signature.as_deref() == Some(symbol) - || crate::lang::css::outline_name_matches(entry.kind, &entry.name, symbol) - || crate::lang::document::outline_name_matches(entry.kind, &entry.name, symbol) - { - return Some((entry.start_line as usize, entry.end_line as usize)); - } - // Search children (methods inside class, etc.) - if let Some(range) = find_symbol_in_entries(&entry.children, symbol) { - return Some(range); - } - } - None -} - #[cfg(test)] mod precision_tests { use super::*; diff --git a/src/search/callers/single.rs b/src/search/callers/single.rs index e78dc99..0b0286d 100644 --- a/src/search/callers/single.rs +++ b/src/search/callers/single.rs @@ -1067,59 +1067,62 @@ pub fn search_callers_expanded_with_artifact( // (as the pointer command uses) lists the full remaining page. let list_collapse = effective_offset == 0 && precision::should_collapse_list(shown); let render_count = if list_collapse { precision::K } else { shown }; - for (i, caller) in sorted_callers.iter().take(render_count).enumerate() { - let caller_kind = detect_file_type(&caller.path) - .structural_lang() - .and_then(crate::capabilities::caller_context_kind) - .unwrap_or("fn"); - - let _ = write!( - output, - " [{caller_kind}] {} {}:{}", - caller.calling_function, - rel_nonempty(&caller.path, scope), - caller.line, + let visible: Vec<&CallerMatch> = sorted_callers.iter().take(render_count).collect(); + // Group visible call sites by file after all selection semantics. + let mut groups: Vec<(&Path, Vec<(usize, &CallerMatch)>)> = Vec::new(); + for (i, caller) in visible.iter().enumerate() { + match groups.iter_mut().find(|(p, _)| *p == caller.path.as_path()) { + Some((_, group)) => group.push((i, caller)), + None => groups.push((caller.path.as_path(), vec![(i, caller)])), + } + } + // Precompute the per-path decision: grouped when strictly smaller than + // the ungrouped inline rows, else inline (single site, tie, or loss). + // Expand windows stay attached to their call site in both shapes. + let mut grouped_by_path: std::collections::HashMap<&Path, String> = + std::collections::HashMap::new(); + for (path, group) in &groups { + if group.len() == 1 { + continue; + } + let mut grouped_candidate = String::new(); + let _ = writeln!( + grouped_candidate, + " {} [{} call sites]", + rel_nonempty(path, scope), + group.len() ); - if let Some(ref prefix) = caller.receiver { - if let Some(kind) = caller.prefix_kind { - let _ = write!(output, " prefix={prefix}({})", kind.suffix()); - } else { - let _ = write!(output, " prefix={prefix}"); - } + for (i, caller) in group { + render_caller_line(&mut grouped_candidate, caller, None, scope); + render_caller_expand(&mut grouped_candidate, caller, *i, expand); } - if let Some(argc) = caller.arg_count { - let _ = write!(output, " args={argc}"); + + let mut ungrouped_candidate = String::new(); + for (i, caller) in group { + render_caller_line(&mut ungrouped_candidate, caller, Some(path), scope); + render_caller_expand(&mut ungrouped_candidate, caller, *i, expand); } - let _ = writeln!(output); - - // Expand only when explicitly requested and we have the range. - if i < expand { - if let Some((start, end)) = caller.caller_range { - // Use cached content — no re-read needed. - // Show a compact window around the callsite (±2 lines) - // bounded by the enclosing function range. - let lines: Vec<&str> = caller.content.lines().collect(); - let window_start = caller.line.saturating_sub(2).max(start); - let window_end = (caller.line + 2).min(end); - let start_idx = (window_start as usize).saturating_sub(1); - let end_idx = (window_end as usize).min(lines.len()); - - output.push_str("\n```\n"); - - for (idx, line) in lines[start_idx..end_idx].iter().enumerate() { - let line_num = start_idx + idx + 1; - let prefix = if line_num == caller.line as usize { - "► " - } else { - " " - }; - let _ = writeln!(output, "{prefix}{line_num:4} │ {line}"); - } - output.push_str("```\n"); + if grouped_candidate.len() < ungrouped_candidate.len() { + grouped_by_path.insert(path, grouped_candidate); + } + } + // Iterate the original visible slice. Emit a profitable group once at + // its first call site; emit every other (single / unprofitable) call + // site inline at its original position with its expand window. + let mut emitted: std::collections::HashSet<&Path> = std::collections::HashSet::new(); + for (i, caller) in visible.iter().enumerate() { + let path = caller.path.as_path(); + if let Some(grouped) = grouped_by_path.get(path) { + if emitted.insert(path) { + output.push_str(grouped); } + continue; } + render_caller_line(&mut output, caller, Some(path), scope); + render_caller_expand(&mut output, caller, i, expand); } + // US-060: every collapsed item stays reachable via one pointer command. if list_collapse { let omitted = shown - precision::K; @@ -1287,6 +1290,84 @@ pub fn search_callers_expanded_with_artifact( Ok(output) } +/// Render one call-site line. When `path` is `Some`, the full `file:line` is +/// shown (single-call-site file); when `None`, a grouped child row using only +/// `:line` is rendered (the file header already carries the path). +fn render_caller_line( + output: &mut String, + caller: &CallerMatch, + path: Option<&Path>, + scope: &Path, +) { + let caller_kind = detect_file_type(&caller.path) + .structural_lang() + .and_then(crate::capabilities::caller_context_kind) + .unwrap_or("fn"); + + match path { + Some(p) => { + let _ = write!( + output, + " [{caller_kind}] {} {}:{}", + caller.calling_function, + rel_nonempty(p, scope), + caller.line, + ); + } + None => { + let _ = write!( + output, + " [{caller_kind}] {} :{}", + caller.calling_function, caller.line, + ); + } + } + + if let Some(ref prefix) = caller.receiver { + if let Some(kind) = caller.prefix_kind { + let _ = write!(output, " prefix={prefix}({})", kind.suffix()); + } else { + let _ = write!(output, " prefix={prefix}"); + } + } + if let Some(argc) = caller.arg_count { + let _ = write!(output, " args={argc}"); + } + let _ = writeln!(output); +} + +/// Render the expand window for one call site when it is within the requested +/// expand depth (`i` is the global visible index). +fn render_caller_expand(output: &mut String, caller: &CallerMatch, i: usize, expand: usize) { + if i >= expand { + return; + } + if let Some((start, end)) = caller.caller_range { + // Use cached content — no re-read needed. + // Show a compact window around the callsite (±2 lines) bounded by the + // enclosing function range. + let lines: Vec<&str> = caller.content.lines().collect(); + let window_start = caller.line.saturating_sub(2).max(start); + let window_end = (caller.line + 2).min(end); + let start_idx = (window_start as usize).saturating_sub(1); + let end_idx = (window_end as usize).min(lines.len()); + + output.push_str("\n```\n"); + + for (idx, line) in lines[start_idx..end_idx].iter().enumerate() { + let line_num = start_idx + idx + 1; + let prefix = if line_num == caller.line as usize { + "► " + } else { + " " + }; + let _ = writeln!(output, "{prefix}{line_num:4} │ {line}"); + } + + output.push_str("```\n"); + } +} + fn append_artifact_callers_grouped( output: &mut String, callers: &[CallerMatch], diff --git a/src/search/content.rs b/src/search/content.rs index fd91dab..17f5866 100644 --- a/src/search/content.rs +++ b/src/search/content.rs @@ -1,5 +1,6 @@ use std::io::Read; use std::path::Path; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use super::file_metadata; @@ -45,6 +46,9 @@ pub fn search( ) } +/// Content search. `eligible_files` is always 0 here: counting eligibility is +/// opt-in and only the explicit literal-text routes request it, so out-of-scope +/// regex/co-occurrence/expanded/inferred routes incur no per-file counter. pub fn search_with_artifact( pattern: &str, scope: &Path, @@ -52,6 +56,33 @@ pub fn search_with_artifact( context: Option<&Path>, glob: Option<&str>, artifact: ArtifactMode, +) -> Result { + search_with_artifact_impl(pattern, scope, is_regex, context, glob, artifact, false) +} + +/// Explicit literal-text search variant that also counts eligible files in the +/// same walker pass via an atomic counter. Only single-scope `--as text` Search +/// and explicit Text OR call this; every other content caller stays on +/// `search_with_artifact` with `eligible_files = 0` and no per-file lock. +pub fn search_with_artifact_counting( + pattern: &str, + scope: &Path, + is_regex: bool, + context: Option<&Path>, + glob: Option<&str>, + artifact: ArtifactMode, +) -> Result { + search_with_artifact_impl(pattern, scope, is_regex, context, glob, artifact, true) +} + +fn search_with_artifact_impl( + pattern: &str, + scope: &Path, + is_regex: bool, + context: Option<&Path>, + glob: Option<&str>, + artifact: ArtifactMode, + count_eligible: bool, ) -> Result { let matcher = if is_regex { RegexMatcher::new(pattern) @@ -64,6 +95,7 @@ pub fn search_with_artifact( })?; let matches: Mutex> = Mutex::new(Vec::new()); + let eligible_files = AtomicUsize::new(0); let walker = if artifact.enabled() { super::io::walker_with_artifact_dirs(scope, glob)? } else { @@ -73,6 +105,7 @@ pub fn search_with_artifact( walker.run(|| { let matcher = &matcher; let matches = &matches; + let eligible_files = &eligible_files; Box::new(move |entry| { let Ok(entry) = entry else { @@ -104,6 +137,13 @@ pub fn search_with_artifact( } } + // On the opt-in counting variant, tally eligibility in this existing + // content-search pass, after every walker/glob/artifact/binary/size + // guard and before I/O. Non-counting callers skip the atomic touch. + if count_eligible { + eligible_files.fetch_add(1, Ordering::Relaxed); + } + let (file_lines, mtime) = file_metadata(path); let mut file_matches = Vec::new(); @@ -150,6 +190,11 @@ pub fn search_with_artifact( let mut all_matches = matches .into_inner() .unwrap_or_else(std::sync::PoisonError::into_inner); + let eligible_files = if count_eligible { + eligible_files.load(Ordering::Relaxed) + } else { + 0 + }; rank::sort(&mut all_matches, pattern, scope, context); @@ -160,6 +205,7 @@ pub fn search_with_artifact( scope: scope.to_path_buf(), matches: all_matches, total_found: total, + eligible_files, definition_candidates: 0, name_occurrence_candidates: 0, definitions: 0, @@ -169,3 +215,43 @@ pub fn search_with_artifact( offset: 0, }) } + +#[cfg(test)] +mod tests { + use crate::ArtifactMode; + + use super::{search_with_artifact, search_with_artifact_counting}; + + #[test] + fn eligible_counting_is_opt_in() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("a.rs"), "fn one() { frobnicate }\n").unwrap(); + std::fs::write(dir.path().join("b.rs"), "fn two() { frobnicate }\n").unwrap(); + + // Non-opt-in content search must not collect an eligible denominator. + let plain = search_with_artifact( + "frobnicate", + dir.path(), + false, + None, + None, + ArtifactMode::Source, + ) + .unwrap(); + assert_eq!(plain.eligible_files, 0, "non-opt-in route abstains"); + assert_eq!(plain.total_found, 2); + + // The opt-in literal-text variant reports the eligible-file count. + let counted = search_with_artifact_counting( + "frobnicate", + dir.path(), + false, + None, + None, + ArtifactMode::Source, + ) + .unwrap(); + assert_eq!(counted.eligible_files, 2, "opt-in route counts eligibility"); + assert_eq!(counted.total_found, 2); + } +} diff --git a/src/search/cooccurrence.rs b/src/search/cooccurrence.rs index 6dc6cd4..596d037 100644 --- a/src/search/cooccurrence.rs +++ b/src/search/cooccurrence.rs @@ -108,6 +108,7 @@ pub fn search_same_line_ordered( scope: scope.to_path_buf(), matches: all_matches, total_found: total, + eligible_files: 0, definition_candidates: 0, name_occurrence_candidates: 0, definitions: 0, diff --git a/src/search/display/mod.rs b/src/search/display/mod.rs index 80513e1..a208dd3 100644 --- a/src/search/display/mod.rs +++ b/src/search/display/mod.rs @@ -97,7 +97,7 @@ pub(super) fn is_artifact_anchor_match(m: &Match) -> bool { m.is_definition && m.text.starts_with("artifact anchor ") } -fn match_evidence_source(m: &Match) -> EvidenceSource { +pub(super) fn match_evidence_source(m: &Match) -> EvidenceSource { if is_artifact_anchor_match(m) { EvidenceSource::Artifact } else if matches!( @@ -119,7 +119,7 @@ pub(super) fn document_outline_kind_label(kind: OutlineKind) -> Option<&'static } } -fn displayed_evidence_kind_label(m: &Match) -> &'static str { +pub(super) fn displayed_evidence_kind_label(m: &Match) -> &'static str { if m.in_comment { "comment occurrence" } else if m.impl_target.is_some() { @@ -152,6 +152,98 @@ pub(super) fn append_match_provenance_with_kind( pub(super) fn append_match_provenance(m: &Match, out: &mut String, indent: &str) { append_match_provenance_with_kind(m, out, indent, None); } + +/// The exact provenance tuple string a non-definition match would print, used to +/// compare against a section default for suppression. Mirrors +/// `append_match_provenance` (no kind override). +fn non_definition_provenance_tuple(m: &Match) -> String { + let source = match_evidence_source(m); + format!( + "source: {} · kind: {} · confidence: {}", + evidence_source_label_for(source), + displayed_evidence_kind_label(m), + confidence_label_for(source) + ) +} + +/// Append facet rows (Tests, Comments) grouping two or more visible hits from +/// the same file under a file header. Grouping applies only when it is strictly +/// fewer UTF-8 bytes than the ungrouped inline rows; a tie keeps ungrouped. +/// Single-hit files keep their current one-line shape. Ordering is +/// first-appearance by file, then original order. +fn append_facet_grouped_rows(out: &mut String, matches: &[Match], scope: &Path) { + use std::collections::HashMap; + use std::fmt::Write as _; + + let mut files: Vec<(&Path, Vec<&Match>)> = Vec::new(); + for m in matches { + match files.iter_mut().find(|(p, _)| *p == m.path.as_path()) { + Some((_, group)) => group.push(m), + None => files.push((m.path.as_path(), vec![m])), + } + } + + // Precompute the per-path decision: grouped when strictly smaller, else + // inline (single-hit, tie, or loss). + let mut grouped_by_path: HashMap<&Path, String> = HashMap::new(); + for (path, group) in &files { + if group.len() < 2 { + continue; + } + let mut grouped_candidate = String::new(); + let _ = write!( + grouped_candidate, + "\n {} [{} matches]", + crate::format::rel_nonempty(path, scope), + group.len() + ); + for m in group { + let atom = (*m).to_evidence_atom(); + let _ = write!( + grouped_candidate, + "\n :{} — {}", + atom.anchor().start_line(), + atom.snippet().trim() + ); + } + + let mut ungrouped_candidate = String::new(); + append_facet_ungrouped_rows(&mut ungrouped_candidate, group, scope); + + if grouped_candidate.len() < ungrouped_candidate.len() { + grouped_by_path.insert(path, grouped_candidate); + } + } + + // Iterate the original visible slice. Emit a profitable group once at its + // first occurrence; emit every other (single-hit / unprofitable) row at its + // original position so rejected/tied file rows keep their relative order. + let mut emitted: std::collections::HashSet<&Path> = std::collections::HashSet::new(); + for m in matches { + let path = m.path.as_path(); + if let Some(grouped) = grouped_by_path.get(path) { + if emitted.insert(path) { + out.push_str(grouped); + } + continue; + } + append_facet_ungrouped_rows(out, &[m], scope); + } +} + +/// Render every hit in a file as a one-line inline row (the ungrouped shape). +fn append_facet_ungrouped_rows(out: &mut String, group: &[&Match], scope: &Path) { + use std::fmt::Write as _; + for m in group { + let atom = m.to_evidence_atom(); + let _ = write!( + out, + "\n {} — {}", + atom.anchor().display_relative_to(scope), + atom.snippet().trim() + ); + } +} pub fn format_raw_result( result: &SearchResult, cache: &OutlineCache, @@ -307,11 +399,15 @@ fn format_scope_miss(expanded: &glob::GlobResult, root: &Path, pattern: &str) -> out } -/// Format match entries with optional expansion. +/// Format compact facet matches. When `hoist_provenance` is true (used only for +/// the `Matches — same package` `usages_local` facet), the most frequent +/// non-definition provenance tuple is hoisted once as a section default and +/// identical per-group provenance is suppressed; deviations print locally. fn format_compact_facet_matches( matches: &[Match], scope: &Path, cache: &OutlineCache, + hoist_provenance: bool, out: &mut String, ) { let mut definitions: IndexMap<&Path, Vec<&Match>> = IndexMap::new(); @@ -324,49 +420,158 @@ fn format_compact_facet_matches( } } - for (path, group) in definitions { + render_compact_definitions(&definitions, scope, cache, out); + + // Hoist the most frequent non-definition provenance tuple as a section + // default when requested (usages_local only). Only suppress when the + // section has >= 2 provenance carriers. The default is chosen from the + // actual rendered provenance carriers (one per path group / single row, + // i.e. `group[0]`), NOT weighted by the number of child hits — a group + // renders one provenance line regardless of how many matches it contains. + // Ties resolve by first-appearance. + let carriers: Vec<&Match> = grouped.values().map(|g| g[0]).collect(); + let suppress = if hoist_provenance && carriers.len() >= 2 { + pick_non_definition_provenance_default(&carriers) + } else { + None + }; + if let Some(tuple) = &suppress { + let _ = write!(out, "\n {tuple}"); + } + + for (path, group) in grouped { if group.len() == 1 { - semantic::format_definition_semantic_match(group[0], scope, cache, out); + format_compact_non_definition_match_suppressed( + group[0], + scope, + out, + suppress.as_deref(), + ); continue; } + let noun = non_definition_group_noun(group[0]); let _ = write!( out, - "\n {} [{} matches]", + "\n {} [{} {noun}]", rel_nonempty(path, scope), group.len() ); + append_match_provenance_if_not_default(group[0], out, " ", suppress.as_deref()); for m in group { - semantic::format_definition_semantic_match_in_file(m, cache, out); + let atom = m.to_evidence_atom(); + let kind = non_definition_label(m); + let _ = write!( + out, + "\n [{kind}] :{} | {}", + atom.anchor().start_line(), + atom.snippet().trim() + ); } } +} - for (path, group) in grouped { +/// Render the compact Definitions facet, hoisting the most frequent provenance +/// tuple as a section default and suppressing identical per-entry provenance. +/// The default is page-local and deterministic: most frequent tuple, ties by +/// first occurrence; never cached or carried across `--offset` pages. +fn render_compact_definitions( + definitions: &IndexMap<&Path, Vec<&Match>>, + scope: &Path, + cache: &OutlineCache, + out: &mut String, +) { + use std::fmt::Write as _; + + // Flatten visible definitions in first-appearance order to pick the default. + let mut flat: Vec<&Match> = Vec::new(); + for group in definitions.values() { + flat.extend(group.iter().copied()); + } + let default = pick_definition_provenance_default(&flat, cache); + + // Hoist the default tuple once below the section header only when the + // section has >= 2 visible definitions; a single definition keeps its + // current per-entry provenance byte-identical. + let suppress = default.filter(|_| flat.len() >= 2); + if let Some(tuple) = &suppress { + let _ = write!(out, "\n {tuple}"); + } + + for (path, group) in definitions { if group.len() == 1 { - format_compact_non_definition_match(group[0], scope, out); + semantic::format_definition_semantic_match_suppressed( + group[0], + scope, + cache, + out, + suppress.as_deref(), + ); continue; } - let noun = non_definition_group_noun(group[0]); let _ = write!( out, - "\n {} [{} {noun}]", + "\n {} [{} matches]", rel_nonempty(path, scope), group.len() ); - append_match_provenance(group[0], out, " "); for m in group { - let atom = m.to_evidence_atom(); - let kind = non_definition_label(m); - let _ = write!( + semantic::format_definition_semantic_match_in_file_suppressed( + m, + cache, out, - "\n [{kind}] :{} | {}", - atom.anchor().start_line(), - atom.snippet().trim() + suppress.as_deref(), ); } } } -fn format_compact_non_definition_match(m: &Match, scope: &Path, out: &mut String) { +/// Select the most frequent visible definition provenance tuple as the section +/// default; ties resolve by first occurrence. Returns `None` when there is no +/// computable tuple (e.g. all relation/impl entries), so nothing is hoisted. +fn pick_definition_provenance_default(matches: &[&Match], cache: &OutlineCache) -> Option { + pick_most_frequent( + matches + .iter() + .filter_map(|m| semantic::definition_provenance_tuple(m, cache)), + ) +} + +/// Select the most frequent non-definition provenance tuple as the section +/// default; ties resolve by first occurrence. +fn pick_non_definition_provenance_default(matches: &[&Match]) -> Option { + pick_most_frequent(matches.iter().map(|m| non_definition_provenance_tuple(m))) +} + +/// Most frequent tuple; ties resolve by first occurrence (iteration order). +fn pick_most_frequent(tuples: impl Iterator) -> Option { + let mut counts: Vec<(String, usize)> = Vec::new(); + for tuple in tuples { + match counts.iter_mut().find(|(t, _)| *t == tuple) { + Some((_, count)) => *count += 1, + None => counts.push((tuple, 1)), + } + } + let mut best: Option<(String, usize)> = None; + for (tuple, count) in counts { + if best + .as_ref() + .is_none_or(|(_, best_count)| count > *best_count) + { + best = Some((tuple, count)); + } + } + best.map(|(tuple, _)| tuple) +} + +/// Compact single-row non-definition match. When `suppress` equals the entry's +/// exact provenance tuple, the per-entry provenance line is omitted (hoisted to +/// the section default computed by the caller); a deviation prints locally. +fn format_compact_non_definition_match_suppressed( + m: &Match, + scope: &Path, + out: &mut String, + suppress: Option<&str>, +) { let atom = m.to_evidence_atom(); let kind = non_definition_label(m); let _ = write!( @@ -375,7 +580,23 @@ fn format_compact_non_definition_match(m: &Match, scope: &Path, out: &mut String atom.anchor().display_relative_to(scope), atom.snippet().trim() ); - append_match_provenance(m, out, " "); + append_match_provenance_if_not_default(m, out, " ", suppress); +} + +/// Append provenance only when it deviates from the section default (or there is +/// no default). Exactly matches `append_match_provenance` otherwise. +fn append_match_provenance_if_not_default( + m: &Match, + out: &mut String, + indent: &str, + suppress: Option<&str>, +) { + if let Some(default) = suppress { + if non_definition_provenance_tuple(m) == default { + return; + } + } + append_match_provenance(m, out, indent); } /// Groups consecutive usage matches in the same enclosing function to reduce token noise. @@ -741,7 +962,13 @@ pub(super) fn format_search_result_with_header( if !faceted.definitions.is_empty() { let _ = write!(out, "\n\n### Definitions ({})", faceted.definitions.len()); if compact_facets { - format_compact_facet_matches(&faceted.definitions, &result.scope, cache, &mut out); + format_compact_facet_matches( + &faceted.definitions, + &result.scope, + cache, + false, + &mut out, + ); } else { format_matches( &faceted.definitions, @@ -772,6 +999,7 @@ pub(super) fn format_search_result_with_header( &faceted.implementations, &result.scope, cache, + false, &mut out, ); } else { @@ -796,7 +1024,7 @@ pub(super) fn format_search_result_with_header( if !faceted.bases.is_empty() { let _ = write!(out, "\n\n### Base relationships ({})", faceted.bases.len()); if compact_facets { - format_compact_facet_matches(&faceted.bases, &result.scope, cache, &mut out); + format_compact_facet_matches(&faceted.bases, &result.scope, cache, false, &mut out); } else { format_matches( &faceted.bases, @@ -820,36 +1048,26 @@ pub(super) fn format_search_result_with_header( let _ = write!(out, "\n\n### Tests ({})", faceted.tests.len()); append_match_provenance(&faceted.tests[0], &mut out, ""); // Compact test format — one line per match, no expand budget consumed - for m in &faceted.tests { - let atom = m.to_evidence_atom(); - let _ = write!( - out, - "\n {} — {}", - atom.anchor().display_relative_to(&result.scope), - atom.snippet().trim() - ); - } + append_facet_grouped_rows(&mut out, &faceted.tests, &result.scope); } if !faceted.comments.is_empty() { let _ = write!(out, "\n\n### Comments ({})", faceted.comments.len()); append_match_provenance(&faceted.comments[0], &mut out, ""); - for m in &faceted.comments { - let atom = m.to_evidence_atom(); - let _ = write!( - out, - "\n {} — {}", - atom.anchor().display_relative_to(&result.scope), - atom.snippet().trim() - ); - } + append_facet_grouped_rows(&mut out, &faceted.comments, &result.scope); } if !faceted.usages_local.is_empty() { let header = non_definition_facet_heading(&faceted.usages_local, true); let _ = write!(out, "\n\n### {header} ({})", faceted.usages_local.len()); if compact_facets { - format_compact_facet_matches(&faceted.usages_local, &result.scope, cache, &mut out); + format_compact_facet_matches( + &faceted.usages_local, + &result.scope, + cache, + true, + &mut out, + ); } else { format_matches( &faceted.usages_local, @@ -873,7 +1091,13 @@ pub(super) fn format_search_result_with_header( let header = non_definition_facet_heading(&faceted.usages_cross, false); let _ = write!(out, "\n\n### {header} ({})", faceted.usages_cross.len()); if compact_facets { - format_compact_facet_matches(&faceted.usages_cross, &result.scope, cache, &mut out); + format_compact_facet_matches( + &faceted.usages_cross, + &result.scope, + cache, + false, + &mut out, + ); } else { format_matches( &faceted.usages_cross, @@ -951,15 +1175,18 @@ pub(super) fn format_search_result_with_header( ); } - if result.total_found > 0 { - let guidance = if has_structural_next_targets { - "read the confirmed structural target above, or use `srcwalk context ` only when you need a Flow Map or call neighborhood." - } else { - "read exact hit evidence with `srcwalk show : -C 10`." - }; + // When a confirmed-structural-target block exists, it already owns the + // next action(s); appending a generic guidance `> Next:` here would create + // a competing primary action. Only add the numeric exact-hit guidance when + // there is no structural target (text/access/name occurrence evidence). + if result.total_found > 0 && !has_structural_next_targets { append_next_action( &mut footer, - NextAction::guidance(guidance, "read exact hit evidence", 50), + NextAction::guidance( + "read exact hit evidence with `srcwalk show : -C 10`.", + "read exact hit evidence", + 50, + ), ); } @@ -1300,3 +1527,400 @@ mod us062_paths_equivalent_tests { let _ = std::fs::remove_dir_all(&base); } } + +#[cfg(test)] +mod provenance_tuple_tests { + use super::*; + use crate::types::Match; + use std::path::PathBuf; + use std::time::SystemTime; + + fn def_match(name: &str, line: u32) -> Match { + Match { + path: PathBuf::from(format!("/repo/{name}.go")), + line, + text: format!("func {name}() {{}}"), + is_definition: true, + exact: true, + file_lines: 40, + mtime: SystemTime::now(), + def_range: Some((line, line + 1)), + def_name: Some(name.to_string()), + def_weight: 80, + impl_target: None, + base_target: None, + in_comment: false, + } + } + + fn tuple_of(m: &[&Match], cache: &OutlineCache) -> Option { + pick_definition_provenance_default(m, cache) + } + + #[test] + fn uniform_ast_definitions_produce_ast_tuple() { + let cache = OutlineCache::default(); + let a = def_match("A", 1); + let b = def_match("B", 5); + let c = def_match("C", 9); + let got = tuple_of(&[&a, &b, &c], &cache).unwrap(); + assert_eq!( + got, + "source: ast · kind: definition · confidence: structural syntax" + ); + } + + #[test] + fn most_frequent_tuple_wins_and_ties_by_first_occurrence() { + let cache = OutlineCache::default(); + let ast_a = def_match("A", 1); + let ast_b = def_match("B", 5); + // A deviation: a plain (non-definition) name occurrence in a code file + // yields a text tuple different from the AST definition tuple. + let dev = Match { + path: PathBuf::from("/repo/usage.go"), + line: 3, + text: "A()".to_string(), + is_definition: false, + exact: true, + file_lines: 40, + mtime: SystemTime::now(), + def_range: None, + def_name: None, + def_weight: 0, + impl_target: None, + base_target: None, + in_comment: false, + }; + // 3 AST defs vs 2 deviations -> AST wins (most frequent). + let ast_c = def_match("C", 9); + let got = tuple_of(&[&ast_a, &ast_b, &ast_c, &dev, &dev], &cache).unwrap(); + assert_eq!( + got, + "source: ast · kind: definition · confidence: structural syntax" + ); + // Single deviation only -> the deviation tuple is the default (honest). + let dev_only = tuple_of(&[&dev], &cache).unwrap(); + assert_eq!( + dev_only, + "source: text · kind: name occurrence · confidence: text evidence" + ); + } + + #[test] + fn impl_base_entries_are_excluded_from_default() { + let cache = OutlineCache::default(); + let a = def_match("A", 1); + let impl_match = Match { + impl_target: Some("Trait".to_string()), + ..def_match("B", 5) + }; + let got = tuple_of(&[&a, &impl_match], &cache).unwrap(); + assert_eq!( + got, + "source: ast · kind: definition · confidence: structural syntax" + ); + } + + fn name_occurrence_match(path: &str, line: u32) -> Match { + Match { + path: PathBuf::from(path), + line, + text: "a.A()".to_string(), + is_definition: false, + exact: true, + file_lines: 40, + mtime: SystemTime::now(), + def_range: None, + def_name: None, + def_weight: 0, + impl_target: None, + base_target: None, + in_comment: false, + } + } + + #[test] + fn non_definition_default_picks_most_frequent_usage_tuple() { + // usages_local provenance hoist: uniform name occurrences pick the + // text/name-occurrence tuple as the default. + let a = name_occurrence_match("/repo/x.go", 1); + let b = name_occurrence_match("/repo/y.go", 5); + let c = name_occurrence_match("/repo/z.go", 9); + let got = pick_non_definition_provenance_default(&[&a, &b, &c]).unwrap(); + assert_eq!( + got, + "source: text · kind: name occurrence · confidence: text evidence" + ); + } + + #[test] + fn non_definition_deviation_keeps_own_tuple() { + // A document/text deviation (different tuple) among usages_local is not + // folded into the default; the majority name-occurrence tuple wins. + let a = name_occurrence_match("/repo/x.go", 1); + let b = name_occurrence_match("/repo/y.go", 5); + // Deviation: a comment occurrence (kind differs). + let dev = Match { + in_comment: true, + ..name_occurrence_match("/repo/x.go", 3) + }; + let got = pick_non_definition_provenance_default(&[&a, &b, &dev]).unwrap(); + assert_eq!( + got, + "source: text · kind: name occurrence · confidence: text evidence" + ); + // Single deviation only -> the deviation tuple is the (honest) default. + let dev_only = pick_non_definition_provenance_default(&[&dev]).unwrap(); + assert_eq!( + dev_only, + "source: text · kind: comment occurrence · confidence: text evidence" + ); + } + + #[test] + fn conditional_grouping_tie_keeps_ungrouped() { + // A 2-hit short-path group is a tie/no-gain: the inline shape is chosen. + let out = ""; + let _ = out; + // Compare the two candidate byte lengths directly for a short path. + let path = std::path::Path::new("/repo/a.go"); + let scope = std::path::Path::new("/repo"); + let mut grouped = String::new(); + let mut ungrouped = String::new(); + let m1 = name_occurrence_match("/repo/a.go", 1); + let m2 = name_occurrence_match("/repo/a.go", 2); + let group: Vec<&Match> = vec![&m1, &m2]; + let _ = write!( + grouped, + "\n {} [{} matches]\n :1 — t\n :2 — t", + crate::format::rel_nonempty(path, scope), + 2 + ); + for m in &group { + let atom = m.to_evidence_atom(); + let _ = write!( + ungrouped, + "\n {} — {}", + atom.anchor().display_relative_to(scope), + atom.snippet().trim() + ); + } + // Short path: grouped is not strictly smaller, so ungrouped wins. + assert!( + grouped.len() >= ungrouped.len(), + "short-path 2-hit group should not be strictly smaller" + ); + } + + fn artifact_anchor_match(name: &str, line: u32) -> Match { + Match { + path: PathBuf::from(format!("/repo/bundle.min.js")), + line, + text: format!("artifact anchor export {name}"), + is_definition: true, + exact: true, + file_lines: 40, + mtime: SystemTime::now(), + def_range: Some((line, line + 1)), + def_name: Some(name.to_string()), + def_weight: 80, + impl_target: None, + base_target: None, + in_comment: false, + } + } + + #[test] + fn artifact_anchor_default_hoisted_once() { + // Blocker fix: an artifact anchor's definition provenance tuple is + // `source: artifact · kind: anchor ...`, so when it is the section + // default it must be suppressed per-entry (printed once as the default). + let cache = OutlineCache::default(); + let a1 = artifact_anchor_match("A1", 1); + let a2 = artifact_anchor_match("A2", 1); + let a3 = artifact_anchor_match("A3", 1); + let a4 = artifact_anchor_match("A4", 1); + let a5 = artifact_anchor_match("A5", 1); + let a6 = artifact_anchor_match("A6", 1); + // All artifact anchors share one provenance tuple -> it is the default. + let default = tuple_of(&[&a1, &a2, &a3, &a4, &a5, &a6], &cache).unwrap(); + assert_eq!( + default, + "source: artifact · kind: anchor · confidence: artifact-level" + ); + // Rendering the compact Definitions facet must not repeat the default + // after every anchor entry. + let mut map: IndexMap<&Path, Vec<&Match>> = IndexMap::new(); + map.insert(a1.path.as_path(), vec![&a1, &a2, &a3, &a4, &a5, &a6]); + let scope = Path::new("/repo"); + let mut out = String::new(); + render_compact_definitions(&map, scope, &cache, &mut out); + assert_eq!( + out.matches("kind: anchor · confidence: artifact-level") + .count(), + 1, + "artifact anchor default must be printed once (hoisted), got:\n{out}" + ); + } + + #[test] + fn artifact_anchor_mixed_keeps_deviation_tuple() { + // Blocker fix: when the section default is an artifact-anchor tuple, a + // non-anchor definition deviation must still print its own tuple. + let cache = OutlineCache::default(); + let a1 = artifact_anchor_match("A1", 1); + let a2 = artifact_anchor_match("A2", 1); + let a3 = artifact_anchor_match("A3", 1); + let a4 = artifact_anchor_match("A4", 1); + let a5 = artifact_anchor_match("A5", 1); + // Deviation: a Go AST definition (different provenance tuple). + let go = Match { + path: PathBuf::from("/repo/lib.go"), + line: 5, + text: "func Lib() {}".to_string(), + is_definition: true, + exact: true, + file_lines: 40, + mtime: SystemTime::now(), + def_range: Some((5, 6)), + def_name: Some("Lib".to_string()), + def_weight: 80, + impl_target: None, + base_target: None, + in_comment: false, + }; + // 5 anchors > 1 AST -> anchor tuple is the default. + let mut map: IndexMap<&Path, Vec<&Match>> = IndexMap::new(); + map.insert(a1.path.as_path(), vec![&a1, &a2, &a3, &a4, &a5]); + map.insert(go.path.as_path(), vec![&go]); + let scope = Path::new("/repo"); + let mut out = String::new(); + render_compact_definitions(&map, scope, &cache, &mut out); + // The hoisted default (anchor) appears once as the section default. + assert_eq!( + out.matches("kind: anchor · confidence: artifact-level") + .count(), + 1, + "anchor default should be printed once, got:\n{out}" + ); + // The Go definition deviation keeps its own tuple. + assert!( + out.contains("source: ast · kind: definition · confidence: structural syntax"), + "AST deviation must keep its own provenance tuple, got:\n{out}" + ); + } + + #[test] + fn usages_local_default_uses_carriers_not_child_count() { + // Blocker fix: the usages_local default is chosen from the actual + // rendered provenance carriers (one `group[0]` per path group), NOT + // weighted by the number of child hits. Here one path group has many + // name-occurrence children but there are two comment-only singleton + // carriers: the comment tuple wins as the default even though the + // child count favors name occurrences. + let cache = OutlineCache::default(); + // Carrier A: a path group with 6 name-occurrence children (only its + // `group[0]` is a carrier). + let mut group_a = Vec::new(); + for i in 0..6 { + group_a.push(name_occurrence_match("/repo/a.go", i + 1)); + } + // Carriers B and C: two comment-occurrence singletons (each a carrier). + let b = Match { + in_comment: true, + path: PathBuf::from("/repo/b.go"), + ..name_occurrence_match("/repo/b.go", 1) + }; + let c = Match { + in_comment: true, + path: PathBuf::from("/repo/c.go"), + ..name_occurrence_match("/repo/c.go", 1) + }; + // Carriers = [a.go -> name, b.go -> comment, c.go -> comment]. + // The comment tuple wins 2 vs 1 (carrier-based). + let mut map: IndexMap<&Path, Vec<&Match>> = IndexMap::new(); + map.insert( + group_a.first().unwrap().path.as_path(), + group_a.iter().collect(), + ); + map.insert(b.path.as_path(), vec![&b]); + map.insert(c.path.as_path(), vec![&c]); + let carriers: Vec<&Match> = map.values().map(|g| g[0]).collect(); + let default = pick_non_definition_provenance_default(&carriers).unwrap(); + assert_eq!( + default, "source: text · kind: comment occurrence · confidence: text evidence", + "carrier-majority default should be the comment tuple" + ); + // The name-occurrence group (deviation) keeps its own tuple. + let non_def_default = pick_non_definition_provenance_default(&[&group_a[0]]).unwrap(); + assert_eq!( + non_def_default, + "source: text · kind: name occurrence · confidence: text evidence" + ); + } + + #[test] + fn interleaved_ungrouped_rows_preserve_original_order() { + // Blocker fix: when a multi-hit file's group ISN'T profitable, its rows + // must stay at their original positions in the visible slice rather than + // being clustered together. Order A1, B1, A2 (A unprofitable short path) + // must render A1, B1, A2 — not A1, A2, B1. + let scope = Path::new("/repo"); + // A is a short-path 2-hit group (grouping ties -> stays inline). + let a1 = name_occurrence_match("/repo/a.go", 1); + let a2 = name_occurrence_match("/repo/a.go", 3); + // B is an unrelated single-hit file. + let b1 = name_occurrence_match("/repo/b.go", 2); + // Visible slice order: A1, B1, A2. + let matches = vec![a1, b1, a2]; + let mut out = String::new(); + append_facet_grouped_rows(&mut out, &matches, scope); + // a.go is short (2 chars) -> grouping is a tie/loss, so its rows stay + // inline at their original positions: a.go:1, b.go:2, a.go:3. + let a1_pos = out.find("a.go:1").unwrap(); + let b1_pos = out.find("b.go:2").unwrap(); + let a2_pos = out.find("a.go:3").unwrap(); + assert!( + a1_pos < b1_pos && b1_pos < a2_pos, + "ungrouped rows must keep original interleaved order A1,B1,A2, got:\n{out}" + ); + assert!( + !out.contains("a.go [2 matches]"), + "short-path 2-hit group must not be grouped, got:\n{out}" + ); + } + + #[test] + fn interleaved_profitable_group_emits_at_first_occurrence() { + // Blocker fix: a PROFITABLE group emits its whole group at the first + // occurrence of its path, consuming later matches. Order A1, B1, A2 where + // A is a long-path multi-hit profitable group renders A[2], B1 — the A + // group at A1's position, B1 after. + let scope = Path::new("/repo"); + // A uses a long path so grouping is strictly smaller. + let a1 = name_occurrence_match( + "/repo/very/long/path/that/makes/grouping/profitable/a.go", + 1, + ); + let a2 = name_occurrence_match( + "/repo/very/long/path/that/makes/grouping/profitable/a.go", + 3, + ); + let b1 = name_occurrence_match("/repo/b.go", 2); + let matches = vec![a1, b1, a2]; + let mut out = String::new(); + append_facet_grouped_rows(&mut out, &matches, scope); + // The A group is emitted at A1's position (before B1); A2 is consumed. + let group_pos = out.find("[2 matches]").unwrap(); + let b1_pos = out.find("b.go:2").unwrap(); + assert!( + group_pos < b1_pos, + "profitable group must emit at first occurrence before B1, got:\n{out}" + ); + assert!( + out.contains(":1") && out.contains(":3"), + "profitable group must contain both child rows, got:\n{out}" + ); + } +} diff --git a/src/search/display/semantic.rs b/src/search/display/semantic.rs index f212a0c..1228405 100644 --- a/src/search/display/semantic.rs +++ b/src/search/display/semantic.rs @@ -47,6 +47,14 @@ pub(in crate::search) struct SemanticChild { pub(super) struct ContextTarget { pub(super) start_line: u32, pub(super) end_line: u32, + /// Parser-backed symbol selector (bare name or `Type.method`) that resolves + /// back to this target's range, or the closest stable selector when + /// `symbol_backed` is false. + pub(super) selector: String, + /// True when `selector` round-trips to exactly `(start_line, end_line)` in + /// this file, so the `show path --section ` footer is safe to + /// emit. False targets fall back to a numeric range command. + pub(super) symbol_backed: bool, } pub(super) fn context_target_for_match(m: &Match, cache: &OutlineCache) -> Option { @@ -60,20 +68,32 @@ pub(super) fn context_target_for_match(m: &Match, cache: &OutlineCache) -> Optio return None; } + let entries = structured_outline_entries(&m.path, cache)?; + if m.is_definition { - if let Some(candidate) = semantic_candidate_for_match(m, cache) { + let range = m.def_range.unwrap_or((m.line, m.line)); + if let Some(candidate) = best_semantic_candidate(&entries, m) { if candidate.kind == OutlineKind::Function { - return Some(ContextTarget { - start_line: candidate.start_line, - end_line: candidate.end_line, - }); + // US-064: `m.def_name` retains the parser-backed `Q.N` form for + // qualified matches, so the footer carries the same selector + // the discover query used instead of reconstructing it. + let selector = m.def_name.clone().unwrap_or_else(|| candidate.name.clone()); + return Some(build_target( + &m.path, + &entries, + candidate.start_line, + candidate.end_line, + selector, + )); } } - if let Some((start_line, end_line)) = function_definition_range_from_outline(m, cache) { - return Some(ContextTarget { - start_line, - end_line, - }); + if let Some((start_line, end_line)) = + find_function_definition_range(&entries, range, m.def_name.as_deref()) + { + let selector = m.def_name.clone().unwrap_or_else(|| start_line.to_string()); + return Some(build_target( + &m.path, &entries, start_line, end_line, selector, + )); } return None; } @@ -82,12 +102,37 @@ pub(super) fn context_target_for_match(m: &Match, cache: &OutlineCache) -> Optio return None; } - let entries = structured_outline_entries(&m.path, cache)?; let candidate = best_enclosing_function(&entries, m.line)?; - Some(ContextTarget { - start_line: candidate.start_line, - end_line: candidate.end_line, - }) + let selector = candidate.name.clone(); + Some(build_target( + &m.path, + &entries, + candidate.start_line, + candidate.end_line, + selector, + )) +} + +/// Build a `ContextTarget` from a candidate range and parser-backed selector. +/// `symbol_backed` is true only when the selector resolves back to exactly this +/// range (round-trip check), so the footer never emits a symbol command that +/// would read a different body. +fn build_target( + path: &Path, + entries: &[OutlineEntry], + start_line: u32, + end_line: u32, + selector: String, +) -> ContextTarget { + let lang = crate::lang::detect_file_type(path).structural_lang(); + let symbol_backed = crate::lang::qualified::resolve_selector_first(entries, lang, &selector) + == Some((start_line, end_line)); + ContextTarget { + start_line, + end_line, + selector, + symbol_backed, + } } pub(super) fn format_definition_semantic_match( @@ -97,15 +142,58 @@ pub(super) fn format_definition_semantic_match( out: &mut String, ) { let path = rel_nonempty(&m.path, scope); - format_definition_semantic_match_with_path(m, Some(&path), cache, out, " "); + format_definition_semantic_match_with_path(m, Some(&path), cache, out, " ", None); +} + +/// Compact-facet variant: when `suppress` is the exact provenance tuple of the +/// entry, the per-entry provenance line is omitted (hoisted to the section +/// default computed by the caller). +pub(super) fn format_definition_semantic_match_suppressed( + m: &Match, + scope: &Path, + cache: &OutlineCache, + out: &mut String, + suppress: Option<&str>, +) { + let path = rel_nonempty(&m.path, scope); + format_definition_semantic_match_with_path(m, Some(&path), cache, out, " ", suppress); } -pub(super) fn format_definition_semantic_match_in_file( +pub(super) fn format_definition_semantic_match_in_file_suppressed( m: &Match, cache: &OutlineCache, out: &mut String, + suppress: Option<&str>, ) { - format_definition_semantic_match_with_path(m, None, cache, out, " "); + format_definition_semantic_match_with_path(m, None, cache, out, " ", suppress); +} + +/// Compute the exact provenance tuple string `source · kind · confidence` for a +/// definition match, mirroring `append_match_provenance_with_kind`. Returns +/// `None` for relation/impl/base artifacts that do not print a provenance line. +pub(super) fn definition_provenance_tuple(m: &Match, cache: &OutlineCache) -> Option { + if m.impl_target.is_some() || m.base_target.is_some() { + return None; + } + let source = super::match_evidence_source(m); + let kind_override = if super::is_artifact_anchor_match(m) { + Some("anchor") + } else if matches!( + crate::lang::detect_file_type(&m.path), + crate::types::FileType::Document(_) + ) && semantic_candidate_for_match(m, cache).is_some() + { + let candidate = semantic_candidate_for_match(m, cache).unwrap(); + super::document_outline_kind_label(candidate.kind) + } else { + None + }; + Some(format!( + "source: {} · kind: {} · confidence: {}", + super::evidence_source_label_for(source), + kind_override.unwrap_or_else(|| super::displayed_evidence_kind_label(m)), + super::confidence_label_for(source) + )) } fn format_definition_semantic_match_with_path( @@ -114,6 +202,7 @@ fn format_definition_semantic_match_with_path( cache: &OutlineCache, out: &mut String, indent: &str, + suppress: Option<&str>, ) { let atom = m.to_evidence_atom(); if super::is_artifact_anchor_match(m) { @@ -126,7 +215,7 @@ fn format_definition_semantic_match_with_path( "\n{indent}[anchor] {label} {}", format_loc(path, atom.anchor().start_line()) ); - super::append_match_provenance_with_kind(m, out, indent, Some("anchor")); + append_provenance_if_not_default(m, out, indent, Some("anchor"), cache, suppress); return; } if m.impl_target.is_some() { @@ -172,7 +261,7 @@ fn format_definition_semantic_match_with_path( } else { None }; - super::append_match_provenance_with_kind(m, out, indent, kind_override); + append_provenance_if_not_default(m, out, indent, kind_override, cache, suppress); for child in candidate.children.iter().take(2) { let _ = write!( out, @@ -201,7 +290,7 @@ fn format_definition_semantic_match_with_path( } else { let _ = write!(out, "\n{indent}[{kind}] {}", format_range(path, start, end)); } - super::append_match_provenance(m, out, indent); + append_provenance_if_not_default(m, out, indent, None, cache, suppress); } else { let kind = if m.impl_target.is_some() { "impl" @@ -221,11 +310,29 @@ fn format_definition_semantic_match_with_path( format_loc(path, atom.anchor().start_line()) ); } - super::append_match_provenance(m, out, indent); + append_provenance_if_not_default(m, out, indent, None, cache, suppress); } append_artifact_definition_snippet(m, out); } +/// Append a match provisioning line unless it equals the supplied section +/// default tuple (hoisted provenance). +fn append_provenance_if_not_default( + m: &Match, + out: &mut String, + indent: &str, + kind_override: Option<&'static str>, + cache: &OutlineCache, + suppress: Option<&str>, +) { + if let Some(default) = suppress { + if definition_provenance_tuple(m, cache).as_deref() == Some(default) { + return; + } + } + super::append_match_provenance_with_kind(m, out, indent, kind_override); +} + fn format_loc(path: Option<&str>, line: u32) -> String { match path { Some(path) => format!("{path}:{line}"), @@ -413,13 +520,6 @@ fn collect_semantic_candidates( } } -fn function_definition_range_from_outline(m: &Match, cache: &OutlineCache) -> Option<(u32, u32)> { - let range = m.def_range?; - let wanted = m.def_name.as_deref(); - let entries = structured_outline_entries(&m.path, cache)?; - find_function_definition_range(&entries, range, wanted) -} - fn find_function_definition_range( entries: &[OutlineEntry], range: (u32, u32), diff --git a/src/search/display/structural_targets.rs b/src/search/display/structural_targets.rs index ca625e5..d71cfd3 100644 --- a/src/search/display/structural_targets.rs +++ b/src/search/display/structural_targets.rs @@ -14,10 +14,28 @@ use crate::types::SearchResult; use super::semantic; use super::RenderedSourceLines; +/// Header line for the confirmed-target block. It teaches the classification +/// (run the printed `Next` command; symbol when stable, numeric as a safe +/// fallback) instead of claiming every target is symbol-addressed. +const CONFIRMED_TARGETS_HEADER: &str = + "## Confirmed structural targets - run the printed Next command (symbol when stable; numeric as fallback)"; + +/// Single line emitted after any numeric-fallback targets. Kept at block level +/// so several fallbacks in one output share one explanation instead of +/// repeating it after every target. +const NUMERIC_FALLBACK_NOTE: &str = + "> Note: numeric fallback - no unique symbol selector resolves to the exact body, so the printed range is the safe read."; + struct StructuralTarget { path: PathBuf, start_line: u32, end_line: u32, + /// Parser-backed symbol selector (bare name or `Type.method`) that resolves + /// back to this target's range when `symbol_backed` is true. + selector: String, + /// True when the footer may emit `show path --section ` safely + /// (the selector round-trips to exactly this range in this file). + symbol_backed: bool, } impl StructuralTarget { @@ -63,7 +81,8 @@ pub(super) fn append_structural_next_targets( return false; } - let actions = show_actions_for_targets(&targets, &result.scope, rendered_lines); + let (actions, fallback_count) = + show_actions_for_targets(&targets, &result.scope, rendered_lines); let rendered = render_next_actions(&actions); if rendered.is_empty() { let target = &targets[0]; @@ -86,8 +105,15 @@ pub(super) fn append_structural_next_targets( } return true; } - out.push_str("\n\n## Confirmed structural targets\n"); + out.push('\n'); + out.push('\n'); + out.push_str(CONFIRMED_TARGETS_HEADER); + out.push('\n'); out.push_str(&rendered); + if fallback_count > 0 { + out.push('\n'); + out.push_str(NUMERIC_FALLBACK_NOTE); + } true } @@ -110,6 +136,8 @@ fn collect_structural_targets( path: m.path.clone(), start_line: target.start_line, end_line: target.end_line, + selector: target.selector, + symbol_backed: target.symbol_backed, }); if targets.len() == 3 { break; @@ -118,11 +146,13 @@ fn collect_structural_targets( targets } +/// Build the confirmed-target actions plus how many of them are numeric +/// fallbacks (used to emit a single block-level explanation). fn show_actions_for_targets( targets: &[StructuralTarget], scope: &Path, rendered: &RenderedSourceLines, -) -> Vec { +) -> (Vec, usize) { let ranges = targets .iter() .map(|target| (target.start_line, target.end_line)) @@ -137,91 +167,85 @@ fn show_actions_for_targets( .collect::>(); if kept_targets.is_empty() { - return Vec::new(); + return (Vec::new(), 0); } - // US-060b: split wide (>W-line) targets out of every offer path so each - // anchors to `path:line (label)` + an `expand: srcwalk show path:A-B` - // command instead of being offered bare. The expand command preserves the - // exact range (section form for comma paths), so the full range is always - // exactly one printed command away. + // US-060b: split wide (>W-line) targets out so their numeric range anchors + // to a bounded `> anchor:` evidence line instead of being offered bare. let (wide, narrow): (Vec<_>, Vec<_>) = kept_targets.into_iter().partition(|target| { precision::should_anchor_range((target.end_line - target.start_line + 1) as usize) }); let mut actions = Vec::new(); + let mut fallback_count = 0; + for target in &wide { - actions.push(NextAction::guidance( - anchored_offer(target, scope, "read confirmed structural source target"), - "read confirmed structural source target", - 10, - )); + if target.symbol_backed { + // Stable parser-backed selector: the symbol command is the primary + // action; the numeric range is non-action evidence metadata. + actions.push( + NextAction::guidance( + show_command_for_target(target, scope), + "read confirmed structural source target", + 10, + ) + .with_preamble([anchor_line(target, scope)]), + ); + } else { + // Ambiguous / non-round-tripping selector: numeric fallback stays + // the primary action and is honestly labeled at block level. + fallback_count += 1; + actions.push(NextAction::guidance( + show_command_for_target(target, scope), + "read confirmed structural source target", + 10, + )); + } } - if narrow.len() == 1 { - let target = narrow[0]; + // Each narrow target is offered as its own read command. Symbol-backed + // targets use `show --section `; the rest fall back to a + // numeric range and are labeled at block level. + for (index, target) in narrow.iter().enumerate() { + if !target.symbol_backed { + fallback_count += 1; + } actions.push(NextAction::from_evidence( show_command_for_target(target, scope), "read confirmed structural source target", - 10, + 10 + index as u16, EvidenceSource::Ast, target.anchor(), )); - } else if !narrow.is_empty() - && narrow - .iter() - .any(|target| target.requires_section_form(scope)) - { - for (index, target) in narrow.iter().enumerate() { - actions.push(NextAction::from_evidence( - show_command_for_target(target, scope), - "read confirmed structural source target", - 10 + index as u16, - EvidenceSource::Ast, - target.anchor(), - )); - } - } else if !narrow.is_empty() { - let joined = narrow - .iter() - .map(|target| target.location_arg_relative_to(scope)) - .collect::>() - .join(","); - actions.push(NextAction::guidance( - format!("srcwalk show {}", quote_or_placeholder(&joined)), - "read confirmed structural source targets", - 10, - )); } - actions + (actions, fallback_count) } -/// US-060b: build the anchored offer for a wide target — a single-line -/// `path:start (label)` anchor plus an `> expand:` command that retrieves the -/// full range in exactly one printed command (preserving section form for comma -/// paths). Rendered as two `> `-prefixed lines by `render_next_actions`. -fn anchored_offer(target: &StructuralTarget, scope: &Path, reason: &str) -> String { - let label = truncate_label(reason); - let path = format::rel_nonempty(&target.path, scope); +/// US-060b: keep the numeric range of a wide target visible as evidence while +/// making clear it is a bounded preview, not the body address. Rendered as a +/// plain (non-action) line using only the START line, so it never looks like a +/// hint that could be re-read as a numeric range. The symbol command on the +/// `> Next:` line is the recommended action. +fn anchor_line(target: &StructuralTarget, scope: &Path) -> String { format!( - "{}:{} ({label})\n> expand: {}", - path, - target.start_line, - show_command_for_target(target, scope) + " evidence anchor: {} (bounded preview; not the body address)", + Anchor::line(&target.path, target.start_line).display_relative_to(scope) ) } -/// Keep the anchor label short enough for a single-line `path:line (label)`. -fn truncate_label(reason: &str) -> &str { - let trimmed = reason.trim(); - if trimmed.len() <= 40 { - trimmed - } else { - &trimmed[..trimmed.floor_char_boundary(40)] +fn show_command_for_target(target: &StructuralTarget, scope: &Path) -> String { + // Symbol form: `show --section ` for a round-tripping + // parser-backed selector. The path is quoted separately so a comma inside + // a quoted path never becomes a multi-target command. + if target.symbol_backed { + return format!( + "srcwalk show {} --section {}", + quote_or_placeholder(&target.path_arg_relative_to(scope)), + quote_or_placeholder(&target.selector) + ); } -} -fn show_command_for_target(target: &StructuralTarget, scope: &Path) -> String { + // Numeric fallback for exceptional targets with no stable symbol selector. if target.requires_section_form(scope) { return format!( "srcwalk show {} --section {}", @@ -249,6 +273,23 @@ mod tests { path: PathBuf::from(path), start_line, end_line, + selector: String::new(), + symbol_backed: false, + } + } + + fn symbol_target( + path: &str, + start_line: u32, + end_line: u32, + selector: &str, + ) -> StructuralTarget { + StructuralTarget { + path: PathBuf::from(path), + start_line, + end_line, + selector: selector.to_string(), + symbol_backed: true, } } @@ -269,22 +310,49 @@ mod tests { #[test] fn batched_show_quotes_combined_space_targets() { let scope = Path::new(""); - let actions = show_actions_for_targets( + let (actions, _) = show_actions_for_targets( &[target("a file.rs", 1, 1), target("b file.rs", 2, 2)], scope, &RenderedSourceLines::default(), ); - assert_eq!(actions.len(), 1); - assert_eq!( - actions[0].command(), - "srcwalk show 'a file.rs:1-1,b file.rs:2-2'" - ); + // Distinct narrow numeric targets stay on their own lines. + assert_eq!(actions.len(), 2); + assert_eq!(actions[0].command(), "srcwalk show 'a file.rs:1-1'"); + assert_eq!(actions[1].command(), "srcwalk show 'b file.rs:2-2'"); + } + + #[test] + fn symbol_target_renders_symbol_section_command() { + let scope = Path::new(""); + let command = show_command_for_target(&symbol_target("lib.rs", 1, 3, "target"), scope); + assert_eq!(command, "srcwalk show lib.rs --section target"); + } + + #[test] + fn symbol_target_preserves_qualified_selector() { + let scope = Path::new(""); + let command = show_command_for_target(&symbol_target("batch.go", 3, 3, "Batch.Set"), scope); + assert_eq!(command, "srcwalk show batch.go --section Batch.Set"); + } + + #[test] + fn symbol_target_quotes_space_path_and_selector() { + let scope = Path::new(""); + let command = show_command_for_target(&symbol_target("a file.rs", 1, 3, "my fn"), scope); + assert_eq!(command, "srcwalk show 'a file.rs' --section 'my fn'"); + } + + #[test] + fn symbol_target_keeps_comma_path_quoted() { + let scope = Path::new(""); + let command = show_command_for_target(&symbol_target("a,file.rs", 1, 3, "target"), scope); + assert_eq!(command, "srcwalk show 'a,file.rs' --section target"); } #[test] fn batched_show_splits_comma_paths() { let scope = Path::new(""); - let actions = show_actions_for_targets( + let (actions, _) = show_actions_for_targets( &[target("a,file.rs", 1, 1), target("b.rs", 2, 2)], scope, &RenderedSourceLines::default(), @@ -299,7 +367,7 @@ mod tests { #[test] fn over_cap_singleton_emits_no_action() { - let actions = show_actions_for_targets( + let (actions, _) = show_actions_for_targets( &[target("large.rs", 1, 201)], Path::new(""), &RenderedSourceLines::default(), @@ -310,7 +378,7 @@ mod tests { #[test] fn over_cap_ranges_skip_and_keep_contiguous_priorities() { let scope = Path::new(""); - let actions = show_actions_for_targets( + let (actions, fallbacks) = show_actions_for_targets( &[ target("a,file.rs", 1, 150), target("b,file.rs", 1, 51), @@ -321,58 +389,154 @@ mod tests { ); // The 201-line `b` range is dropped by the line cap; the surviving `a` - // (150) and `c` (50) are both >W so they anchor to path:line + expand. + // (150) and `c` (50) are both >W and non-symbol-backed, so they become + // numeric fallback commands (section form for comma paths). assert_eq!(actions.len(), 2); + assert_eq!(fallbacks, 2); assert_eq!( actions[0].command(), - "a,file.rs:1 (read confirmed structural source target)\n> expand: srcwalk show 'a,file.rs' --section 1-150" + "srcwalk show 'a,file.rs' --section 1-150" ); assert_eq!(actions[0].rank(), 10); assert_eq!( actions[1].command(), - "c,file.rs:1 (read confirmed structural source target)\n> expand: srcwalk show 'c,file.rs' --section 1-50" + "srcwalk show 'c,file.rs' --section 1-50" ); assert_eq!(actions[1].rank(), 10); } #[test] - fn wide_range_offered_anchors_but_w_boundary_does_not() { + fn wide_boundary_stays_plain_offer() { let scope = Path::new(""); // Width W (40) is the boundary: exactly 40 lines stays a plain offer. - let boundary = show_actions_for_targets( + let (actions, fallbacks) = show_actions_for_targets( &[target("p.rs", 1, 40)], scope, &RenderedSourceLines::default(), ); - assert_eq!(boundary.len(), 1); + assert_eq!(actions.len(), 1); + assert_eq!(fallbacks, 1); + assert_eq!(actions[0].command(), "srcwalk show p.rs:1-40"); + } + + #[test] + fn wide_numeric_fallback_uses_numeric_command_primary() { + let scope = Path::new(""); + // Width W+1 (41) >W, non-symbol-backed: numeric command is the primary + // action (no separate anchor, no `> expand:`). + let (actions, fallbacks) = show_actions_for_targets( + &[target("p.rs", 1, 41)], + scope, + &RenderedSourceLines::default(), + ); + assert_eq!(actions.len(), 1); + assert_eq!(fallbacks, 1); + assert_eq!(actions[0].command(), "srcwalk show p.rs:1-41"); assert!( - !boundary[0].command().contains("expand:"), - "width-40 target must not anchor: {:?}", - boundary[0].command() + !actions[0].command().contains("expand:"), + "{:?}", + actions[0].command() ); - assert_eq!(boundary[0].command(), "srcwalk show p.rs:1-40"); + } - // Width W+1 (41) must anchor to `path:line (label)` + `> expand:`. - let wide = show_actions_for_targets( - &[target("p.rs", 1, 41)], + #[test] + fn wide_symbol_backed_promotes_symbol_command_to_primary() { + let scope = Path::new(""); + // Wide symbol-backed target: the symbol command is the primary action + // and the numeric range is non-action evidence metadata. + let (actions, fallbacks) = show_actions_for_targets( + &[symbol_target( + "semantic.rs", + 156, + 272, + "format_definition_semantic_match_with_path", + )], + scope, + &RenderedSourceLines::default(), + ); + assert_eq!(actions.len(), 1); + assert_eq!(fallbacks, 0); + assert_eq!( + actions[0].command(), + "srcwalk show semantic.rs --section format_definition_semantic_match_with_path" + ); + assert_eq!( + actions[0].reason(), + "read confirmed structural source target" + ); + } + + #[test] + fn wide_symbol_backed_anchor_is_non_action_metadata() { + let scope = Path::new(""); + let (actions, _) = show_actions_for_targets( + &[symbol_target("semantic.rs", 156, 272, "Type.method")], scope, &RenderedSourceLines::default(), ); - assert_eq!(wide.len(), 1); + let preamble = &actions[0]; + // The action's command is the symbol command; the anchor is plain + // metadata using the START line only, never a competing action or a + // repeat of the full body range. + assert_eq!( + preamble.command(), + "srcwalk show semantic.rs --section Type.method" + ); + let rendered = render_next_actions(std::slice::from_ref(preamble)); + assert_eq!( + rendered, + " evidence anchor: semantic.rs:156 (bounded preview; not the body address)\n> Next: srcwalk show semantic.rs --section Type.method" + ); + assert!(!rendered.contains("expand:"), "{rendered}"); + assert!(!rendered.contains("> Next: semantic.rs"), "{rendered}"); assert!( - wide[0] - .command() - .contains("> expand: srcwalk show p.rs:1-41"), - "width-41 target must anchor with an expand command: {:?}", - wide[0].command() + !rendered.contains("156-272"), + "anchor must not repeat the full range: {rendered}" ); assert!( - wide[0].command().starts_with("p.rs:1 ("), - "{:?}", - wide[0].command() + !rendered.starts_with('>'), + "anchor must be plain metadata, not action-shaped: {rendered}" ); } + #[test] + fn narrow_symbol_backed_has_exactly_one_symbol_next() { + let scope = Path::new(""); + let (actions, fallbacks) = show_actions_for_targets( + &[symbol_target("lib.rs", 1, 3, "helper")], + scope, + &RenderedSourceLines::default(), + ); + assert_eq!(actions.len(), 1); + assert_eq!(fallbacks, 0); + let rendered = render_next_actions(&actions); + assert_eq!(rendered, "> Next: srcwalk show lib.rs --section helper"); + assert!(!rendered.contains("expand:"), "{rendered}"); + assert!(!rendered.contains(":1-3"), "{rendered}"); + } + + #[test] + fn header_teaches_classification() { + assert!(CONFIRMED_TARGETS_HEADER.contains("run the printed Next command")); + assert!(CONFIRMED_TARGETS_HEADER.contains("symbol when stable")); + assert!(CONFIRMED_TARGETS_HEADER.contains("numeric as fallback")); + } + + #[test] + fn numeric_fallback_note_is_single_block_level() { + // Two non-symbol-backed wide targets -> one shared fallback note at + // block level, not repeated per target. + let (actions, fallbacks) = show_actions_for_targets( + &[target("a.rs", 1, 41), target("b.rs", 1, 41)], + Path::new(""), + &RenderedSourceLines::default(), + ); + assert_eq!(actions.len(), 2); + assert_eq!(fallbacks, 2); + assert!(NUMERIC_FALLBACK_NOTE.starts_with("> Note:")); + assert!(NUMERIC_FALLBACK_NOTE.contains("numeric fallback")); + } + #[test] fn fully_rendered_target_is_suppressed_but_partial_is_kept() { let scope = Path::new(""); @@ -384,14 +548,14 @@ mod tests { ); // Full containment (1-6) -> offer suppressed. - let full = show_actions_for_targets(&[target("p.rs", 1, 6)], scope, &rendered); + let (full, _) = show_actions_for_targets(&[target("p.rs", 1, 6)], scope, &rendered); assert!( full.is_empty(), "fully-rendered target must be suppressed: {full:?}" ); // Partial overlap (1-3 all rendered, 4-8 not) -> offer kept. - let partial = show_actions_for_targets(&[target("p.rs", 1, 8)], scope, &rendered); + let (partial, _) = show_actions_for_targets(&[target("p.rs", 1, 8)], scope, &rendered); assert_eq!(partial.len(), 1, "partial overlap must keep the offer"); assert!( partial[0].command().contains('8'), @@ -400,7 +564,26 @@ mod tests { ); // No overlap (20-25) -> offer kept. - let none = show_actions_for_targets(&[target("p.rs", 20, 25)], scope, &rendered); + let (none, _) = show_actions_for_targets(&[target("p.rs", 20, 25)], scope, &rendered); assert_eq!(none.len(), 1); } + + #[test] + fn mixed_symbol_and_fallback_emit_one_primary_action_each() { + let scope = Path::new(""); + let (actions, fallbacks) = show_actions_for_targets( + &[ + symbol_target("a.rs", 1, 3, "stableOne"), + target("b.rs", 1, 41), + ], + scope, + &RenderedSourceLines::default(), + ); + // One canonical primary action per emitted target. + assert_eq!(actions.len(), 2); + assert_eq!(fallbacks, 1); + let rendered = render_next_actions(&actions); + assert_eq!(rendered.matches("> Next:").count(), 2, "{rendered}"); + assert!(!rendered.contains("expand:"), "{rendered}"); + } } diff --git a/src/search/low_signal.rs b/src/search/low_signal.rs new file mode 100644 index 0000000..f507df1 --- /dev/null +++ b/src/search/low_signal.rs @@ -0,0 +1,207 @@ +use crate::types::SearchResult; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct LowSignalTermStats { + pub(crate) term: String, + pub(crate) total_matches: usize, + pub(crate) matched_files: usize, + pub(crate) eligible_files: usize, +} + +pub(crate) fn low_signal_term_stats(term: &str, result: &SearchResult) -> LowSignalTermStats { + let matched_files = result + .matches + .iter() + .map(|matched| &matched.path) + .collect::>() + .len(); + LowSignalTermStats { + term: term.to_string(), + total_matches: result.total_found, + matched_files, + eligible_files: result.eligible_files, + } +} + +/// v1 thresholds are evidence-derived, not a universal semantic classifier. +/// Validation date: 2026-08-12. Pinned repositories: Ktor +/// `a8d8038939d788547b807acbc580609e7603d9dd`, Spring Framework +/// `68e6acd37ed0c12e395ef96d170971028e727383`, Symfony +/// `3b11ffbe2520436b0951974d1993dc2144f91dd3`, and dotnet/runtime +/// `656d1d6f42b140e751f65a2ec58e5066b54e1f54`. The closest observed separator +/// was runtime `GetTypeInfo` near 1.26% versus runtime `execute` near 1.92%, a +/// 0.66 percentage-point margin. Retuning any constant requires new +/// cross-repository evidence, an updated matrix and boundary tests, and reviewer +/// approval. +const MIN_MATCHES: usize = 400; +const MIN_MATCHED_FILES: usize = 150; +const SPREAD_SCALE: u128 = 1_000; +const MIN_SPREAD: u128 = 15; + +pub(crate) fn low_signal_term_advisory(stats: &LowSignalTermStats) -> Option { + if stats.eligible_files == 0 + || stats.total_matches < MIN_MATCHES + || stats.matched_files < MIN_MATCHED_FILES + { + return None; + } + + let matched_scaled = (stats.matched_files as u128).checked_mul(SPREAD_SCALE)?; + let eligible_scaled = (stats.eligible_files as u128).checked_mul(MIN_SPREAD)?; + if matched_scaled < eligible_scaled { + return None; + } + + Some(format!( + "> Note: {} matches across {} of {} eligible files for `{}`; if this spread is not intentional, consider `overview`, a narrower term or scope, or a structural route.", + format_count(stats.total_matches), + format_count(stats.matched_files), + format_count(stats.eligible_files), + escape_term(&stats.term), + )) +} + +/// Put shared advisory lines into the trailing footer immediately before the +/// existing generic `> Next:` action. The budget layer preserves this footer. +pub(crate) fn insert_low_signal_advisories(output: String, advisories: &[String]) -> String { + if advisories.is_empty() { + return output; + } + let notes = advisories.join("\n"); + let Some((body, footer)) = crate::format::split_trailing_footer(&output) else { + return format!("{}\n\n{notes}", output.trim_end()); + }; + + let footer = footer.trim(); + // Insert before the generic `> Next:` action when present; otherwise append + // at the footer end so pre-existing caveats/notes stay first (contract: existing + // evidence first, advisory before generic Next). + let insertion = footer.find("> Next:").unwrap_or(footer.len()); + let (before, after) = footer.split_at(insertion); + let before = before.trim_end(); + let after = after.trim_start(); + let mut rendered_footer = String::new(); + if !before.is_empty() { + rendered_footer.push_str(before); + rendered_footer.push('\n'); + } + rendered_footer.push_str(¬es); + if !after.is_empty() { + rendered_footer.push('\n'); + rendered_footer.push_str(after); + } + format!("{}\n\n{rendered_footer}", body.trim_end()) +} + +fn format_count(value: usize) -> String { + let digits = value.to_string(); + let mut rendered = String::with_capacity(digits.len() + digits.len() / 3); + for (index, character) in digits.chars().enumerate() { + if index > 0 && (digits.len() - index).is_multiple_of(3) { + rendered.push(','); + } + rendered.push(character); + } + rendered +} + +fn escape_term(term: &str) -> String { + let mut escaped = String::with_capacity(term.len()); + for character in term.chars() { + match character { + '\\' => escaped.push_str("\\\\"), + '`' => escaped.push_str("\\`"), + '\n' => escaped.push_str("\\n"), + '\r' => escaped.push_str("\\r"), + '\t' => escaped.push_str("\\t"), + character if character.is_control() => { + use std::fmt::Write as _; + let _ = write!(escaped, "\\u{{{:x}}}", character as u32); + } + character => escaped.push(character), + } + } + escaped +} + +#[cfg(test)] +mod tests { + use super::{insert_low_signal_advisories, low_signal_term_advisory, LowSignalTermStats}; + + fn stats( + total_matches: usize, + matched_files: usize, + eligible_files: usize, + ) -> LowSignalTermStats { + LowSignalTermStats { + term: "execute".to_string(), + total_matches, + matched_files, + eligible_files, + } + } + + #[test] + fn threshold_boundaries_are_inclusive() { + assert!(low_signal_term_advisory(&stats(399, 150, 1_000)).is_none()); + assert!(low_signal_term_advisory(&stats(400, 149, 1_000)).is_none()); + assert!(low_signal_term_advisory(&stats(400, 150, 10_001)).is_none()); + assert_eq!( + low_signal_term_advisory(&stats(400, 150, 10_000)).as_deref(), + Some("> Note: 400 matches across 150 of 10,000 eligible files for `execute`; if this spread is not intentional, consider `overview`, a narrower term or scope, or a structural route.") + ); + } + + #[test] + fn zero_eligible_files_never_trigger() { + assert!(low_signal_term_advisory(&stats(10_000, 10_000, 0)).is_none()); + } + + #[test] + fn repeated_calls_are_byte_identical_and_wording_is_conditional() { + let stats = stats(452, 171, 3_046); + let first = low_signal_term_advisory(&stats).unwrap(); + assert_eq!(first, low_signal_term_advisory(&stats).unwrap()); + assert!(first.contains("if this spread is not intentional")); + for forbidden in ["stop", "must", "avoid"] { + assert!(!first.to_ascii_lowercase().contains(forbidden), "{first}"); + } + } + + #[test] + fn term_escaping_keeps_the_note_single_line_and_quoted() { + let mut stats = stats(400, 150, 10_000); + stats.term = "a`b\\c\n".to_string(); + let note = low_signal_term_advisory(&stats).unwrap(); + assert!(note.contains("for `a\\`b\\\\c\\n`;"), "{note}"); + assert!(!note.contains('\n')); + } + + #[test] + fn advisory_inserts_before_existing_next_footer() { + let output = "body\n\n> Caveat: existing\n\n> Next: continue".to_string(); + let note = low_signal_term_advisory(&stats(400, 150, 10_000)).unwrap(); + let rendered = insert_low_signal_advisories(output, &[note]); + assert!( + rendered.contains("> Caveat: existing\n> Note:"), + "{rendered}" + ); + assert!(rendered.find("> Note:").unwrap() < rendered.find("> Next:").unwrap()); + } + + #[test] + fn advisory_appends_after_existing_notes_when_no_next() { + // Footer with existing caveat + note but no `> Next:`. The low-signal + // note must go after the existing note, not before it. + let out = "body\n\n> Caveat: existing\n\n> Note: prior note\n".to_string(); + let note = low_signal_term_advisory(&stats(400, 150, 10_000)).unwrap(); + let rendered = insert_low_signal_advisories(out, &[note]); + let caveat = rendered.find("> Caveat:").unwrap(); + let prior = rendered.find("> Note: prior note").unwrap(); + let low = rendered.rfind("> Note: 400 matches").unwrap(); + assert!( + caveat < prior && prior < low, + "existing evidence must precede advisory:\n{rendered}" + ); + } +} diff --git a/src/search/mod.rs b/src/search/mod.rs index 3b3b8c5..b85c65c 100644 --- a/src/search/mod.rs +++ b/src/search/mod.rs @@ -11,6 +11,7 @@ mod filter; pub mod glob; mod go_imports; pub mod io; +mod low_signal; pub mod pagination; pub mod rank; pub mod siblings; @@ -40,6 +41,9 @@ pub use self::display::{ pub use self::filter::apply_general_filter; pub(crate) use self::io::{file_metadata, read_file_bytes}; use self::io::{parse_pattern, walker}; +pub(crate) use self::low_signal::{ + insert_low_signal_advisories, low_signal_term_advisory, low_signal_term_stats, +}; use self::pagination::paginate; use self::display::{ @@ -526,22 +530,28 @@ pub fn search_symbol_glob_raw_with_artifact( } /// Raw content search — returns structured result for programmatic inspection. -pub fn search_content_raw( +/// `eligible_files` is always 0 (counting is opt-in). +pub fn search_content_raw_with_artifact( query: &str, scope: &Path, glob: Option<&str>, + artifact: ArtifactMode, ) -> Result { - search_content_raw_with_artifact(query, scope, glob, ArtifactMode::Source) + let (pattern, is_regex) = parse_pattern(query); + content::search_with_artifact(pattern, scope, is_regex, None, glob, artifact) } -pub fn search_content_raw_with_artifact( +/// Raw literal-text search that also counts eligible files in the same pass. +/// Only the explicit single-scope `--as text` and Text OR routes call this; +/// every other content caller stays on `search_content_raw_with_artifact`. +pub(crate) fn search_content_raw_with_artifact_counting( query: &str, scope: &Path, glob: Option<&str>, artifact: ArtifactMode, ) -> Result { let (pattern, is_regex) = parse_pattern(query); - content::search_with_artifact(pattern, scope, is_regex, None, glob, artifact) + content::search_with_artifact_counting(pattern, scope, is_regex, None, glob, artifact) } /// Raw regex search — returns structured result for programmatic inspection. diff --git a/src/search/pagination.rs b/src/search/pagination.rs index a317cfa..39a68ba 100644 --- a/src/search/pagination.rs +++ b/src/search/pagination.rs @@ -67,6 +67,7 @@ mod tests { hit(3, false, false), ], total_found: 3, + eligible_files: 0, definition_candidates: 1, name_occurrence_candidates: 1, definitions: 1, diff --git a/src/search/symbol.rs b/src/search/symbol.rs index e54e325..651657c 100644 --- a/src/search/symbol.rs +++ b/src/search/symbol.rs @@ -7,10 +7,9 @@ mod glob_search; mod suggest; mod usages; +pub(crate) use crate::lang::qualified::{normalize_receiver_type, split_dot_symbol_query}; use comments::tag_comment_matches; use definitions::find_definitions_with_artifact; -pub(crate) use definitions::normalize_receiver_type; -pub(crate) use definitions::split_dot_symbol_query; #[cfg(test)] use definitions::{find_artifact_anchor_defs, find_defs_treesitter}; use usages::find_usages_with_artifact; @@ -122,6 +121,7 @@ pub fn search_with_artifact( query: query.to_string(), scope: scope.to_path_buf(), total_found: total, + eligible_files: 0, definition_candidates: def_count, name_occurrence_candidates: merged .iter() diff --git a/src/search/symbol/batch.rs b/src/search/symbol/batch.rs index 8ad2988..e18d39b 100644 --- a/src/search/symbol/batch.rs +++ b/src/search/symbol/batch.rs @@ -84,6 +84,7 @@ pub(super) fn search_batch( query: (*query).to_string(), scope: scope.to_path_buf(), total_found: total, + eligible_files: 0, definition_candidates: def_count, name_occurrence_candidates: merged .iter() diff --git a/src/search/symbol/definitions.rs b/src/search/symbol/definitions.rs index ef118c9..c12189b 100644 --- a/src/search/symbol/definitions.rs +++ b/src/search/symbol/definitions.rs @@ -6,6 +6,10 @@ use std::time::SystemTime; use crate::error::SrcwalkError; use crate::lang::detect_file_type; use crate::lang::outline::outline_language; +use crate::lang::qualified::{ + normalize_outline_container, normalize_receiver_type, outline_container_kind, + split_dot_symbol_query, +}; use crate::lang::treesitter::{ definition_weight, elixir_definition_weight, extract_base_list_targets, extract_definition_name, extract_elixir_definition_name, extract_impl_trait, extract_impl_type, @@ -307,18 +311,6 @@ fn outline_entry_matches_query(entry: &OutlineEntry, query: &str) -> bool { || crate::lang::document::outline_name_matches(entry.kind, &entry.name, query) } -/// US-064: split a `Q.N` symbol query — exactly one dot, both sides non-empty. -/// Multi-dot queries (`a.b.c`) and trailing/leading dots return `None`. -pub(crate) fn split_dot_symbol_query(query: &str) -> Option<(&str, &str)> { - let mut parts = query.split('.'); - let qualifier = parts.next()?; - let plain = parts.next()?; - if parts.next().is_some() || qualifier.is_empty() || plain.is_empty() { - return None; - } - Some((qualifier, plain)) -} - /// US-064: extract a Go receiver type from a `method_declaration` node. /// The receiver is the first `parameter_list` child; its type is the last /// named child of the receiver's `parameter_declaration`. @@ -343,19 +335,6 @@ fn go_receiver_type_from_node(node: tree_sitter::Node, lines: &[&str]) -> Option Some(normalize_receiver_type(&text)) } -/// US-064: normalize a Go receiver type — strip leading `*` and generic -/// params: `*Batch` → `Batch`, `syncQueue[T]` → `syncQueue`. Shared with the -/// display layer's ambiguity assist (single source of truth). -pub(crate) fn normalize_receiver_type(receiver: &str) -> String { - let stripped = receiver.trim().trim_start_matches('*').trim(); - stripped - .chars() - .take_while(|&c| c != '[') - .collect::() - .trim() - .to_string() -} - /// US-064: container name if `node` is a container (class/struct/object/ /// impl/module/enum). Rust `impl X` / `impl T for X` counts as `X` /// (`extract_impl_type` returns the implemented type). @@ -399,26 +378,6 @@ fn qualified_def_matches( && go_receiver_type_from_node(node, lines).as_deref() == Some(qualifier) } -/// US-064: is this outline kind a container that qualifies its members? -fn outline_container_kind(kind: OutlineKind) -> bool { - matches!( - kind, - OutlineKind::Class - | OutlineKind::Struct - | OutlineKind::Module - | OutlineKind::Interface - | OutlineKind::Enum - ) -} - -/// US-064: normalize an outline container name — `impl X` entries count as `X`. -fn normalize_outline_container(name: &str) -> String { - name.strip_prefix("impl ") - .unwrap_or(name) - .trim() - .to_string() -} - fn collect_outline_defs( entries: &[OutlineEntry], query: &str, diff --git a/src/search/symbol/glob_search.rs b/src/search/symbol/glob_search.rs index e676d10..926efe7 100644 --- a/src/search/symbol/glob_search.rs +++ b/src/search/symbol/glob_search.rs @@ -137,6 +137,7 @@ pub(super) fn search_name_glob_with_artifact( scope: scope.to_path_buf(), matches: merged, total_found: total, + eligible_files: 0, definition_candidates: total, name_occurrence_candidates: 0, definitions: total, diff --git a/src/types.rs b/src/types.rs index a326998..c9953d5 100644 --- a/src/types.rs +++ b/src/types.rs @@ -94,7 +94,7 @@ pub struct RegexCoOccurrenceQuery { /// Provider-owned language identity for removable capability modules. #[allow(dead_code)] -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct ProviderLang { id: LangId, label: &'static str, @@ -121,7 +121,7 @@ impl ProviderLang { /// Programming language, carried through the type system so downstream /// code never re-detects. Built-in IDs stay closed; provider extensions use /// `Lang::Provider` while the compiler still checks built-in coverage. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Lang { Rust, TypeScript, @@ -176,7 +176,7 @@ impl FileType { /// What the output contains — shown in the header bracket. #[allow(dead_code)] -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct ProviderViewMode { id: ViewModeId, label: &'static str, @@ -317,6 +317,9 @@ pub struct SearchResult { pub scope: PathBuf, pub matches: Vec, pub total_found: usize, + /// Number of files that survived content-search eligibility guards before matching. + /// This denominator is unpaginated and remains stable through filtering and pagination. + pub(crate) eligible_files: usize, /// Definition candidates before pagination; retained so ambiguity stays visible on every page. pub definition_candidates: usize, /// Text-matched name occurrences before pagination; excludes literal text-search matches. @@ -377,7 +380,7 @@ pub struct OutlineEntry { } #[allow(dead_code)] -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct ProviderOutlineKind { id: OutlineKindId, outline_label: &'static str, @@ -426,7 +429,7 @@ impl ProviderOutlineKind { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum OutlineKind { Import, Function, diff --git a/tests/intent_first_cli.rs b/tests/intent_first_cli.rs index 67186ce..273572b 100644 --- a/tests/intent_first_cli.rs +++ b/tests/intent_first_cli.rs @@ -1,7 +1,9 @@ use std::fs; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::Command; +const OWNER_LINK_ZERO_EDGE: &str = "No direct name-level call evidence among hit owners. Dynamic dispatch, DI, callbacks, and protocol wiring are not ruled out."; + fn srcwalk() -> Command { Command::new(env!("CARGO_BIN_EXE_srcwalk")) } @@ -1059,30 +1061,22 @@ fn discover_match_any_text_comma_terms_are_literal_or() { } #[test] -fn discover_match_any_text_or_large_output_rolls_up_by_file() { - let dir = temp_repo("discover_text_or_file_rollup"); +fn discover_text_or_go_owners_render_mechanical_call_evidence() { + let dir = temp_repo("discover_text_or_go_owner_edges"); fs::write( dir.join("feature.go"), - "alpha here\nbeta here\ngamma here\nalpha beta gamma\n", - ) - .unwrap(); - fs::write( - dir.join("feature_test.go"), - "alpha test\nbeta test\ngamma test\n", + "package feature\ntype DB struct{}\nfunc (d *DB) Apply() { /* alpha */ }\nfunc (d *DB) Set() { /* beta */ d.Apply() }\n", ) .unwrap(); - fs::write(dir.join("other.go"), "alpha only\n").unwrap(); let output = srcwalk() .args([ "discover", - "alpha,beta,gamma,missing", + "alpha,beta", "--match", "any", "--as", "text", - "--limit", - "2", "--scope", ]) .arg(&dir) @@ -1091,99 +1085,80 @@ fn discover_match_any_text_or_large_output_rolls_up_by_file() { assert!( output.status.success(), - "discover text OR rollup failed:\n{}", + "{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - let files_idx = stdout.find("## Files ranked by term coverage").unwrap(); - let terms_idx = stdout.find("## Terms").unwrap(); - assert!( - files_idx < terms_idx, - "file rollup must lead term summary:\n{stdout}" - ); - assert!(stdout.contains("feature.go — 3 terms"), "{stdout}"); - assert!(stdout.contains("terms: alpha("), "{stdout}"); + assert!(stdout.contains("[owner DB.Apply@3-3]"), "{stdout}"); + assert!(stdout.contains("[owner DB.Set@4-4]"), "{stdout}"); + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); assert!( - stdout.contains("> Next: srcwalk show feature.go --section 1-4 -C 10"), + stdout.contains("DB.Set calls Apply@feature.go:4"), "{stdout}" ); + assert!(stdout.contains("candidate DB.Apply@:3-3"), "{stdout}"); assert!( - stdout.contains("missing — 0/0 matches, 0 files"), + stdout.contains("structural owner and mechanically filtered"), "{stdout}" ); - assert!(stdout.contains("omitted by per-term limit"), "{stdout}"); - assert!( - !stdout.contains("## alpha —"), - "compact mode should not dump term-first hit blocks:\n{stdout}" - ); + assert!(!stdout.contains(OWNER_LINK_ZERO_EDGE), "{stdout}"); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_text_or_rollup_next_read_uses_bounded_hit_windows() { - let dir = temp_repo("discover_text_or_bounded_windows"); - let mut lines = vec!["filler".to_string(); 1_900]; - lines[65] = "rpc StopContainer has a timeout contract".to_string(); - lines[70] = "container is forcibly killed after the timeout".to_string(); - lines[1177] = "message StopContainerRequest {".to_string(); - lines[1182] = "int64 timeout = 2;".to_string(); - lines[1376] = "int64 unrelated_timeout = 1;".to_string(); - lines[1850] = "timeout for another request".to_string(); - fs::write(dir.join("api.proto"), lines.join("\n")).unwrap(); +fn discover_text_or_go_owner_render_caps_edge_bullets_at_ten() { + let dir = temp_repo("discover_text_or_go_owner_cap"); + // 12 candidate methods on the same receiver; Run calls each once so the + // builder emits 12 edges but the renderer must cap the bullet list at 10. + let mut src = String::from("package p\ntype DB struct{}"); + for i in 0..12 { + src.push_str(&format!("\nfunc (d *DB) M{i}() {{ /* body */ }}")); + } + src.push_str("\nfunc (d *DB) Run() {\n"); + for i in 0..12 { + src.push_str(&format!(" d.M{i}()\n")); + } + src.push('}'); + fs::write(dir.join("cap.go"), src).unwrap(); let output = srcwalk() .args([ - "discover", - "StopContainerRequest,timeout,forcibly killed", - "--match", - "any", - "--as", - "text", - "--scope", + "discover", "body,Run", "--match", "any", "--as", "text", "--scope", ]) .arg(&dir) .output() .unwrap(); - assert!( output.status.success(), - "discover text OR rollup failed:\n{}", + "{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - assert!(stdout.contains("windows: :66-71 terms="), "{stdout}"); - assert!(stdout.contains(":1178-1183 terms="), "{stdout}"); - assert!( - stdout.contains("--section '66-71,1178-1183' -C 10"), - "bounded windows should be batched into one exact read:\n{stdout}" - ); - assert!( - !stdout.contains("api.proto:66-1851") && !stdout.contains("api.proto:66-1852"), - "must not suggest sparse min-max reads:\n{stdout}" - ); - assert!( - stdout.contains("hit-window proximity is literal navigation evidence"), - "{stdout}" - ); + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); + let bullets = stdout + .lines() + .filter(|l| l.starts_with("- [") && l.contains(" calls ")) + .count(); + assert_eq!(bullets, 10, "{stdout}"); + assert!(!stdout.contains("M11"), "{stdout}"); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_text_or_rollup_keeps_rare_terms_represented() { - let dir = temp_repo("discover_text_or_rare_terms"); - let mut lines = vec!["filler".to_string(); 1_100]; - lines[9] = "common term first".to_string(); - lines[199] = "common term second".to_string(); - lines[399] = "common term third".to_string(); - lines[999] = "rare term only evidence".to_string(); - fs::write(dir.join("notes.md"), lines.join("\n")).unwrap(); +fn discover_text_or_go_owner_only_prints_exact_zero_edge_line_once() { + let dir = temp_repo("discover_text_or_go_owner_zero_edge"); + fs::write( + dir.join("feature.go"), + "package feature\nfunc First() { /* alpha */ }\nfunc Second() { /* beta */ }\n", + ) + .unwrap(); let output = srcwalk() .args([ "discover", - "common,rare,missing", + "alpha,beta", "--match", "any", "--as", @@ -1196,39 +1171,33 @@ fn discover_text_or_rollup_keeps_rare_terms_represented() { assert!( output.status.success(), - "discover text OR rollup failed:\n{}", + "{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); + assert_eq!(stdout.matches(OWNER_LINK_ZERO_EDGE).count(), 1, "{stdout}"); + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); assert!( - stdout.contains("--section '10-10,1000-1000' -C 10"), - "next read must balance common and rare terms instead of only common clusters:\n{stdout}" - ); - assert!( - stdout.contains("missing — 0/0 matches, 0 files"), + stdout.contains("structural owner and mechanically filtered"), "{stdout}" ); - assert!( - !stdout.contains("notes.md:10-1000"), - "must not suggest sparse min-max reads:\n{stdout}" - ); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_text_or_rollup_splits_transitive_near_gap_chains() { - let dir = temp_repo("discover_text_or_chained_gaps"); - let mut lines = vec!["filler".to_string(); 180]; - for line in [1usize, 22, 43, 64, 85, 106] { - lines[line - 1] = "chain term".to_string(); - } - fs::write(dir.join("chain.txt"), lines.join("\n")).unwrap(); +fn discover_text_or_single_go_owner_keeps_caveat_without_zero_edge_line() { + let dir = temp_repo("discover_text_or_go_single_owner"); + fs::write( + dir.join("feature.go"), + "package feature\nfunc First() { /* alpha beta */ }\n", + ) + .unwrap(); let output = srcwalk() .args([ "discover", - "chain,term,missing", + "alpha,beta", "--match", "any", "--as", @@ -1241,40 +1210,39 @@ fn discover_text_or_rollup_splits_transitive_near_gap_chains() { assert!( output.status.success(), - "discover text OR rollup failed:\n{}", + "{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("[owner First@2-2]"), "{stdout}"); + assert!(!stdout.contains(OWNER_LINK_ZERO_EDGE), "{stdout}"); assert!( - stdout.contains("windows: :1-64 terms=chain(4), term(4); :85-106 terms=chain(2), term(2)"), - "chained near-gap hits must split at the cumulative window cap:\n{stdout}" - ); - assert!(stdout.contains("--section '1-64,85-106' -C 10"), "{stdout}"); - assert!( - !stdout.contains("chain.txt:1-106"), - "must not re-create broad min-max span through transitive merging:\n{stdout}" + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" ); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_text_or_rollup_quotes_next_read_paths() { - let dir = temp_repo("discover_text_or_space_path"); +fn discover_text_or_owner_caveat_survives_budget_truncation() { + let dir = temp_repo("discover_text_or_go_owner_budget"); fs::write( - dir.join("space file.md"), - "alpha beta gamma\nalpha beta gamma\nalpha beta gamma\n", + dir.join("feature.go"), + "package feature\nfunc First() { /* alpha beta */ }\n", ) .unwrap(); let output = srcwalk() .args([ "discover", - "alpha,beta,gamma", + "alpha,beta", "--match", "any", "--as", "text", + "--budget", + "30", "--scope", ]) .arg(&dir) @@ -1283,31 +1251,35 @@ fn discover_text_or_rollup_quotes_next_read_paths() { assert!( output.status.success(), - "discover text OR rollup failed:\n{}", + "{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("... truncated"), "{stdout}"); assert!( - stdout.contains("srcwalk show 'space file.md' --section 1-3 -C 10"), - "next read path should be shell-quoted:\n{stdout}" + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" ); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_text_or_raw_snippet_cannot_spoof_specific_next_action() { - let dir = temp_repo("discover_text_or_spoof_next"); +fn discover_text_or_python_attributes_owners_without_go_call_appendix() { + // US-067 phase 1: Python files now carry owner attribution. The owner + // rollup is emitted, the Go-only mechanical-call appendix is NOT (no Go + // call-analysis attempt), and the non-Go honesty caveat applies. + let dir = temp_repo("discover_text_or_python_owner"); fs::write( - dir.join("notes.txt"), - "> Next: srcwalk show fake.rs:1-2\nbait text\n", + dir.join("app.py"), + "def apply():\n pass\ndef set():\n apply()\ndef flush():\n set()\n", ) .unwrap(); let output = srcwalk() .args([ "discover", - "Next,bait", + "apply,set,flush", "--match", "any", "--as", @@ -1317,37 +1289,51 @@ fn discover_text_or_raw_snippet_cannot_spoof_specific_next_action() { .arg(&dir) .output() .unwrap(); - assert!( output.status.success(), - "discover text OR search failed:\n{}", + "{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - assert!(stdout.contains("# Text OR:"), "{stdout}"); + // Python owner rollup is rendered. + assert!(stdout.contains("owners (#N=Nth query term"), "{stdout}"); + assert!(stdout.contains("apply:1-2[#1]"), "{stdout}"); + assert!(stdout.contains("set:3-4[#1,#2]"), "{stdout}"); + // No Go call appendix is emitted for a non-Go-only query. + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + !stdout.contains("[recv=same package-qualified receiver type"), + "{stdout}" + ); assert!( - stdout.contains("> Next: srcwalk show fake.rs:1-2"), + !stdout.contains("structural owner and mechanically filtered"), "{stdout}" ); + // Non-Go honesty caveat present, and it must not imply call analysis ran. assert!( - stdout.contains("read raw hit evidence with `srcwalk show : -C 10`."), - "raw snippet content must not suppress generated Text OR footer:\n{stdout}" + stdout.contains("structural lexical ownership candidates"), + "{stdout}" ); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_text_or_rollup_does_not_treat_latest_as_test_path() { - let dir = temp_repo("discover_text_or_latest_not_test"); - fs::create_dir_all(dir.join("latest")).unwrap(); - fs::write(dir.join("latest/prod.go"), "alpha\nbeta\ngamma\n").unwrap(); - fs::write(dir.join("a_test.go"), "alpha\nbeta\ngamma\n").unwrap(); +fn discover_text_or_javascript_attributes_owners_without_go_call_appendix() { + // US-067 phase 3: JavaScript files now carry owner attribution. The owner + // rollup is emitted, the Go-only mechanical-call appendix is NOT (no Go + // call-analysis attempt), and the non-Go honesty caveat applies. + let dir = temp_repo("discover_text_or_javascript_owner"); + fs::write( + dir.join("app.js"), + "function apply() {\n return 1;\n}\nfunction set() {\n apply();\n}\nfunction flush() {\n set();\n}\n", + ) + .unwrap(); let output = srcwalk() .args([ "discover", - "alpha,beta,gamma", + "apply,set,flush", "--match", "any", "--as", @@ -1357,563 +1343,665 @@ fn discover_text_or_rollup_does_not_treat_latest_as_test_path() { .arg(&dir) .output() .unwrap(); - assert!( output.status.success(), - "discover text OR rollup failed:\n{}", + "{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - let prod_idx = stdout.find("latest/prod.go — 3 terms").unwrap(); - let test_idx = stdout.find("a_test.go — 3 terms").unwrap(); + // JavaScript owner rollup is rendered with dot-less top-level names. + assert!(stdout.contains("owners (#N=Nth query term"), "{stdout}"); + assert!(stdout.contains("apply:1-3[#1]"), "{stdout}"); + assert!(stdout.contains("set:4-6[#1,#2]"), "{stdout}"); + assert!(stdout.contains("flush:7-9[#2,#3]"), "{stdout}"); + // No Go call appendix is emitted for a non-Go-only query. + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + !stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + // Non-Go honesty caveat present, and it must not imply call analysis ran. assert!( - prod_idx < test_idx, - "production path under latest/ must rank before test file:\n{stdout}" + stdout.contains("structural lexical ownership candidates"), + "{stdout}" ); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_match_any_text_or_omission_note_does_not_suggest_global_offset() { - let dir = temp_repo("discover_text_or_omission_note"); - fs::write(dir.join("one.txt"), "alpha one\nalpha two\nbeta one\n").unwrap(); +fn discover_jsx_routes_through_javascript_grammar_with_callback_barrier() { + // A real `.jsx` file must route through the JavaScript grammar (JSX + // elements parse), the named component gets an exact owner, and the inline + // JSX callback (an anonymous arrow) must NOT fall through as a bogus owner. + // The non-Go honesty caveat holds and no Go call appendix is emitted. + let dir = temp_repo("discover_jsx_owner_barrier"); + fs::write( + dir.join("app.jsx"), + "function App() {\n return ;\n}\nfunction util() {\n return 1;\n}\n", + ) + .unwrap(); let output = srcwalk() .args([ - "discover", - "alpha,beta", - "--match", - "any", - "--as", - "text", - "--limit", - "1", - "--scope", + "discover", "App,util", "--match", "any", "--as", "text", "--scope", ]) .arg(&dir) .output() .unwrap(); - assert!( output.status.success(), - "discover text OR failed:\n{}", + "{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - assert!(stdout.contains("## alpha — 1/2 matches"), "{stdout}"); - assert!( - stdout.contains("more `alpha` matches omitted by per-term limit 1"), + // Named component routes through JS grammar with an exact owner. + assert!(stdout.contains("app.jsx:1 [owner App@1-3]"), "{stdout}"); + assert!(stdout.contains("app.jsx:4 [owner util@4-6]"), "{stdout}"); + // The inline JSX callback line is an anonymous barrier: it does NOT carry + // its own `[owner ...]` and does not fall through to a bogus name. + assert!(!stdout.contains("app.jsx:2 [owner"), "{stdout}"); + // Non-Go honesty caveat present; no Go mechanical-call appendix. + assert!( + stdout.contains("structural lexical ownership candidates"), "{stdout}" ); + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); assert!( - !stdout.contains("Continue with --offset"), - "text OR must not suggest a global offset that hides shorter terms:\n{stdout}" + !stdout.contains("structural owner and mechanically filtered"), + "{stdout}" ); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_match_any_text_or_rejects_offset() { - let dir = temp_repo("discover_text_or_rejects_offset"); - fs::write(dir.join("one.txt"), "alpha one\nbeta one\n").unwrap(); +fn discover_typescript_attributes_owners_without_go_call_appendix() { + // A real `.ts` file routes through the TypeScript grammar: namespace + // nesting yields dot-joined owners, exact ranges render, and the non-Go + // honesty caveat holds with no Go call appendix. + let dir = temp_repo("discover_typescript_owner"); + fs::write( + dir.join("app.ts"), + "namespace A.B {\n export function foo() {}\n export class C {\n bar() {}\n }\n}\n", + ) + .unwrap(); let output = srcwalk() .args([ - "discover", - "alpha,beta", - "--match", - "any", - "--as", - "text", - "--offset", - "1", - "--scope", + "discover", "foo,bar", "--match", "any", "--as", "text", "--scope", ]) .arg(&dir) .output() .unwrap(); - - assert!(!output.status.success(), "offset should be rejected"); - let stderr = String::from_utf8_lossy(&output.stderr); assert!( - stderr.contains("does not support --offset"), - "expected offset diagnostic, got:\n{stderr}" + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("app.ts:2 [owner A.B.foo@2-2]"), "{stdout}"); + assert!( + stdout.contains("app.ts:4 [owner A.B.C.bar@4-4]"), + "{stdout}" + ); + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + !stdout.contains("structural owner and mechanically filtered"), + "{stdout}" ); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_bare_punctuation_list_infers_text_or() { - let dir = temp_repo("discover_bare_text_or"); - fs::write(dir.join("one.rs"), "fn handler() { let url = req.body; }\n").unwrap(); - fs::write(dir.join("two.rs"), "fn proxy() { fetch(url); }\n").unwrap(); +fn discover_tsx_routes_through_tsx_grammar_with_callback_barrier() { + // A real `.tsx` file routes through the TSX grammar: the named component is + // an exact owner, the inline JSX callback is an anonymous barrier (no bogus + // owner), and the non-Go caveat/no-Go-appendix holds. + let dir = temp_repo("discover_tsx_owner_barrier"); + fs::write( + dir.join("app.tsx"), + "function App() {\n return ;\n}\nfunction util() {\n return 1;\n}\n", + ) + .unwrap(); let output = srcwalk() - .args(["discover", "req.body,fetch", "--scope"]) + .args([ + "discover", "App,util", "--match", "any", "--as", "text", "--scope", + ]) .arg(&dir) .output() .unwrap(); - assert!( output.status.success(), - "bare punctuation list should infer text OR:\n{}", + "{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - assert!(stdout.contains("# Text OR:"), "{stdout}"); - assert!(stdout.contains("## req.body"), "{stdout}"); - assert!(stdout.contains("## fetch"), "{stdout}"); - assert!(stdout.contains("literal OR text evidence only"), "{stdout}"); + assert!(stdout.contains("app.tsx:1 [owner App@1-3]"), "{stdout}"); + assert!(stdout.contains("app.tsx:4 [owner util@4-6]"), "{stdout}"); + assert!(!stdout.contains("app.tsx:2 [owner"), "{stdout}"); + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_structural_matches_suggest_confirmed_show_targets() { - let dir = temp_repo("discover_show_targets"); +fn discover_mts_cts_route_owners_through_existing_lang_mapping() { + // `.mts`/`.cts` share the TypeScript Lang tier via the existing extension + // mapping (no extension hacks): both carry owner attribution. + let dir = temp_repo("discover_mts_cts_owner_routing"); fs::write( - dir.join("lib.rs"), - r#"fn target() -> i32 { - helper() -} - -fn helper() -> i32 { 1 } - -fn caller() -> i32 { - target() -} -"#, + dir.join("mod.mts"), + "namespace N {\n export function foo() {}\n}\n", ) .unwrap(); + fs::write(dir.join("main.cts"), "class Svc {\n handle() {}\n}\n").unwrap(); let output = srcwalk() - .args(["discover", "target", "--scope"]) + .args([ + "discover", + "foo,handle", + "--match", + "any", + "--as", + "text", + "--scope", + ]) .arg(&dir) .output() .unwrap(); - assert!( output.status.success(), - "discover target failed:\n{}", + "{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("mod.mts:2 [owner N.foo@2-2]"), "{stdout}"); assert!( - stdout.contains("## Confirmed structural targets"), + stdout.contains("main.cts:2 [owner Svc.handle@2-2]"), "{stdout}" ); assert!( - stdout.contains("> Next: srcwalk show 'lib.rs:1-3,lib.rs:7-9'"), + stdout.contains("structural lexical ownership candidates"), "{stdout}" ); - assert_eq!( - stdout - .matches("> Next: srcwalk show 'lib.rs:1-3,lib.rs:7-9'") - .count(), - 1, - "confirmed structural next action should be deduplicated:\n{stdout}" - ); - assert!( - stdout.contains("read the confirmed structural target above"), - "discover footer should route structural candidates to show first:\n{stdout}" - ); - assert!( - !stdout.contains("use --expand to inline definition source"), - "confirmed structural target should suppress definition expand guidance:\n{stdout}" - ); + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_over_cap_structural_target_omits_action_and_heading() { - let dir = temp_repo("discover_over_cap_show_target"); - let mut content = String::from("fn target() {\n"); - for line in 2..201 { - content.push_str(&format!(" let v{line} = {line};\n")); - } - content.push_str("}\n"); - fs::write(dir.join("lib.rs"), content).unwrap(); +fn discover_malformed_go_with_python_owners_suppresses_go_call_appendix() { + // Regression for the gate bug: a malformed Go input must not leave + // `go_call_analysis_attempted` true, because `build_owner_link_evidence` + // only inserts successfully-parsed Go files into its analysis set. Python + // owner attribution is retained, but the Go-only mechanical-call appendix + // (zero-edge sentence + call caveat) must NOT render. + let dir = temp_repo("discover_malformed_go_suppresses_go_appendix"); + fs::write(dir.join("app.py"), "def apply():\n pass\n").unwrap(); + // Deterministically malformed Go: unclosed parameter list. + fs::write(dir.join("broken.go"), "package p\nfunc main( {\n").unwrap(); let output = srcwalk() - .args(["discover", "target", "--scope"]) + .args([ + "discover", + "apply,main", + "--match", + "any", + "--as", + "text", + "--scope", + ]) .arg(&dir) .output() .unwrap(); - assert!( output.status.success(), - "discover target failed:\n{}", + "{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - assert!( - !stdout.contains("## Confirmed structural targets"), + // Python owner evidence is retained. + assert!(stdout.contains("[owner apply@1-2]"), "{stdout}"); + // The malformed Go hit is present but carries NO owner attribution. + assert!(stdout.contains("broken.go:2"), "{stdout}"); + assert!(!stdout.contains("broken.go:2 [owner"), "{stdout}"); + // No Go zero-edge sentence, no Go call caveat, no Mechanical Go header. + assert!( + !stdout.contains("No direct name-level call evidence"), "{stdout}" ); assert!( - !stdout.contains("> Next: srcwalk show lib.rs:1-201"), + !stdout.contains("structural owner and mechanically filtered"), "{stdout}" ); + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + // Non-Go honesty caveat is retained. assert!( - stdout.contains("> Caveat: confirmed structural target lib.rs:1-201 spans 201 lines, over the 200-line next-action bound."), + stdout.contains("structural lexical ownership candidates"), "{stdout}" ); - assert!( - stdout.contains("read the confirmed structural target above"), - "existing prose footer must remain unchanged:\n{stdout}" - ); - - let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_multiple_structural_matches_suggest_batched_show_target() { - let dir = temp_repo("discover_batched_show_targets"); - fs::create_dir_all(dir.join("a")).unwrap(); - fs::create_dir_all(dir.join("b")).unwrap(); - fs::write(dir.join("a/lib.rs"), "fn target() -> i32 { 1 }\n").unwrap(); - fs::write(dir.join("b/lib.rs"), "fn target() -> i32 { 2 }\n").unwrap(); +fn discover_text_or_rust_attributes_owners_without_go_call_appendix() { + // US-067 phase 2: Rust files now carry owner attribution. The owner rollup + // is emitted, the Go-only mechanical-call appendix is NOT (no Go call- + // analysis attempt), and the non-Go honesty caveat applies. + let dir = temp_repo("discover_text_or_rust_owner"); + fs::write( + dir.join("app.rs"), + "fn apply() {\n}\nfn set() {\n apply();\n}\nfn flush() {\n set();\n}\n", + ) + .unwrap(); let output = srcwalk() - .args(["discover", "target", "--scope"]) + .args([ + "discover", + "apply,set,flush", + "--match", + "any", + "--as", + "text", + "--scope", + ]) .arg(&dir) - .args(["--limit", "5"]) .output() .unwrap(); - assert!( output.status.success(), - "discover target failed:\n{}", + "{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - assert!( - stdout.contains("## Confirmed structural targets"), + // Rust owner rollup is rendered with exact owner ranges. + assert!(stdout.contains("owners (#N=Nth query term"), "{stdout}"); + assert!(stdout.contains("apply:1-2[#1]"), "{stdout}"); + assert!(stdout.contains("set:3-5[#1,#2]"), "{stdout}"); + assert!(stdout.contains("flush:6-8[#2,#3]"), "{stdout}"); + // No Go call appendix is emitted for a non-Go-only query. + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + !stdout.contains("[recv=same package-qualified receiver type"), "{stdout}" ); assert!( - stdout.contains("> Next: srcwalk show 'a/lib.rs:1-1,b/lib.rs:1-1'"), - "expected one batched show next action:\n{stdout}" - ); - assert_eq!( - stdout - .matches("> Next: srcwalk show 'a/lib.rs:1-1,b/lib.rs:1-1'") - .count(), - 1, - "batched show next action should be deduplicated:\n{stdout}" + !stdout.contains("structural owner and mechanically filtered"), + "{stdout}" ); + // Non-Go honesty caveat present, and it must not imply call analysis ran. assert!( - !stdout.contains("srcwalk context a/lib.rs:1-1"), - "discover should not route confirmed source reads through context:\n{stdout}" + stdout.contains("structural lexical ownership candidates"), + "{stdout}" ); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_structural_show_targets_quote_spaces_and_comma_paths() { - let dir = temp_repo("discover_show_target_path_safety"); - fs::write(dir.join("a file.rs"), "fn target() -> i32 { 1 }\n").unwrap(); +fn discover_mixed_go_and_rust_attributes_both_and_go_appendix() { + // Phase 2 capability honesty: a mixed Go + Rust query retains Rust owner + // attribution AND the Go-only mechanical-call appendix (Go call analysis + // ran), plus the non-Go honesty caveat for the Rust evidence. + let dir = temp_repo("discover_mixed_go_rust_owner"); + fs::write( + dir.join("app.rs"), + "fn apply() {\n}\nfn set() {\n apply();\n}\n", + ) + .unwrap(); + fs::write( + dir.join("db.go"), + "package db\ntype DB struct{}\nfunc (d *DB) Apply() { /* apply body */ }\nfunc (d *DB) Set() { /* set body */ d.Apply() }\n", + ) + .unwrap(); let output = srcwalk() - .args(["discover", "target", "--scope"]) + .args([ + "discover", + "apply,set", + "--match", + "any", + "--as", + "text", + "--scope", + ]) .arg(&dir) .output() .unwrap(); - - assert!(output.status.success()); - let stdout = String::from_utf8_lossy(&output.stdout); assert!( - stdout.contains("> Next: srcwalk show 'a file.rs:1-1'"), - "space-bearing target must be shell-quoted:\n{stdout}" + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) ); - - fs::remove_file(dir.join("a file.rs")).unwrap(); - fs::write(dir.join("a,file.rs"), "fn target() -> i32 { 1 }\n").unwrap(); - - let output = srcwalk() - .args(["discover", "target", "--scope"]) - .arg(&dir) - .output() - .unwrap(); - - assert!(output.status.success()); let stdout = String::from_utf8_lossy(&output.stdout); + // Rust owner evidence is retained. + assert!(stdout.contains("[owner apply@1-2]"), "{stdout}"); + // Go mechanical-call appendix is present (Go call analysis ran). + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); assert!( - stdout.contains("> Next: srcwalk show 'a,file.rs' --section 1-1"), - "comma-bearing path must use --section instead of ambiguous inline target:\n{stdout}" + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" ); + // Non-Go honesty caveat present for the Rust owner evidence. assert!( - !stdout.contains("srcwalk show a,file.rs:1-1"), - "comma-bearing path must not be emitted as an ambiguous inline target:\n{stdout}" + stdout.contains("structural lexical ownership candidates"), + "{stdout}" ); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_typescript_function_definition_suggests_confirmed_show_target() { - let dir = temp_repo("discover_ts_show_target"); +fn discover_text_or_go_compact_rollup_has_owner_line_by_default() { + // Default-on owner attribution: a compact Go Text OR (>=3 terms) yields the + // `owners (#N=...` rollup line with NO opt-in flag. + let dir = temp_repo("discover_text_or_go_owner_default"); fs::write( - dir.join("server.ts"), - r#"import { Server } from "@modelcontextprotocol/sdk/server/index.js"; - -function createGatewayServer(context: unknown): Server { - const server = new Server({ name: "gateway", version: "1" }); - server.setRequestHandler("list", async () => ({ tools: [] })); - server.setRequestHandler("call", async (request) => request); - return server; -} - -export function startServer() { - return createGatewayServer({}); -} -"#, + dir.join("db.go"), + "package db\ntype DB struct{}\nfunc (d *DB) Apply() { /* apply body */ }\nfunc (d *DB) Set() { /* set body */ d.Apply() }\nfunc (d *DB) Flush() { /* flush body */ d.Set(); d.Apply() }\n", ) .unwrap(); let output = srcwalk() - .args(["discover", "createGatewayServer", "--scope"]) + .args([ + "discover", + "apply body,set body,flush body", + "--match", + "any", + "--as", + "text", + "--scope", + ]) .arg(&dir) .output() .unwrap(); - assert!( output.status.success(), - "discover createGatewayServer failed:\n{}", + "{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); assert!( - stdout.contains("## Confirmed structural targets"), + stdout.contains("owners (#N=Nth query term; *K=hits)"), "{stdout}" ); + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); assert!( - stdout.contains("> Next: srcwalk show 'server.ts:3-8,server.ts:10-12'"), + stdout.contains("[recv] DB.Set calls Apply@db.go:4; candidate DB.Apply@:3-3"), "{stdout}" ); assert!( - !stdout.contains("use --expand to inline definition source"), - "confirmed TypeScript structural target should suppress definition expand guidance:\n{stdout}" + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" ); + let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_unsupported_language_function_does_not_suggest_context_target() { - let dir = temp_repo("discover_unsupported_context_target"); +fn discover_match_any_text_or_large_output_rolls_up_by_file() { + let dir = temp_repo("discover_text_or_file_rollup"); fs::write( - dir.join("App.swift"), - r#"func didUpdatePermissionStatus(_ message: String) { - print(message) -} - -func callStatus() { - didUpdatePermissionStatus("ok") -} -"#, + dir.join("feature.go"), + "alpha here\nbeta here\ngamma here\nalpha beta gamma\n", + ) + .unwrap(); + fs::write( + dir.join("feature_test.go"), + "alpha test\nbeta test\ngamma test\n", ) .unwrap(); + fs::write(dir.join("other.go"), "alpha only\n").unwrap(); let output = srcwalk() - .args(["discover", "didUpdatePermissionStatus", "--scope"]) + .args([ + "discover", + "alpha,beta,gamma,missing", + "--match", + "any", + "--as", + "text", + "--limit", + "2", + "--scope", + ]) .arg(&dir) .output() .unwrap(); assert!( output.status.success(), - "discover didUpdatePermissionStatus failed:\n{}", + "discover text OR rollup failed:\n{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); + let files_idx = stdout.find("## Files ranked by term coverage").unwrap(); + let terms_idx = stdout.find("## Terms").unwrap(); assert!( - stdout.contains("[fn] didUpdatePermissionStatus"), - "{stdout}" + files_idx < terms_idx, + "file rollup must lead term summary:\n{stdout}" ); + assert!(stdout.contains("feature.go — 3 terms"), "{stdout}"); + assert!(stdout.contains("terms: alpha("), "{stdout}"); assert!( - !stdout.contains("## Confirmed structural targets"), - "unsupported context language must not suggest structural targets:\n{stdout}" + stdout.contains("> Next: srcwalk show feature.go --section 1-4 -C 10"), + "{stdout}" ); assert!( - !stdout.contains("srcwalk context"), - "unsupported context language must not suggest any context command:\n{stdout}" + stdout.contains("missing — 0/0 matches, 0 files"), + "{stdout}" ); - + assert!(stdout.contains("omitted by per-term limit"), "{stdout}"); assert!( - stdout.contains("use --expand to inline definition source"), - "unsupported context language should keep definition expand guidance:\n{stdout}" + !stdout.contains("## alpha —"), + "compact mode should not dump term-first hit blocks:\n{stdout}" ); - fs::write( - dir.join("OrderReturn.php"), - r#": -C 10`"), - "text discover footer should prefer exact reads without context guesses:\n{text_stdout}" + stdout.contains("--section '10-10,1000-1000' -C 10"), + "next read must balance common and rare terms instead of only common clusters:\n{stdout}" ); - - let doc_output = srcwalk() - .args(["discover", "Getting Started", "--scope"]) - .arg(&dir) - .output() - .unwrap(); - assert!(doc_output.status.success()); - let doc_stdout = String::from_utf8_lossy(&doc_output.stdout); assert!( - doc_stdout.contains("[section] Getting Started"), - "{doc_stdout}" + stdout.contains("missing — 0/0 matches, 0 files"), + "{stdout}" ); assert!( - !doc_stdout.contains("## Confirmed structural targets"), - "document evidence must not suggest structural targets:\n{doc_stdout}" + !stdout.contains("notes.md:10-1000"), + "must not suggest sparse min-max reads:\n{stdout}" ); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_default_text_comma_stays_literal_and_hints_when_empty() { - let dir = temp_repo("discover_text_literal_comma_hint"); - fs::write(dir.join("one.txt"), "alpha only\nbeta only\n").unwrap(); +fn discover_text_or_rollup_splits_transitive_near_gap_chains() { + let dir = temp_repo("discover_text_or_chained_gaps"); + let mut lines = vec!["filler".to_string(); 180]; + for line in [1usize, 22, 43, 64, 85, 106] { + lines[line - 1] = "chain term".to_string(); + } + fs::write(dir.join("chain.txt"), lines.join("\n")).unwrap(); let output = srcwalk() - .args(["discover", "alpha,beta", "--as", "text", "--scope"]) + .args([ + "discover", + "chain,term,missing", + "--match", + "any", + "--as", + "text", + "--scope", + ]) .arg(&dir) .output() .unwrap(); assert!( output.status.success(), - "literal comma text search failed:\n{}", + "discover text OR rollup failed:\n{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - assert!(stdout.contains("0 matches"), "{stdout}"); assert!( - stdout.contains("treated as one literal text query"), - "{stdout}" + stdout.contains("windows: :1-64 terms=chain(4), term(4); :85-106 terms=chain(2), term(2)"), + "chained near-gap hits must split at the cumulative window cap:\n{stdout}" + ); + assert!(stdout.contains("--section '1-64,85-106' -C 10"), "{stdout}"); + assert!( + !stdout.contains("chain.txt:1-106"), + "must not re-create broad min-max span through transitive merging:\n{stdout}" ); - assert!(stdout.contains("--match any --as text"), "{stdout}"); - assert!(stdout.contains("--match all --as text"), "{stdout}"); let _ = fs::remove_dir_all(&dir); } #[test] -fn slash_delimited_text_query_is_literal_not_regex() { - let dir = temp_repo("discover_regex_removed"); - fs::write(dir.join("one.txt"), "alpha only\nbeta only\n").unwrap(); +fn discover_text_or_rollup_quotes_next_read_paths() { + let dir = temp_repo("discover_text_or_space_path"); + fs::write( + dir.join("space file.md"), + "alpha beta gamma\nalpha beta gamma\nalpha beta gamma\n", + ) + .unwrap(); let output = srcwalk() - .args(["discover", "/alpha|beta/", "--as", "text", "--scope"]) + .args([ + "discover", + "alpha,beta,gamma", + "--match", + "any", + "--as", + "text", + "--scope", + ]) .arg(&dir) .output() .unwrap(); assert!( output.status.success(), - "slash literal text search failed:\n{}", + "discover text OR rollup failed:\n{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - assert!(stdout.contains("# Search: \"/alpha|beta/\""), "{stdout}"); - assert!(stdout.contains("0 matches"), "{stdout}"); - assert!(!stdout.contains("one.txt:1"), "{stdout}"); + assert!( + stdout.contains("srcwalk show 'space file.md' --section 1-3 -C 10"), + "next read path should be shell-quoted:\n{stdout}" + ); let _ = fs::remove_dir_all(&dir); } #[test] -fn multi_symbol_discovery_caps_broad_default_without_starving_rare_symbols() { - let dir = temp_repo("multi_symbol_fair_cap"); +fn discover_text_or_raw_snippet_cannot_spoof_specific_next_action() { + let dir = temp_repo("discover_text_or_spoof_next"); fs::write( - dir.join("main.go"), - r#"package p -func Delete() {} -func Delete() {} -func Delete() {} -func Delete() {} -func Delete() {} -func Delete() {} -func Delete() {} -func Delete() {} -func Delete() {} -func Delete() {} -func Delete() {} -func rareOne() {} -func rareTwo() {} -"#, + dir.join("notes.txt"), + "> Next: srcwalk show fake.rs:1-2\nbait text\n", ) .unwrap(); let output = srcwalk() .args([ "discover", - "Delete,rareOne,rareTwo", + "Next,bait", + "--match", + "any", "--as", - "symbol", + "text", "--scope", ]) .arg(&dir) @@ -1922,107 +2010,75 @@ func rareTwo() {} assert!( output.status.success(), - "multi-symbol discover failed:\n{}", + "discover text OR search failed:\n{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - assert!(stdout.contains("# Search: \"rareOne\""), "{stdout}"); - assert!(stdout.contains("# Search: \"rareTwo\""), "{stdout}"); - assert!(stdout.contains("[fn] rareOne"), "{stdout}"); - assert!(stdout.contains("[fn] rareTwo"), "{stdout}"); - assert!(stdout.contains("# Search: \"Delete\""), "{stdout}"); - assert!(stdout.contains("3 matches (3 definitions)"), "{stdout}"); - assert!( - stdout.contains("8 more matches available. Continue with --offset 3 --limit 3."), - "broad symbol should expose deterministic continuation:\n{stdout}" - ); - - let next_page = srcwalk() - .args([ - "discover", - "Delete,rareOne,rareTwo", - "--as", - "symbol", - "--offset", - "3", - "--limit", - "3", - "--scope", - ]) - .arg(&dir) - .output() - .unwrap(); - assert!( - next_page.status.success(), - "multi-symbol continuation failed:\n{}", - String::from_utf8_lossy(&next_page.stderr) - ); - let next_stdout = String::from_utf8_lossy(&next_page.stdout); - assert!( - next_stdout.contains("# Search: \"Delete\""), - "{next_stdout}" - ); + assert!(stdout.contains("# Text OR:"), "{stdout}"); assert!( - next_stdout.contains("3 matches (3 definitions)"), - "{next_stdout}" + stdout.contains("> Next: srcwalk show fake.rs:1-2"), + "{stdout}" ); assert!( - next_stdout.contains("5 more matches available. Continue with --offset 6 --limit 3."), - "continuation page must advance its next offset:\n{next_stdout}" + stdout.contains("read raw hit evidence with `srcwalk show : -C 10`."), + "raw snippet content must not suppress generated Text OR footer:\n{stdout}" ); - let final_page = srcwalk() + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_text_or_rollup_does_not_treat_latest_as_test_path() { + let dir = temp_repo("discover_text_or_latest_not_test"); + fs::create_dir_all(dir.join("latest")).unwrap(); + fs::write(dir.join("latest/prod.go"), "alpha\nbeta\ngamma\n").unwrap(); + fs::write(dir.join("a_test.go"), "alpha\nbeta\ngamma\n").unwrap(); + + let output = srcwalk() .args([ "discover", - "Delete,rareOne,rareTwo", + "alpha,beta,gamma", + "--match", + "any", "--as", - "symbol", - "--offset", - "9", - "--limit", - "3", + "text", "--scope", ]) .arg(&dir) .output() .unwrap(); - assert!(final_page.status.success()); - let final_stdout = String::from_utf8_lossy(&final_page.stdout); + assert!( - final_stdout.contains("2 matches (2 definitions)"), - "{final_stdout}" + output.status.success(), + "discover text OR rollup failed:\n{}", + String::from_utf8_lossy(&output.stderr) ); + let stdout = String::from_utf8_lossy(&output.stdout); + let prod_idx = stdout.find("latest/prod.go — 3 terms").unwrap(); + let test_idx = stdout.find("a_test.go — 3 terms").unwrap(); assert!( - !final_stdout.contains("more matches available"), - "final page must not emit a false continuation:\n{final_stdout}" + prod_idx < test_idx, + "production path under latest/ must rank before test file:\n{stdout}" ); + let _ = fs::remove_dir_all(&dir); } #[test] -fn multi_symbol_discovery_respects_explicit_limit() { - let dir = temp_repo("multi_symbol_explicit_limit"); - fs::write( - dir.join("main.go"), - r#"package p -func Delete() {} -func Delete() {} -func Delete() {} -func Delete() {} -func Delete() {} -func rareOne() {} -"#, - ) - .unwrap(); +fn discover_match_any_text_or_omission_note_does_not_suggest_global_offset() { + let dir = temp_repo("discover_text_or_omission_note"); + fs::write(dir.join("one.txt"), "alpha one\nalpha two\nbeta one\n").unwrap(); let output = srcwalk() .args([ "discover", - "Delete,rareOne", + "alpha,beta", + "--match", + "any", "--as", - "symbol", + "text", "--limit", - "5", + "1", "--scope", ]) .arg(&dir) @@ -2031,227 +2087,1681 @@ func rareOne() {} assert!( output.status.success(), - "multi-symbol discover with explicit limit failed:\n{}", + "discover text OR failed:\n{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - assert!(stdout.contains("# Search: \"rareOne\""), "{stdout}"); - assert!(stdout.contains("# Search: \"Delete\""), "{stdout}"); - assert!(stdout.contains("5 matches (5 definitions)"), "{stdout}"); + assert!(stdout.contains("## alpha — 1/2 matches"), "{stdout}"); assert!( - !stdout.contains("2 more matches available. Continue with --offset 3 --limit 3."), - "explicit limit should override default per-symbol cap:\n{stdout}" + stdout.contains("more `alpha` matches omitted by per-term limit 1"), + "{stdout}" + ); + assert!( + !stdout.contains("Continue with --offset"), + "text OR must not suggest a global offset that hides shorter terms:\n{stdout}" ); let _ = fs::remove_dir_all(&dir); } #[test] -fn multi_symbol_discovery_keeps_small_batches_complete() { - let dir = temp_repo("multi_symbol_small_complete"); - fs::write( - dir.join("main.go"), - r#"package p -func Alpha() {} -func Alpha() {} -func Alpha() {} -func Alpha() {} -func Beta() {} -func Beta() {} -func Beta() {} -func Beta() {} -"#, - ) - .unwrap(); +fn discover_match_any_text_or_rejects_offset() { + let dir = temp_repo("discover_text_or_rejects_offset"); + fs::write(dir.join("one.txt"), "alpha one\nbeta one\n").unwrap(); let output = srcwalk() - .args(["discover", "Alpha,Beta", "--as", "symbol", "--scope"]) + .args([ + "discover", + "alpha,beta", + "--match", + "any", + "--as", + "text", + "--offset", + "1", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + + assert!(!output.status.success(), "offset should be rejected"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("does not support --offset"), + "expected offset diagnostic, got:\n{stderr}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_bare_punctuation_list_infers_text_or() { + let dir = temp_repo("discover_bare_text_or"); + fs::write(dir.join("one.rs"), "fn handler() { let url = req.body; }\n").unwrap(); + fs::write(dir.join("two.rs"), "fn proxy() { fetch(url); }\n").unwrap(); + + let output = srcwalk() + .args(["discover", "req.body,fetch", "--scope"]) .arg(&dir) .output() .unwrap(); assert!( output.status.success(), - "small multi-symbol discover failed:\n{}", + "bare punctuation list should infer text OR:\n{}", String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - assert_eq!( - stdout.matches("4 matches (4 definitions)").count(), - 2, - "small batch should keep every match for both symbols:\n{stdout}" - ); - assert!( - !stdout.contains("more matches available"), - "small batch should not be compacted:\n{stdout}" - ); + assert!(stdout.contains("# Text OR:"), "{stdout}"); + assert!(stdout.contains("## req.body"), "{stdout}"); + assert!(stdout.contains("## fetch"), "{stdout}"); + assert!(stdout.contains("literal OR text evidence only"), "{stdout}"); let _ = fs::remove_dir_all(&dir); } #[test] -fn path_symbol_rejections_preserve_command_intent() { - let dir = temp_repo("path_symbol_rejections"); +fn discover_structural_matches_suggest_confirmed_show_targets() { + let dir = temp_repo("discover_show_targets"); fs::write( dir.join("lib.rs"), - "fn target() {\n helper();\n}\nfn helper() {}\n", + r#"fn target() -> i32 { + helper() +} + +fn helper() -> i32 { 1 } + +fn caller() -> i32 { + target() +} +"#, ) .unwrap(); - let trace = srcwalk() - .args(["trace", "callees", "lib.rs:target", "--detailed", "--scope"]) + let output = srcwalk() + .args(["discover", "target", "--scope"]) .arg(&dir) .output() .unwrap(); - assert!(!trace.status.success()); - let trace_stderr = String::from_utf8_lossy(&trace.stderr); + assert!( - trace_stderr.contains("> Did you mean: target"), - "{trace_stderr}" + output.status.success(), + "discover target failed:\n{}", + String::from_utf8_lossy(&output.stderr) ); + let stdout = String::from_utf8_lossy(&output.stdout); assert!( - trace_stderr.contains("`path:symbol` targets are accepted by `context`, not `trace`."), - "{trace_stderr}" + stdout.contains("## Confirmed structural targets"), + "{stdout}" ); assert!( - trace_stderr.contains("srcwalk trace callees target --detailed --scope"), - "{trace_stderr}" + stdout.contains("> Next: srcwalk show lib.rs --section target"), + "{stdout}" ); - - let show = srcwalk() - .args(["show", "lib.rs:target", "--scope"]) - .arg(&dir) - .output() - .unwrap(); - assert!(!show.status.success()); - let show_stderr = String::from_utf8_lossy(&show.stderr); assert!( - show_stderr.contains("did you mean: lib.rs:1-3"), - "{show_stderr}" + stdout.contains("> Next: srcwalk show lib.rs --section caller"), + "{stdout}" + ); + assert_eq!( + stdout + .matches("> Next: srcwalk show lib.rs --section target") + .count(), + 1, + "confirmed structural next action should be deduplicated:\n{stdout}" ); assert!( - show_stderr.contains("`show` takes line ranges; `path:symbol` is `context` grammar."), - "{show_stderr}" + !stdout.contains("read the confirmed structural target above"), + "confirmed-target block owns the next action; no generic guidance may follow:\n{stdout}" ); - assert!(!show_stderr.contains("trace callees"), "{show_stderr}"); + assert!( + !stdout.contains("use --expand to inline definition source"), + "confirmed structural target should suppress definition expand guidance:\n{stdout}" + ); let _ = fs::remove_dir_all(&dir); } #[test] -fn ambiguous_path_symbol_trace_names_candidates_without_runnable_command() { - let dir = temp_repo("path_symbol_trace_ambiguous"); - fs::write(dir.join("a.rs"), "fn target() {}\n").unwrap(); - fs::write(dir.join("b.rs"), "fn target() {}\n").unwrap(); +fn discover_over_cap_structural_target_omits_action_and_heading() { + let dir = temp_repo("discover_over_cap_show_target"); + let mut content = String::from("fn target() {\n"); + for line in 2..201 { + content.push_str(&format!(" let v{line} = {line};\n")); + } + content.push_str("}\n"); + fs::write(dir.join("lib.rs"), content).unwrap(); let output = srcwalk() - .args(["trace", "callees", "a.rs:target", "--scope"]) + .args(["discover", "target", "--scope"]) .arg(&dir) .output() .unwrap(); - assert!(!output.status.success()); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("Candidates:"), "{stderr}"); - assert!(stderr.contains("a.rs:1-1"), "{stderr}"); - assert!(stderr.contains("b.rs:1-1"), "{stderr}"); - assert!(!stderr.contains("For this symbol:"), "{stderr}"); - assert!(!stderr.contains("Did you mean: target"), "{stderr}"); + + assert!( + output.status.success(), + "discover target failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + !stdout.contains("## Confirmed structural targets"), + "{stdout}" + ); + assert!( + !stdout.contains("> Next: srcwalk show lib.rs:1-201"), + "{stdout}" + ); + assert!( + stdout.contains("> Caveat: confirmed structural target lib.rs:1-201 spans 201 lines, over the 200-line next-action bound."), + "{stdout}" + ); + // A structural target exists (just over the cap), so the generic guidance + // is suppressed too; the caveat block owns the message. + assert!( + !stdout.contains("read the confirmed structural target above"), + "structural-target query must suppress generic guidance:\n{stdout}" + ); let _ = fs::remove_dir_all(&dir); } #[test] -fn unsupported_path_symbol_show_explains_grammar_without_guessing_range() { - let dir = temp_repo("path_symbol_unsupported"); - fs::write(dir.join("plain.txt"), "target text\n").unwrap(); +fn discover_multiple_structural_matches_suggest_batched_show_target() { + let dir = temp_repo("discover_batched_show_targets"); + fs::create_dir_all(dir.join("a")).unwrap(); + fs::create_dir_all(dir.join("b")).unwrap(); + fs::write(dir.join("a/lib.rs"), "fn target() -> i32 { 1 }\n").unwrap(); + fs::write(dir.join("b/lib.rs"), "fn target() -> i32 { 2 }\n").unwrap(); let output = srcwalk() - .args(["show", "plain.txt:target", "--scope"]) + .args(["discover", "target", "--scope"]) .arg(&dir) + .args(["--limit", "5"]) .output() .unwrap(); - assert!(!output.status.success()); - let stderr = String::from_utf8_lossy(&output.stderr); + assert!( - stderr.contains("`show` takes line ranges; `path:symbol` is `context` grammar."), - "{stderr}" + output.status.success(), + "discover target failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stdout.contains("## Confirmed structural targets"), + "{stdout}" + ); + assert!( + stdout.contains("> Next: srcwalk show a/lib.rs --section target"), + "expected symbol show next action:\n{stdout}" + ); + assert!( + stdout.contains("> Next: srcwalk show b/lib.rs --section target"), + "expected symbol show next action:\n{stdout}" + ); + assert_eq!( + stdout + .matches("> Next: srcwalk show a/lib.rs --section target") + .count(), + 1, + "symbol show next action should be deduplicated:\n{stdout}" + ); + assert!( + !stdout.contains("srcwalk context a/lib.rs:1-1"), + "discover should not route confirmed source reads through context:\n{stdout}" ); - assert!(!stderr.contains("did you mean:"), "{stderr}"); let _ = fs::remove_dir_all(&dir); } #[test] -fn discover_path_symbol_zero_result_reports_resolved_definition_only() { - let dir = temp_repo("discover_path_symbol_zero"); - fs::write(dir.join("lib.rs"), "fn target() {}\n").unwrap(); +fn discover_structural_show_targets_quote_spaces_and_comma_paths() { + let dir = temp_repo("discover_show_target_path_safety"); + fs::write(dir.join("a file.rs"), "fn target() -> i32 { 1 }\n").unwrap(); - let resolved = srcwalk() - .args(["discover", "lib.rs:target", "--scope"]) + let output = srcwalk() + .args(["discover", "target", "--scope"]) .arg(&dir) .output() .unwrap(); - assert!(resolved.status.success()); - let stdout = String::from_utf8_lossy(&resolved.stdout); - assert!(stdout.contains("0 of 0 files"), "{stdout}"); - assert!( - stdout.contains("`target` is defined at lib.rs:1-1"), - "{stdout}" - ); + + assert!(output.status.success()); + let stdout = String::from_utf8_lossy(&output.stdout); assert!( - stdout.contains("`path:symbol` is `context` grammar, not `discover` grammar."), - "{stdout}" + stdout.contains("> Next: srcwalk show 'a file.rs' --section target"), + "space-bearing target must be shell-quoted:\n{stdout}" ); - let unresolved = srcwalk() - .args(["discover", "lib.rs:nothing", "--scope"]) + fs::remove_file(dir.join("a file.rs")).unwrap(); + fs::write(dir.join("a,file.rs"), "fn target() -> i32 { 1 }\n").unwrap(); + + let output = srcwalk() + .args(["discover", "target", "--scope"]) .arg(&dir) .output() .unwrap(); - assert!(unresolved.status.success()); - let unresolved_stdout = String::from_utf8_lossy(&unresolved.stdout); - assert!( - !unresolved_stdout.contains("> Caveat:"), + + assert!(output.status.success()); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stdout.contains("> Next: srcwalk show 'a,file.rs' --section target"), + "comma-bearing path must use --section with a symbol selector:\n{stdout}" + ); + assert!( + !stdout.contains("srcwalk show a,file.rs:1-1"), + "comma-bearing path must not be emitted as an ambiguous inline target:\n{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_typescript_function_definition_suggests_confirmed_show_target() { + let dir = temp_repo("discover_ts_show_target"); + fs::write( + dir.join("server.ts"), + r#"import { Server } from "@modelcontextprotocol/sdk/server/index.js"; + +function createGatewayServer(context: unknown): Server { + const server = new Server({ name: "gateway", version: "1" }); + server.setRequestHandler("list", async () => ({ tools: [] })); + server.setRequestHandler("call", async (request) => request); + return server; +} + +export function startServer() { + return createGatewayServer({}); +} +"#, + ) + .unwrap(); + + let output = srcwalk() + .args(["discover", "createGatewayServer", "--scope"]) + .arg(&dir) + .output() + .unwrap(); + + assert!( + output.status.success(), + "discover createGatewayServer failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stdout.contains("## Confirmed structural targets"), + "{stdout}" + ); + assert!( + stdout.contains("> Next: srcwalk show server.ts --section createGatewayServer"), + "{stdout}" + ); + assert!( + stdout.contains("> Next: srcwalk show server.ts --section startServer"), + "{stdout}" + ); + assert!( + !stdout.contains("use --expand to inline definition source"), + "confirmed TypeScript structural target should suppress definition expand guidance:\n{stdout}" + ); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_unsupported_language_function_does_not_suggest_context_target() { + let dir = temp_repo("discover_unsupported_context_target"); + fs::write( + dir.join("App.swift"), + r#"func didUpdatePermissionStatus(_ message: String) { + print(message) +} + +func callStatus() { + didUpdatePermissionStatus("ok") +} +"#, + ) + .unwrap(); + + let output = srcwalk() + .args(["discover", "didUpdatePermissionStatus", "--scope"]) + .arg(&dir) + .output() + .unwrap(); + + assert!( + output.status.success(), + "discover didUpdatePermissionStatus failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stdout.contains("[fn] didUpdatePermissionStatus"), + "{stdout}" + ); + assert!( + !stdout.contains("## Confirmed structural targets"), + "unsupported context language must not suggest structural targets:\n{stdout}" + ); + assert!( + !stdout.contains("srcwalk context"), + "unsupported context language must not suggest any context command:\n{stdout}" + ); + + assert!( + stdout.contains("use --expand to inline definition source"), + "unsupported context language should keep definition expand guidance:\n{stdout}" + ); + + fs::write( + dir.join("OrderReturn.php"), + r#": -C 10`"), + "text discover footer should prefer exact reads without context guesses:\n{text_stdout}" + ); + + let doc_output = srcwalk() + .args(["discover", "Getting Started", "--scope"]) + .arg(&dir) + .output() + .unwrap(); + assert!(doc_output.status.success()); + let doc_stdout = String::from_utf8_lossy(&doc_output.stdout); + assert!( + doc_stdout.contains("[section] Getting Started"), + "{doc_stdout}" + ); + assert!( + !doc_stdout.contains("## Confirmed structural targets"), + "document evidence must not suggest structural targets:\n{doc_stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_default_text_comma_stays_literal_and_hints_when_empty() { + let dir = temp_repo("discover_text_literal_comma_hint"); + fs::write(dir.join("one.txt"), "alpha only\nbeta only\n").unwrap(); + + let output = srcwalk() + .args(["discover", "alpha,beta", "--as", "text", "--scope"]) + .arg(&dir) + .output() + .unwrap(); + + assert!( + output.status.success(), + "literal comma text search failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("0 matches"), "{stdout}"); + assert!( + stdout.contains("treated as one literal text query"), + "{stdout}" + ); + assert!(stdout.contains("--match any --as text"), "{stdout}"); + assert!(stdout.contains("--match all --as text"), "{stdout}"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn slash_delimited_text_query_is_literal_not_regex() { + let dir = temp_repo("discover_regex_removed"); + fs::write(dir.join("one.txt"), "alpha only\nbeta only\n").unwrap(); + + let output = srcwalk() + .args(["discover", "/alpha|beta/", "--as", "text", "--scope"]) + .arg(&dir) + .output() + .unwrap(); + + assert!( + output.status.success(), + "slash literal text search failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("# Search: \"/alpha|beta/\""), "{stdout}"); + assert!(stdout.contains("0 matches"), "{stdout}"); + assert!(!stdout.contains("one.txt:1"), "{stdout}"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn multi_symbol_discovery_caps_broad_default_without_starving_rare_symbols() { + let dir = temp_repo("multi_symbol_fair_cap"); + fs::write( + dir.join("main.go"), + r#"package p +func Delete() {} +func Delete() {} +func Delete() {} +func Delete() {} +func Delete() {} +func Delete() {} +func Delete() {} +func Delete() {} +func Delete() {} +func Delete() {} +func Delete() {} +func rareOne() {} +func rareTwo() {} +"#, + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", + "Delete,rareOne,rareTwo", + "--as", + "symbol", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + + assert!( + output.status.success(), + "multi-symbol discover failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("# Search: \"rareOne\""), "{stdout}"); + assert!(stdout.contains("# Search: \"rareTwo\""), "{stdout}"); + assert!(stdout.contains("[fn] rareOne"), "{stdout}"); + assert!(stdout.contains("[fn] rareTwo"), "{stdout}"); + assert!(stdout.contains("# Search: \"Delete\""), "{stdout}"); + assert!(stdout.contains("3 matches (3 definitions)"), "{stdout}"); + assert!( + stdout.contains("8 more matches available. Continue with --offset 3 --limit 3."), + "broad symbol should expose deterministic continuation:\n{stdout}" + ); + + let next_page = srcwalk() + .args([ + "discover", + "Delete,rareOne,rareTwo", + "--as", + "symbol", + "--offset", + "3", + "--limit", + "3", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + next_page.status.success(), + "multi-symbol continuation failed:\n{}", + String::from_utf8_lossy(&next_page.stderr) + ); + let next_stdout = String::from_utf8_lossy(&next_page.stdout); + assert!( + next_stdout.contains("# Search: \"Delete\""), + "{next_stdout}" + ); + assert!( + next_stdout.contains("3 matches (3 definitions)"), + "{next_stdout}" + ); + assert!( + next_stdout.contains("5 more matches available. Continue with --offset 6 --limit 3."), + "continuation page must advance its next offset:\n{next_stdout}" + ); + + let final_page = srcwalk() + .args([ + "discover", + "Delete,rareOne,rareTwo", + "--as", + "symbol", + "--offset", + "9", + "--limit", + "3", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!(final_page.status.success()); + let final_stdout = String::from_utf8_lossy(&final_page.stdout); + assert!( + final_stdout.contains("2 matches (2 definitions)"), + "{final_stdout}" + ); + assert!( + !final_stdout.contains("more matches available"), + "final page must not emit a false continuation:\n{final_stdout}" + ); + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn multi_symbol_discovery_respects_explicit_limit() { + let dir = temp_repo("multi_symbol_explicit_limit"); + fs::write( + dir.join("main.go"), + r#"package p +func Delete() {} +func Delete() {} +func Delete() {} +func Delete() {} +func Delete() {} +func rareOne() {} +"#, + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", + "Delete,rareOne", + "--as", + "symbol", + "--limit", + "5", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + + assert!( + output.status.success(), + "multi-symbol discover with explicit limit failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("# Search: \"rareOne\""), "{stdout}"); + assert!(stdout.contains("# Search: \"Delete\""), "{stdout}"); + assert!(stdout.contains("5 matches (5 definitions)"), "{stdout}"); + assert!( + !stdout.contains("2 more matches available. Continue with --offset 3 --limit 3."), + "explicit limit should override default per-symbol cap:\n{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn multi_symbol_discovery_keeps_small_batches_complete() { + let dir = temp_repo("multi_symbol_small_complete"); + fs::write( + dir.join("main.go"), + r#"package p +func Alpha() {} +func Alpha() {} +func Alpha() {} +func Alpha() {} +func Beta() {} +func Beta() {} +func Beta() {} +func Beta() {} +"#, + ) + .unwrap(); + + let output = srcwalk() + .args(["discover", "Alpha,Beta", "--as", "symbol", "--scope"]) + .arg(&dir) + .output() + .unwrap(); + + assert!( + output.status.success(), + "small multi-symbol discover failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert_eq!( + stdout.matches("4 matches (4 definitions)").count(), + 2, + "small batch should keep every match for both symbols:\n{stdout}" + ); + assert!( + !stdout.contains("more matches available"), + "small batch should not be compacted:\n{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn path_symbol_rejections_preserve_command_intent() { + let dir = temp_repo("path_symbol_rejections"); + fs::write( + dir.join("lib.rs"), + "fn target() {\n helper();\n}\nfn helper() {}\n", + ) + .unwrap(); + + let trace = srcwalk() + .args(["trace", "callees", "lib.rs:target", "--detailed", "--scope"]) + .arg(&dir) + .output() + .unwrap(); + assert!(!trace.status.success()); + let trace_stderr = String::from_utf8_lossy(&trace.stderr); + assert!( + trace_stderr.contains("> Did you mean: target"), + "{trace_stderr}" + ); + assert!( + trace_stderr.contains("`path:symbol` targets are accepted by `context`, not `trace`."), + "{trace_stderr}" + ); + assert!( + trace_stderr.contains("srcwalk trace callees target --detailed --scope"), + "{trace_stderr}" + ); + + let show = srcwalk() + .args(["show", "lib.rs:target", "--scope"]) + .arg(&dir) + .output() + .unwrap(); + assert!(!show.status.success()); + let show_stderr = String::from_utf8_lossy(&show.stderr); + assert!( + show_stderr.contains("did you mean: lib.rs:1-3"), + "{show_stderr}" + ); + assert!( + show_stderr.contains("`show` takes line ranges; `path:symbol` is `context` grammar."), + "{show_stderr}" + ); + assert!(!show_stderr.contains("trace callees"), "{show_stderr}"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn ambiguous_path_symbol_trace_names_candidates_without_runnable_command() { + let dir = temp_repo("path_symbol_trace_ambiguous"); + fs::write(dir.join("a.rs"), "fn target() {}\n").unwrap(); + fs::write(dir.join("b.rs"), "fn target() {}\n").unwrap(); + + let output = srcwalk() + .args(["trace", "callees", "a.rs:target", "--scope"]) + .arg(&dir) + .output() + .unwrap(); + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("Candidates:"), "{stderr}"); + assert!(stderr.contains("a.rs:1-1"), "{stderr}"); + assert!(stderr.contains("b.rs:1-1"), "{stderr}"); + assert!(!stderr.contains("For this symbol:"), "{stderr}"); + assert!(!stderr.contains("Did you mean: target"), "{stderr}"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn unsupported_path_symbol_show_explains_grammar_without_guessing_range() { + let dir = temp_repo("path_symbol_unsupported"); + fs::write(dir.join("plain.txt"), "target text\n").unwrap(); + + let output = srcwalk() + .args(["show", "plain.txt:target", "--scope"]) + .arg(&dir) + .output() + .unwrap(); + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("`show` takes line ranges; `path:symbol` is `context` grammar."), + "{stderr}" + ); + assert!(!stderr.contains("did you mean:"), "{stderr}"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_path_symbol_zero_result_reports_resolved_definition_only() { + let dir = temp_repo("discover_path_symbol_zero"); + fs::write(dir.join("lib.rs"), "fn target() {}\n").unwrap(); + + let resolved = srcwalk() + .args(["discover", "lib.rs:target", "--scope"]) + .arg(&dir) + .output() + .unwrap(); + assert!(resolved.status.success()); + let stdout = String::from_utf8_lossy(&resolved.stdout); + assert!(stdout.contains("0 of 0 files"), "{stdout}"); + assert!( + stdout.contains("`target` is defined at lib.rs:1-1"), + "{stdout}" + ); + assert!( + stdout.contains("`path:symbol` is `context` grammar, not `discover` grammar."), + "{stdout}" + ); + + let unresolved = srcwalk() + .args(["discover", "lib.rs:nothing", "--scope"]) + .arg(&dir) + .output() + .unwrap(); + assert!(unresolved.status.success()); + let unresolved_stdout = String::from_utf8_lossy(&unresolved.stdout); + assert!( + !unresolved_stdout.contains("> Caveat:"), "{unresolved_stdout}" ); - let excluded = srcwalk() + let excluded = srcwalk() + .args([ + "discover", + "lib.rs:target", + "--as", + "file", + "--exclude", + "*", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!(excluded.status.success()); + let excluded_stdout = String::from_utf8_lossy(&excluded.stdout); + assert!(!excluded_stdout.contains("> Caveat:"), "{excluded_stdout}"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn trace_callers_path_symbol_success_path_remains_without_new_hint() { + let dir = temp_repo("callers_path_symbol_unchanged"); + fs::write(dir.join("lib.rs"), "fn target() {}\n").unwrap(); + + let output = srcwalk() + .args(["trace", "callers", "lib.rs:target", "--scope"]) + .arg(&dir) + .output() + .unwrap(); + assert!(output.status.success()); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + !stdout.contains("srcwalk discover lib.rs:target"), + "{stdout}" + ); + assert!(output.stderr.is_empty()); + + let _ = fs::remove_dir_all(&dir); +} + +/// US-067 cross-language orchestration fixture: one temp scope with a Go +/// owner pair + valid Go->Go edge, named owners in Python/Rust/JS/TS/TSX, one +/// malformed supported file, and one unsupported `.txt`. +fn write_mixed_owner_scope(dir: &Path) { + fs::write( + dir.join("feature.go"), + "package feature\nfunc First() { /* alpha */ }\nfunc Second() { /* beta */ First() }\n", + ) + .unwrap(); + fs::write(dir.join("app.py"), "def load():\n return \"alpha\"\n").unwrap(); + fs::write( + dir.join("lib.rs"), + "fn load() {\n let _ = \"alpha\";\n}\n", + ) + .unwrap(); + fs::write( + dir.join("app.js"), + "function greet() {\n return \"alpha\";\n}\n", + ) + .unwrap(); + fs::write( + dir.join("app.ts"), + "function greet(): string {\n return \"alpha\";\n}\n", + ) + .unwrap(); + fs::write( + dir.join("App.tsx"), + "function App() {\n return
alpha
;\n}\n", + ) + .unwrap(); + // Malformed supported-language file: has a raw alpha hit but must abstain. + fs::write(dir.join("broken.py"), "def broken(\n return \"alpha\"\n").unwrap(); + // Unsupported raw file: preserved by search, absent from owner evidence. + fs::write(dir.join("notes.txt"), "line with alpha here\n").unwrap(); +} + +/// US-067 orchestration + determinism (tasks 1+2): one mixed Go/Python/Rust/JS/ +/// TS/TSX scope with a malformed supported file and an unsupported `.txt`. The +/// Go mechanical-call appendix renders Go-only, every clean file carries exact +/// per-file owner evidence, the malformed + unsupported raw hits stay visible +/// WITHOUT an owner, the non-Go honesty caveat holds, and no non-Go zero-edge/ +/// call claim is made. The exact command runs twice with byte-identical stdout +/// AND stderr. +#[test] +fn discover_text_or_mixed_owner_orchestration_and_determinism() { + let dir = temp_repo("discover_mixed_owner_orchestration"); + write_mixed_owner_scope(&dir); + + let run = || { + srcwalk() + .args([ + "discover", + "alpha,beta", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap() + }; + + let first = run(); + assert!( + first.status.success(), + "{}", + String::from_utf8_lossy(&first.stderr) + ); + + // Determinism: run twice, byte-compare stdout AND stderr. + let second = run(); + assert_eq!( + first.stdout, second.stdout, + "stdout bytes changed between runs" + ); + assert_eq!( + first.stderr, second.stderr, + "stderr bytes changed between runs" + ); + + let stdout = String::from_utf8_lossy(&first.stdout); + + // Header: 2-term Text OR, 9 matches across 8 files (detail path, <=30 hits). + assert!(stdout.contains("— 2 terms, 9 matches, 8 files"), "{stdout}"); + + // Every supported clean file carries exact per-file owner evidence. + for tag in [ + "feature.go:2 [owner First@2-2]", + "feature.go:3 [owner Second@3-3]", + "app.py:2 [owner load@1-2]", + "lib.rs:2 [owner load@1-3]", + "app.js:2 [owner greet@1-3]", + "app.ts:2 [owner greet@1-3]", + "App.tsx:2 [owner App@1-3]", + ] { + assert!(stdout.contains(tag), "missing {tag}:\n{stdout}"); + } + + // Malformed supported file + unsupported .txt: raw hit rows remain visible + // but carry NO owner tag. + assert!( + stdout.contains("broken.py:2 — return \"alpha\""), + "{stdout}" + ); + assert!( + stdout.contains("notes.txt:1 — line with alpha here"), + "{stdout}" + ); + assert!(!stdout.contains("broken.py:2 [owner"), "{stdout}"); + assert!(!stdout.contains("notes.txt:1 [owner"), "{stdout}"); + + // Go mechanical-call appendix exists and the single rendered edge is Go-only. + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + stdout.contains("- [bare] Second calls First@feature.go:3; candidate First@:2-2",), + "{stdout}" + ); + let go_edge_rows = stdout + .lines() + .filter(|l| l.starts_with("- [") && l.contains(" calls ")) + .count(); + assert_eq!(go_edge_rows, 1, "{stdout}"); + + // No non-Go zero-edge/call claim: not the zero-edge sentence, and no non-Go + // edge candidate appears. + assert!(!stdout.contains(OWNER_LINK_ZERO_EDGE), "{stdout}"); + assert!(!stdout.contains("candidate app."), "{stdout}"); + assert!(!stdout.contains("candidate lib."), "{stdout}"); + + // Go mechanical caveat + non-Go honesty caveat both present. + assert!( + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +/// US-067 Go isolation (task 5): adding non-matching non-Go files to a Go-only +/// scope leaves the Go query's stdout AND stderr byte-identical. +#[test] +fn discover_text_or_go_only_bytes_unchanged_by_non_matching_non_go_files() { + let dir = temp_repo("discover_go_isolation"); + fs::write( + dir.join("feature.go"), + "package feature\nfunc First() { /* alpha */ }\nfunc Second() { /* beta */ First() }\n", + ) + .unwrap(); + + let run = || { + srcwalk() + .args([ + "discover", + "alpha,beta", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap() + }; + + let before = run(); + assert!( + before.status.success(), + "{}", + String::from_utf8_lossy(&before.stderr) + ); + + // Add non-matching non-Go files (no alpha/beta anywhere) to the SAME dir so + // the scope path is unchanged. + fs::write(dir.join("app.py"), "def load():\n return 1\n").unwrap(); + fs::write(dir.join("lib.rs"), "fn load() {\n let _ = 1;\n}\n").unwrap(); + fs::write(dir.join("app.js"), "function greet() {\n return 1;\n}\n").unwrap(); + fs::write( + dir.join("App.tsx"), + "function App() {\n return
plain
;\n}\n", + ) + .unwrap(); + fs::write(dir.join("notes.txt"), "just a plain text note\n").unwrap(); + + let after = run(); + assert!( + after.status.success(), + "{}", + String::from_utf8_lossy(&after.stderr) + ); + assert_eq!( + before.stdout, after.stdout, + "Go stdout changed when non-Go files added" + ); + assert_eq!( + before.stderr, after.stderr, + "Go stderr changed when non-Go files added" + ); + + let _ = fs::remove_dir_all(&dir); +} + +/// Wave 2A full mixed-language scope: Go + TSX/TS/JS + Python + Rust + Java + +/// Kotlin + C# + PHP, each with a named owner over a matching hit. Only Go has +/// a name-level call edge (`Second -> First`). +fn write_wave2a_full_mixed_scope(dir: &Path) { + fs::write( + dir.join("feature.go"), + "package feature\nfunc First() { /* alpha */ }\nfunc Second() { /* beta */ First() }\n", + ) + .unwrap(); + fs::write(dir.join("app.py"), "def load():\n return \"alpha\"\n").unwrap(); + fs::write( + dir.join("lib.rs"), + "fn load() {\n let _ = \"alpha\";\n}\n", + ) + .unwrap(); + fs::write( + dir.join("app.js"), + "function greet() {\n return \"alpha\";\n}\n", + ) + .unwrap(); + fs::write( + dir.join("app.ts"), + "function greet(): string {\n return \"alpha\";\n}\n", + ) + .unwrap(); + fs::write( + dir.join("App.tsx"), + "function App() {\n return
alpha
;\n}\n", + ) + .unwrap(); + fs::write( + dir.join("Service.java"), + "class Service {\n void handle() {\n int x = 1; // alpha\n }\n}\n", + ) + .unwrap(); + fs::write( + dir.join("App.kt"), + "class App {\n fun load() {\n val s = \"alpha\"\n }\n}\n", + ) + .unwrap(); + fs::write( + dir.join("Program.cs"), + "class Service {\n void Load() {\n // alpha\n }\n}\n", + ) + .unwrap(); + fs::write( + dir.join("page.php"), + " First`; +/// no non-Go edge or zero-edge sentence appears. +#[test] +fn discover_text_or_wave2a_full_mixed_owner_orchestration() { + let dir = temp_repo("discover_wave2a_full_mixed_owner"); + write_wave2a_full_mixed_scope(&dir); + + let output = srcwalk() + .args([ + "discover", + "alpha,beta", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + + // Header: 2 terms, 11 matches across 10 files (detail path, <=30 hits). + assert!( + stdout.contains("— 2 terms, 11 matches, 10 files"), + "{stdout}" + ); + + // Every supported language carries exact per-file owner evidence. + for tag in [ + "feature.go:2 [owner First@2-2]", + "feature.go:3 [owner Second@3-3]", + "app.py:2 [owner load@1-2]", + "lib.rs:2 [owner load@1-3]", + "app.js:2 [owner greet@1-3]", + "app.ts:2 [owner greet@1-3]", + "App.tsx:2 [owner App@1-3]", + "Service.java:3 [owner Service.handle@2-4]", + "App.kt:3 [owner App.load@2-4]", + "Program.cs:3 [owner Service.Load@2-4]", + "page.php:3 [owner load@2-4]", + ] { + assert!(stdout.contains(tag), "missing {tag}:\n{stdout}"); + } + + // Go mechanical-call appendix exists and the single rendered edge is Go-only. + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + stdout.contains("- [bare] Second calls First@feature.go:3; candidate First@:2-2"), + "{stdout}" + ); + let go_edge_rows = stdout + .lines() + .filter(|l| l.starts_with("- [") && l.contains(" calls ")) + .count(); + assert_eq!(go_edge_rows, 1, "{stdout}"); + + // No non-Go edge/zero-edge claim. + assert!(!stdout.contains(OWNER_LINK_ZERO_EDGE), "{stdout}"); + assert!(!stdout.contains("candidate app."), "{stdout}"); + assert!(!stdout.contains("candidate Service."), "{stdout}"); + assert!(!stdout.contains("candidate App."), "{stdout}"); + + // Both honesty caveats present. + assert!( + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +/// US-068 integration task 2: same mixed scope run under several file-creation +/// orders must yield byte-identical stdout AND stderr (owner rollups, term +/// indices, ranges, caveats, and the Go appendix). +#[test] +fn discover_text_or_wave2a_determinism_across_file_creation_orders() { + let dir = temp_repo("discover_wave2a_determinism"); + write_wave2a_full_mixed_scope(&dir); + + let run = |d: &Path| { + srcwalk() + .args([ + "discover", + "alpha,beta", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(d) + .output() + .unwrap() + }; + let first = run(&dir); + assert!( + first.status.success(), + "{}", + String::from_utf8_lossy(&first.stderr) + ); + + // Recreate the same files in reverse lexical order in the same directory. + // This changes file-creation order without changing the rendered scope path. + let mut files = fs::read_dir(&dir) + .unwrap() + .map(|entry| { + let path = entry.unwrap().path(); + let bytes = fs::read(&path).unwrap(); + (path, bytes) + }) + .collect::>(); + files.sort_by(|(left, _), (right, _)| left.cmp(right)); + for (path, _) in &files { + fs::remove_file(path).unwrap(); + } + for (path, bytes) in files.iter().rev() { + fs::write(path, bytes).unwrap(); + } + + let second = run(&dir); + assert!( + second.status.success(), + "{}", + String::from_utf8_lossy(&second.stderr) + ); + assert_eq!( + first.stdout, second.stdout, + "stdout differs across creation orders" + ); + assert_eq!( + first.stderr, second.stderr, + "stderr differs across creation orders" + ); + + let _ = fs::remove_dir_all(&dir); +} + +/// US-068 integration task 3: one malformed file per Wave 2A language. Raw hits +/// remain visible; the error-overlapping region abstains; a valid region in the +/// same partially-parsed file stays eligible; no outer owner leakage occurs. +#[test] +fn discover_text_or_wave2a_malformed_files_abstain_without_outer_leakage() { + let dir = temp_repo("discover_wave2a_malformed"); + // Java: valid method + malformed method (unclosed param list) in one class. + fs::write( + dir.join("Bad.java"), + "class Service {\n void good() {\n // alpha\n }\n void bad( {\n // beta\n }\n}\n", + ) + .unwrap(); + // Kotlin: malformed statement inside a function body leaves the valid region + // eligible while the error-overlapping region abstains. + fs::write( + dir.join("Bad.kt"), + "class App {\n fun good() {\n val a = \"alpha\"\n }\n fun bad() {\n val b = \"beta\"\n if ( {\n val c = \"gamma\"\n }\n }\n}\n", + ) + .unwrap(); + // C#: valid method + malformed method in one class. + fs::write( + dir.join("Bad.cs"), + "class Service {\n void Good() {\n // alpha\n }\n void Bad( {\n // beta\n }\n}\n", + ) + .unwrap(); + // PHP: valid function + malformed function in one file. + fs::write( + dir.join("Bad.php"), + " Caveat:"), "{excluded_stdout}"); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + + // Valid regions in partially-parsed files stay eligible. + for tag in [ + "Bad.java:3 [owner Service.good@2-4]", + "Bad.kt:3 [owner App.good@2-4]", + "Bad.cs:3 [owner Service.Good@2-4]", + "Bad.php:3 [owner good@2-4]", + ] { + assert!(stdout.contains(tag), "missing {tag}:\n{stdout}"); + } + + // Malformed regions keep raw hits but carry NO owner (abstain, no leakage). + for file in ["Bad.java:6", "Bad.kt:6", "Bad.cs:6", "Bad.php:6"] { + assert!( + stdout.contains(&format!("{file} —")), + "raw hit missing {file}:\n{stdout}" + ); + assert!( + !stdout.contains(&format!("{file} [owner")), + "malformed region leaked owner at {file}:\n{stdout}" + ); + } let _ = fs::remove_dir_all(&dir); } +/// US-068 integration task 4: nonmatching Wave 2A files must not change the byte +/// output of Go-only or US-067-language-only queries. Go rollups/edges stay +/// byte-identical after adding non-matching Java/Kotlin/C#/PHP files. #[test] -fn trace_callers_path_symbol_success_path_remains_without_new_hint() { - let dir = temp_repo("callers_path_symbol_unchanged"); - fs::write(dir.join("lib.rs"), "fn target() {}\n").unwrap(); +fn discover_text_or_wave2a_nonmatching_files_do_not_change_go_and_us067_bytes() { + let run = |dir: &Path, query: &str| { + srcwalk() + .args([ + "discover", query, "--match", "any", "--as", "text", "--scope", + ]) + .arg(dir) + .output() + .unwrap() + }; + + // Go-only baseline: adding nonmatching Wave 2A files cannot alter bytes. + let go_dir = temp_repo("discover_wave2a_go_isolation"); + fs::write( + go_dir.join("feature.go"), + "package feature\nfunc First() { /* alpha */ }\nfunc Second() { /* beta */ First() }\n", + ) + .unwrap(); + let go_before = run(&go_dir, "alpha,beta"); + assert!( + go_before.status.success(), + "{}", + String::from_utf8_lossy(&go_before.stderr) + ); + + for (name, source) in [ + ("NonMatch.java", "class N { void m() { int x = 1; } }\n"), + ("NonMatch.kt", "class N { fun m() { val x = 1 } }\n"), + ("NonMatch.cs", "class N { void M() { int x = 1; } }\n"), + ("NonMatch.php", "alpha;\n}\n", + ) + .unwrap(); + let us067_before = run(&us067_dir, "alpha"); + assert!( + us067_before.status.success(), + "{}", + String::from_utf8_lossy(&us067_before.stderr) + ); + for (name, source) in [ + ("NonMatch.java", "class N { void m() { int x = 1; } }\n"), + ("NonMatch.kt", "class N { fun m() { val x = 1 } }\n"), + ("NonMatch.cs", "class N { void M() { int x = 1; } }\n"), + ("NonMatch.php", "=3 terms) renders owner +/// evidence for every language with no non-Go edge/zero-edge sentence. +#[test] +fn discover_text_or_wave2a_compact_rollup_attributes_all_languages() { + let dir = temp_repo("discover_wave2a_compact"); + write_wave2a_full_mixed_scope(&dir); + // Compact rendering intentionally ranks at most eight files. Keep one + // representative JS file here; the inline mixed test covers TS and TSX. + fs::remove_file(dir.join("app.ts")).unwrap(); + fs::remove_file(dir.join("App.tsx")).unwrap(); let output = srcwalk() - .args(["trace", "callers", "lib.rs:target", "--scope"]) + .args([ + "discover", + "alpha,beta,gamma", + "--match", + "any", + "--as", + "text", + "--scope", + ]) .arg(&dir) + .args(["--budget", "20000", "--limit", "20"]) .output() .unwrap(); - assert!(output.status.success()); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); let stdout = String::from_utf8_lossy(&output.stdout); + + // Compact rollup owner line header present. assert!( - !stdout.contains("srcwalk discover lib.rs:target"), + stdout.contains("owners (#N=Nth query term; *K=hits)"), "{stdout}" ); - assert!(output.stderr.is_empty()); + // Compact owner anchors for every language. + for (file, owner) in [ + ("feature.go —", "First:2-2[#1]"), + ("app.py —", "load:1-2[#1]"), + ("lib.rs —", "load:1-3[#1]"), + ("app.js —", "greet:1-3[#1]"), + ("Service.java —", "Service.handle:2-4[#1]"), + ("App.kt —", "App.load:2-4[#1]"), + ("Program.cs —", "Service.Load:2-4[#1]"), + ("page.php —", "load:2-4[#1]"), + ] { + assert!(stdout.contains(file), "missing {file}:\n{stdout}"); + assert!(stdout.contains(owner), "missing {owner}:\n{stdout}"); + } + // Go mechanical appendix still present and Go-only edge. + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + stdout.contains("Second calls First@feature.go:3"), + "{stdout}" + ); + // No non-Go zero-edge sentence. + assert!(!stdout.contains(OWNER_LINK_ZERO_EDGE), "{stdout}"); + // Non-Go honesty caveat retained. + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +// US-069: low-signal term advisory for literal text Search and Text OR. +const LOW_SIGNAL_ADVISORY: &str = "> Note: 450 matches across 150 of 1,000 eligible files for `frobnicate`; if this spread is not intentional, consider `overview`, a narrower term or scope, or a structural route."; + +/// Build a deterministic repo: `a/` and `b/` each hold 500 eligible source files. +/// 150 of the 1,000 files (75 per dir) carry 3 `frobnicate` matches each +/// (450 matches total), comfortably above the 400/150/1.5% advisory boundary. +fn build_low_signal_repo(name: &str) -> PathBuf { + let dir = temp_repo(name); + for sub in ["a", "b"] { + let sub = dir.join(sub); + fs::create_dir_all(&sub).unwrap(); + for i in 0..75 { + fs::write( + sub.join(format!("m{i:03}.rs")), + "fn a() { frobnicate }\nfn b() { frobnicate }\nfn c() { frobnicate }\n", + ) + .unwrap(); + } + for i in 75..500 { + fs::write(sub.join(format!("g{i:03}.rs")), "fn x() {}\n").unwrap(); + } + } + dir +} + +#[test] +fn discover_low_signal_route_coverage_and_guard() { + let dir = build_low_signal_repo("low_signal_route_guard"); + + // Explicit single-term text Search emits the exact shared advisory. + let single = srcwalk() + .args(["discover", "frobnicate", "--as", "text", "--scope"]) + .arg(&dir) + .arg("--no-budget") + .output() + .unwrap(); + assert!(single.status.success()); + let single_out = String::from_utf8_lossy(&single.stdout); + assert!(single_out.contains(LOW_SIGNAL_ADVISORY), "{single_out}"); + + // Text OR emits the same line for the triggering term. + let or = srcwalk() + .args([ + "discover", + "frobnicate,unrelated", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .arg("--no-budget") + .output() + .unwrap(); + assert!(or.status.success()); + let or_out = String::from_utf8_lossy(&or.stdout); + assert!(or_out.contains(LOW_SIGNAL_ADVISORY), "{or_out}"); + + // Multi-scope inferred/mixed routes abstain: no explicit literal-text route + // exists, so the advisory must never appear even for a high-spread term. + let multi = srcwalk() + .args(["discover", "frobnicate", "--scope"]) + .arg(dir.join("a")) + .arg("--scope") + .arg(dir.join("b")) + .arg("--no-budget") + .output() + .unwrap(); + assert!(multi.status.success()); + let multi_out = String::from_utf8_lossy(&multi.stdout); + assert!(!multi_out.contains("eligible files"), "{multi_out}"); + + // Below-threshold term emits no advisory. + fs::write(dir.join("a/one.rs"), "fn tiny() { frobnicate }\n").unwrap(); + let below = srcwalk() + .args(["discover", "tiny", "--as", "text", "--scope"]) + .arg(&dir) + .arg("--no-budget") + .output() + .unwrap(); + let below_out = String::from_utf8_lossy(&below.stdout); + assert!(!below_out.contains("eligible files"), "{below_out}"); + + // File, access, and co-occurrence routes never emit the advisory. + for (args, scope) in [ + (vec!["discover", "*.rs", "--as", "file"], &dir), + (vec!["discover", "frobnicate", "--as", "access"], &dir), + ( + vec!["discover", "frobnicate,frobnicate", "--match", "all"], + &dir, + ), + ] { + let output = srcwalk() + .args(&args) + .arg("--scope") + .arg(scope) + .arg("--no-budget") + .output() + .unwrap(); + let out = String::from_utf8_lossy(&output.stdout); + assert!(!out.contains("eligible files"), "{args:?}\n{out}"); + } + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_low_signal_budget_survives_and_replays() { + let dir = build_low_signal_repo("low_signal_budget_replay"); + + // Enough output plus a tiny budget forces body truncation; the advisory + // must survive once and stay before the final `> Next:`. + let first = srcwalk() + .args(["discover", "frobnicate", "--as", "text", "--scope"]) + .arg(&dir) + .arg("--budget") + .arg("80") + .output() + .unwrap(); + assert!(first.status.success()); + let first_out = String::from_utf8_lossy(&first.stdout); + assert_eq!( + first_out.matches(LOW_SIGNAL_ADVISORY).count(), + 1, + "advisory must appear exactly once under budget:\n{first_out}" + ); + let note_idx = first_out.find(LOW_SIGNAL_ADVISORY).unwrap(); + let next_idx = first_out.rfind("> Next:").unwrap(); + assert!(note_idx < next_idx, "advisory must precede final `> Next:`"); + + // Identical command replays byte-identically. + let second = srcwalk() + .args(["discover", "frobnicate", "--as", "text", "--scope"]) + .arg(&dir) + .arg("--budget") + .arg("80") + .output() + .unwrap(); + assert_eq!(first_out, String::from_utf8_lossy(&second.stdout)); let _ = fs::remove_dir_all(&dir); } diff --git a/tests/js_ts_private_members.rs b/tests/js_ts_private_members.rs index 566990f..17f8d0e 100644 --- a/tests/js_ts_private_members.rs +++ b/tests/js_ts_private_members.rs @@ -160,6 +160,8 @@ fn callers_private_attributed_to_enclosing_class_method() { stdout.contains("— 3 call sites"), "exactly the three #evict sites:\n{stdout}" ); + // Short relative path `cache.js`: grouping is a tie/no-gain, so the three + // sites stay inline (conditional grouping keeps ungrouped on tie). for line in ["cache.js:6", "cache.js:7", "cache.js:8"] { assert!(stdout.contains(line), "call site {line} missing:\n{stdout}"); } @@ -184,6 +186,7 @@ fn public_name_distinct_from_private() { pub_out.contains("— 2 call sites"), "public evict must see only its two sites:\n{pub_out}" ); + // Short path `cache.js`: 2 sites stay inline (grouping would be a tie). assert!( pub_out.contains("cache.js:9") && pub_out.contains("cache.js:10"), "public evict must see the bare + member sites:\n{pub_out}" diff --git a/tests/semantic_compact.rs b/tests/semantic_compact.rs index 855349b..737c5e2 100644 --- a/tests/semantic_compact.rs +++ b/tests/semantic_compact.rs @@ -223,6 +223,146 @@ fn symbol_search_compact_groups_multiple_definitions_in_same_file() { ); } +#[test] +fn definitions_hoist_uniform_default_once() { + // US-065-D: a compact Definitions section with uniform provenance prints the + // default tuple once below the header and does not repeat it per entry. + let dir = tempfile::tempdir().unwrap(); + for idx in 0..6 { + std::fs::write( + dir.path().join(format!("K{idx}.go")), + format!("package db\nfunc K{idx}(v int) {{}} \n"), + ) + .unwrap(); + } + + let out = srcwalk() + .args(["discover", "K*", "--glob", "*.go", "--scope"]) + .arg(dir.path()) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + + assert!( + stdout.contains("### Definitions (6)"), + "expected a compact Definitions facet, got:\n{stdout}" + ); + assert!( + stdout.contains("source: ast · kind: definition · confidence: structural syntax"), + "expected the hoisted default provenance tuple, got:\n{stdout}" + ); + // The uniform default appears exactly once (as the section default line). + assert_eq!( + stdout + .matches("kind: definition · confidence: structural syntax") + .count(), + 1, + "uniform default provenance should be printed once, got:\n{stdout}" + ); +} + +#[test] +fn definitions_single_entry_keeps_inline_provenance() { + // US-065-D: a one-definition result keeps its per-entry provenance inline + // (no hoist), byte-identical to pre-compaction output. + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("solo.go"), + "package db\nfunc Ksolo(v int) {}\n", + ) + .unwrap(); + let solo = srcwalk() + .args(["discover", "Ksolo", "--glob", "*.go", "--scope"]) + .arg(dir.path()) + .output() + .unwrap(); + let solo_stdout = String::from_utf8_lossy(&solo.stdout); + assert!( + solo_stdout.contains("[fn] Ksolo") && solo_stdout.contains("kind: definition"), + "single definition should keep its inline provenance, got:\n{solo_stdout}" + ); +} + +#[test] +fn usages_local_hoists_default_provenance_keeps_deviations() { + // US-065: the compact `Matches — same package` (usages_local) facet hoists + // the most frequent provenance tuple once and suppresses identical per-group + // provenance, while a deviation group keeps its own tuple locally. + let dir = tempfile::tempdir().unwrap(); + // A go.mod is required so the definition's package root is known and the + // calls are classified as same-package (usages_local). + std::fs::write(dir.path().join("go.mod"), "module app\n\ngo 1.21\n").unwrap(); + // Multiple name occurrences of the target in one package (uniform tuple). + std::fs::write( + dir.path().join("use.go"), + "package app\nfunc helper() {}\nfunc f() { helper() }\nfunc h() { helper() }\nfunc k() { helper() }\nfunc m() { helper() }\nfunc n() { helper() }\n", + ) + .unwrap(); + let out = srcwalk() + .args(["discover", "helper", "--as", "symbol", "--scope"]) + .arg(dir.path()) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + + // The default provenance appears once below the section header. + assert!( + stdout.contains("### Name occurrences — same package"), + "expected usages_local facet, got:\n{stdout}" + ); + assert_eq!( + stdout + .matches("kind: name occurrence · confidence: text evidence") + .count(), + 1, + "usages_local default provenance should be hoisted once, got:\n{stdout}" + ); +} + +#[test] +fn usages_cross_section_byte_unchanged() { + // US-065: provenance hoist is bounded to usages_local; the cross-package + // section must not change. Build a mixed fixture with a cross-package hit. + let dir = tempfile::tempdir().unwrap(); + let pkg_a = dir.path().join("pkg_a"); + let pkg_b = dir.path().join("pkg_b"); + std::fs::create_dir_all(&pkg_a).unwrap(); + std::fs::create_dir_all(&pkg_b).unwrap(); + std::fs::write(pkg_a.join("go.mod"), "module pkg_a\n\ngo 1.21\n").unwrap(); + std::fs::write(pkg_b.join("go.mod"), "module pkg_b\n\ngo 1.21\n").unwrap(); + std::fs::write( + pkg_a.join("a.go"), + "package pkg_a\nfunc Target() {}\nfunc use() { Target() }\n", + ) + .unwrap(); + // Enough cross-package usages to exceed the compact threshold (>5 matches). + std::fs::write( + pkg_b.join("b.go"), + "package pkg_b\nimport \"pkg_a\"\nfunc u1() { pkg_a.Target() }\nfunc u2() { pkg_a.Target() }\nfunc u3() { pkg_a.Target() }\nfunc u4() { pkg_a.Target() }\nfunc u5() { pkg_a.Target() }\nfunc u6() { pkg_a.Target() }\n", + ) + .unwrap(); + let out = srcwalk() + .args(["discover", "Target", "--as", "symbol", "--scope"]) + .arg(dir.path()) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + // The cross section keeps its per-entry provenance (no hoist): each group + // still prints its own provenance tuple. + assert!( + stdout.contains("### Name occurrences — other"), + "expected a cross-package compact section, got:\n{stdout}" + ); + // No hoist: per-group provenance is still emitted (not suppressed). + assert_eq!( + stdout + .matches("kind: name occurrence · confidence: text evidence") + .count(), + 2, + "cross-package section must keep per-group provenance, got:\n{stdout}" + ); +} + #[test] fn symbol_search_semantic_rows_work_across_rust_typescript_and_python() { let dir = tempfile::tempdir().unwrap(); diff --git a/tests/us060b_anchor_seam.rs b/tests/us060b_anchor_seam.rs index 97f19b7..7fcfc66 100644 --- a/tests/us060b_anchor_seam.rs +++ b/tests/us060b_anchor_seam.rs @@ -1,7 +1,8 @@ //! US-060b: no offered range wider than W=40 lines appears bare in discover / -//! trace output. Wide ranges are anchored to `path:line (label)` + an -//! `expand: srcwalk show path:A-B` command, so the full range is always exactly -//! one printed command away. +//! trace output. Wide ranges are anchored to a bounded `> anchor: path:line` +//! evidence line plus a primary `> Next:` command (symbol-addressed when the +//! selector round-trips; a numeric range otherwise), so the full body is +//! always exactly one printed command away. use std::fs; use std::path::PathBuf; @@ -82,11 +83,31 @@ fn discover_offers_no_bare_range_wider_than_forty() { String::from_utf8_lossy(&out.stderr) ); let stdout = String::from_utf8_lossy(&out.stdout); - // The wide definition range is anchored, not offered bare. + // The wide definition range is symbol-addressed: the symbol command is the + // primary `> Next:` action, and the numeric range is non-action evidence + // metadata (a bounded START-line preview), never a competing `> expand:` + // or an action-shaped `> anchor:` line repeating the full body range. assert!( - stdout.contains("> expand: srcwalk show target.js:"), - "wide range should be anchored with an expand command, got:\n{stdout}" + stdout.contains("> Next: srcwalk show target.js --section target"), + "wide range should be symbol-addressed as the primary next action, got:\n{stdout}" ); + assert!( + stdout.contains(" evidence anchor: target.js:1 (bounded preview; not the body address)"), + "START-line anchor should appear as plain metadata, got:\n{stdout}" + ); + assert!( + !stdout.contains("> anchor:"), + "anchor must not be action-shaped (no '> anchor:'), got:\n{stdout}" + ); + assert!( + !stdout.contains("evidence anchor: target.js:1-83"), + "anchor must not repeat the full body range, got:\n{stdout}" + ); + assert!( + !stdout.contains("> expand:"), + "no expand line may compete with the symbol next action:\n{stdout}" + ); + // No bare offer exposes a >40-line range. let widths = bare_offered_widths(&stdout); assert!( diff --git a/tests/us063_offer_dedupe.rs b/tests/us063_offer_dedupe.rs index 7531002..dc688c9 100644 --- a/tests/us063_offer_dedupe.rs +++ b/tests/us063_offer_dedupe.rs @@ -69,7 +69,7 @@ fn discover_keeps_offer_when_source_not_rendered() { ); let stdout = String::from_utf8_lossy(&out.stdout); assert!( - stdout.contains("> Next: srcwalk show lib.js:1-6"), + stdout.contains("> Next: srcwalk show lib.js --section target"), "unrendered target should still be offered:\n{stdout}" ); let _ = fs::remove_dir_all(&dir); diff --git a/tests/us065_symbol_section_footer.rs b/tests/us065_symbol_section_footer.rs new file mode 100644 index 0000000..86fe7d5 --- /dev/null +++ b/tests/us065_symbol_section_footer.rs @@ -0,0 +1,269 @@ +//! Symbol-addressed confirmed-structural-target footer + qualified `--section` +//! resolution. +//! +//! The discover footer points to `srcwalk show --section ` +//! (bare or `Type.method`) instead of a numeric range, so models read the +//! parser-backed symbol body rather than guessing numeric ranges. The +//! `--section` reader resolves `Q.N` receiver/container-qualified symbols +//! matching US-064 discover semantics. + +use std::fs; +use std::path::PathBuf; +use std::process::Command; + +fn srcwalk() -> Command { + Command::new(env!("CARGO_BIN_EXE_srcwalk")) +} + +struct Fixture { + dir: PathBuf, +} + +impl Fixture { + fn new(name: &str, files: &[(&str, &str)]) -> Self { + let dir = std::env::temp_dir().join(format!( + "us065_footer_{name}_{}_{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()) + )); + fs::create_dir_all(&dir).unwrap(); + for (rel, content) in files { + let path = dir.join(rel); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).unwrap(); + } + fs::write(path, content).unwrap(); + } + Self { dir } + } + + fn run(&self, args: &[&str]) -> (bool, String) { + let out = srcwalk() + .current_dir(&self.dir) + .args(args) + .output() + .unwrap(); + ( + out.status.success(), + String::from_utf8_lossy(&out.stdout).into_owned() + + &String::from_utf8_lossy(&out.stderr), + ) + } + + fn discover(&self, args: &[&str]) -> String { + let (ok, out) = self.run(args); + assert!(ok, "command {:?} failed:\n{out}", args); + out + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.dir); + } +} + +// ---------------------------------------------------------------- footer A + +#[test] +fn discover_bare_function_emits_symbol_section_command() { + let fx = Fixture::new( + "bare_fn", + &[( + "lib.rs", + "fn target() -> i32 {\n helper()\n}\n\nfn helper() -> i32 { 1 }\n", + )], + ); + let out = fx.discover(&["discover", "target", "--scope", "."]); + assert!(out.contains("## Confirmed structural targets"), "{out}"); + assert!( + out.contains("> Next: srcwalk show lib.rs --section target"), + "{out}" + ); + assert!( + !out.contains("srcwalk show 'lib.rs:1-3'") && !out.contains("srcwalk show lib.rs:1-3"), + "no numeric read command should be emitted:\n{out}" + ); + // The confirmed block owns the next action; no generic guidance may + // follow it as a competing primary `> Next:`. + assert!( + !out.contains("read the confirmed structural target above"), + "generic guidance must not follow a confirmed-target block:\n{out}" + ); +} + +#[test] +fn discover_qualified_preserves_qualified_selector() { + let fx = Fixture::new( + "qualified", + &[( + "batch.go", + "package db\n\ntype Batch struct{}\n\nfunc (b *Batch) Set(v int) {}\n", + )], + ); + let out = fx.discover(&["discover", "Batch.Set", "--as", "symbol", "--scope", "."]); + assert!( + out.contains("> Next: srcwalk show batch.go --section Batch.Set"), + "{out}" + ); +} + +#[test] +fn ambiguous_bare_name_falls_back_to_numeric_for_unresolvable_target() { + let fx = Fixture::new( + "ambiguous", + &[( + "lib.rs", + "fn helper() -> i32 { 1 }\nfn other() -> i32 { 2 }\nfn helper() -> i32 { 3 }\n", + )], + ); + let out = fx.discover(&["discover", "helper", "--scope", "."]); + // The first `helper` round-trips via the bare symbol; the second same-name + // `helper` cannot round-trip (the bare selector reads the first), so it + // must fall back to a numeric range rather than point at the wrong body. + assert!( + out.contains("> Next: srcwalk show lib.rs --section helper"), + "{out}" + ); + assert!(out.contains("> Next: srcwalk show lib.rs:3-3"), "{out}"); +} + +#[test] +fn discover_quotes_space_and_comma_paths_in_symbol_command() { + let fx = Fixture::new("quoted", &[("a file.rs", "fn target() -> i32 { 1 }\n")]); + let out = fx.discover(&["discover", "target", "--scope", "."]); + assert!( + out.contains("> Next: srcwalk show 'a file.rs' --section target"), + "{out}" + ); + + fs::remove_file(fx.dir.join("a file.rs")).unwrap(); + fs::write(fx.dir.join("a,file.rs"), "fn target() -> i32 { 1 }\n").unwrap(); + let out = fx.discover(&["discover", "target", "--scope", "."]); + assert!( + out.contains("> Next: srcwalk show 'a,file.rs' --section target"), + "comma path must stay quoted and single-target:\n{out}" + ); +} + +#[test] +fn non_structural_search_keeps_numeric_exact_hit_guidance() { + let fx = Fixture::new( + "text_hit", + &[("lib.rs", "fn main() {\n // nothing structural here\n}\n")], + ); + // A plain text search yields no confirmed structural target, so the + // numeric exact-hit guidance must remain (not be replaced by nothing). + let out = fx.discover(&["discover", "nothing", "--as", "text", "--scope", "."]); + assert!(!out.contains("## Confirmed structural targets"), "{out}"); + assert!( + out.contains("read exact hit evidence with `srcwalk show : -C 10`"), + "non-structural search must keep numeric exact-hit guidance:\n{out}" + ); +} + +// ------------------------------------------------------- section resolution B + +#[test] +fn rust_impl_qualified_section_reads_correct_method() { + let fx = Fixture::new( + "rust_impl", + &[( + "service.rs", + "pub struct Service;\nimpl Service {\n pub fn run(&self) {}\n pub fn stop(&self) {}\n}\n", + )], + ); + let (ok, out) = fx.run(&["show", "service.rs", "--section", "Service.run"]); + assert!(ok, "{out}"); + assert!(out.contains("pub fn run(&self)"), "{out}"); + assert!(!out.contains("pub fn stop"), "wrong method body:\n{out}"); + + // Bare method still works. + let (ok, out) = fx.run(&["show", "service.rs", "--section", "stop"]); + assert!(ok, "{out}"); + assert!(out.contains("pub fn stop(&self)"), "{out}"); +} + +#[test] +fn nested_classes_same_method_qualified_selects_correct_and_wrong_fails() { + let fx = Fixture::new( + "py_two_classes", + &[( + "config.py", + "class Alpha:\n def run(self):\n return 1\n\nclass Beta:\n def run(self):\n return 2\n", + )], + ); + let (ok, out) = fx.run(&["show", "config.py", "--section", "Alpha.run"]); + assert!(ok, "{out}"); + assert!( + out.contains("return 1"), + "Alpha.run must select Alpha's body:\n{out}" + ); + assert!(!out.contains("return 2"), "wrong container body:\n{out}"); + + let (ok, out) = fx.run(&["show", "config.py", "--section", "Beta.run"]); + assert!(ok, "{out}"); + assert!( + out.contains("return 2"), + "Beta.run must select Beta's body:\n{out}" + ); + + // Wrong qualifier is rejected. + let (ok, _) = fx.run(&["show", "config.py", "--section", "Nope.run"]); + assert!(!ok, "wrong qualifier must not silently resolve"); +} + +#[test] +fn go_receiver_qualified_section_reads_pointer_value_generic() { + let fx = Fixture::new( + "go_receivers", + &[( + "db/batch.go", + "package db\n\ntype Batch struct{}\ntype syncQueue[T any] struct{}\n\nfunc (b *Batch) Ptr() {}\nfunc (b Batch) Val() {}\nfunc (q *syncQueue[T]) Gen() {}\n", + )], + ); + for (selector, body) in [ + ("Batch.Ptr", "func (b *Batch) Ptr()"), + ("Batch.Val", "func (b Batch) Val()"), + ("syncQueue.Gen", "func (q *syncQueue[T]) Gen()"), + ] { + let (ok, out) = fx.run(&["show", "db/batch.go", "--section", selector]); + assert!(ok, "selector {selector} failed:\n{out}"); + assert!(out.contains(body), "selector {selector} wrong body:\n{out}"); + } +} + +#[test] +fn exact_dotted_outline_name_wins_before_qualified_interpretation() { + let fx = Fixture::new( + "elixir_dotted", + &[( + "app.ex", + "defmodule Foo.Bar do\n def hello do\n :world\n end\nend\n", + )], + ); + // `Foo.Bar` is a real dotted module name; it must resolve as the module, + // not as qualifier `Foo` + member `Bar`. + let (ok, out) = fx.run(&["show", "app.ex", "--section", "Foo.Bar"]); + assert!(ok, "{out}"); + assert!(out.contains("defmodule Foo.Bar"), "{out}"); +} + +#[test] +fn multi_dot_and_empty_side_selectors_reject_without_exact_match() { + let fx = Fixture::new( + "invalid_dots", + &[( + "app.ex", + "defmodule Foo.Bar do\n def hello do\n :world\n end\nend\n", + )], + ); + // Multi-dot is not a qualified symbol (no exact dotted name matches). + let (ok, _) = fx.run(&["show", "app.ex", "--section", "Foo.Bar.hello"]); + assert!(!ok, "multi-dot must not resolve as a qualified symbol"); + // Emptydot side is invalid. + let (ok, _) = fx.run(&["show", "app.ex", "--section", ".Bar"]); + assert!(!ok, "leading-dot must not resolve"); +}