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