From 952dd659ae287c99e7dd9bcce4f3d38acae296d0 Mon Sep 17 00:00:00 2001 From: sting8k Date: Tue, 11 Aug 2026 11:08:05 +0700 Subject: [PATCH 01/26] feat: symbol-addressed confirmed-target footer + qualified --section Discover's Confirmed structural targets footer now points to `srcwalk show --section ` (bare or Q.N) instead of a numeric range, so models read the parser-backed symbol body rather than guessing/reusing numeric ranges that cause partial-function loops. The --section reader resolves receiver/container-qualified Q.N selectors, matching US-064 discover semantics. US-064 primitives (split_dot_symbol_query, normalize_receiver_type, normalize_outline_container, outline_container_kind) moved to a shared src/lang/qualified.rs used by both search and read, plus a shared outline resolver with exact dotted-name precedence and Go receiver-from-signature extraction. A round-trip check gates the symbol footer: it is emitted only when the selector resolves back to exactly the target range, otherwise a numeric fallback is retained. --- skills/srcwalk/GUIDE.md | 2 +- src/lang/mod.rs | 1 + src/lang/qualified.rs | 198 ++++++++++++++++++ src/read/section.rs | 23 +-- src/search/display/semantic.rs | 82 ++++++-- src/search/display/structural_targets.rs | 109 +++++++--- src/search/symbol.rs | 3 +- src/search/symbol/definitions.rs | 49 +---- tests/intent_first_cli.rs | 32 ++- tests/us060b_anchor_seam.rs | 7 +- tests/us063_offer_dedupe.rs | 2 +- tests/us065_symbol_section_footer.rs | 247 +++++++++++++++++++++++ 12 files changed, 619 insertions(+), 136 deletions(-) create mode 100644 src/lang/qualified.rs create mode 100644 tests/us065_symbol_section_footer.rs diff --git a/skills/srcwalk/GUIDE.md b/skills/srcwalk/GUIDE.md index 33f84c2..48ae6af 100644 --- a/skills/srcwalk/GUIDE.md +++ b/skills/srcwalk/GUIDE.md @@ -66,7 +66,7 @@ Use auto overview depth first; explicit `--depth N` is strict. Narrow `overview 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. -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 `srcwalk show ...` command verbatim. It is symbol-addressed (`--section `) when the selector round-trips to the exact body, with a numeric `:` fallback for ambiguous names. 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. diff --git a/src/lang/mod.rs b/src/lang/mod.rs index f484342..831b9c4 100644 --- a/src/lang/mod.rs +++ b/src/lang/mod.rs @@ -4,6 +4,7 @@ pub mod detection; pub(crate) mod document; pub(crate) mod js_imports; pub mod outline; +pub(crate) mod qualified; pub(crate) mod ruby; pub(crate) mod scoped_occurrences; pub mod treesitter; diff --git a/src/lang/qualified.rs b/src/lang/qualified.rs new file mode 100644 index 0000000..d4f804c --- /dev/null +++ b/src/lang/qualified.rs @@ -0,0 +1,198 @@ +//! US-064 shared qualified-symbol primitives and outline resolution. +//! +//! `Type.method` (exactly one dot with both sides non-empty) resolves a +//! member `method` defined under container / on receiver `Type`. These rules +//! are shared between the search pipeline (`src/search/symbol/definitions.rs`) +//! and the `--section` reader (`src/read/section.rs`) so receiver/container +//! interpretation never diverges between discovery and read. + +use crate::types::{Lang, OutlineEntry, OutlineKind}; + +/// Split a `Q.N` symbol query — exactly one dot, both sides non-empty. +/// Multi-dot queries (`a.b.c`) and trailing/leading dots return `None`. +pub(crate) fn split_dot_symbol_query(query: &str) -> Option<(&str, &str)> { + let mut parts = query.split('.'); + let qualifier = parts.next()?; + let plain = parts.next()?; + if parts.next().is_some() || qualifier.is_empty() || plain.is_empty() { + return None; + } + Some((qualifier, plain)) +} + +/// Normalize a Go receiver type — strip leading `*` and generic params: +/// `*Batch` -> `Batch`, `syncQueue[T]` -> `syncQueue`. Single source of truth +/// shared by search and the `--section` reader. +pub(crate) fn normalize_receiver_type(receiver: &str) -> String { + let stripped = receiver.trim().trim_start_matches('*').trim(); + stripped + .chars() + .take_while(|&c| c != '[') + .collect::() + .trim() + .to_string() +} + +/// Normalize an outline container name — Rust `impl X` entries count as `X`. +pub(crate) fn normalize_outline_container(name: &str) -> String { + name.strip_prefix("impl ") + .unwrap_or(name) + .trim() + .to_string() +} + +/// Is this outline kind a container that qualifies its members? +pub(crate) fn outline_container_kind(kind: OutlineKind) -> bool { + matches!( + kind, + OutlineKind::Class + | OutlineKind::Struct + | OutlineKind::Module + | OutlineKind::Interface + | OutlineKind::Enum + ) +} + +/// Extract a Go receiver type from a method's outline signature. Signatures +/// look like `func (b *Batch) Set(...)`. Only real methods (receiver group +/// immediately after `func`) qualify; a plain `func Set(...)` returns `None`. +/// Normalization (pointer/value/generic) flows through `normalize_receiver_type`. +fn go_receiver_from_signature(signature: &str) -> Option { + let sig = signature.trim().strip_prefix("func")?.trim_start(); + if !sig.starts_with('(') { + return None; + } + let close = sig.find(')')?; + let receiver = &sig[1..close]; + let type_text = receiver.split_whitespace().last()?; + Some(normalize_receiver_type(type_text)) +} + +/// Resolve a symbol selector (bare name or `Q.N`) against a file's outline +/// entries, returning the first matching `(start_line, end_line)` inclusive. +/// +/// Exact dotted-name precedence is preserved: a legitimate exact entry.name / +/// signature / CSS / document dotted name is resolved before `Q.N` is +/// interpreted as qualifier + plain name. Bare names resolve through the exact +/// path only. +pub(crate) fn resolve_selector_first( + entries: &[OutlineEntry], + lang: Option, + selector: &str, +) -> Option<(u32, u32)> { + if let Some((start, end)) = find_exact_in_entries(entries, selector) { + return Some((start, end)); + } + if let Some((qualifier, plain)) = split_dot_symbol_query(selector) { + if let Some((start, end)) = qualified_outline_ranges(entries, lang, qualifier, plain) + .into_iter() + .next() + { + return Some((start, end)); + } + } + None +} + +/// Recursively find an exact entry.name / signature / CSS / document match. +fn find_exact_in_entries(entries: &[OutlineEntry], symbol: &str) -> Option<(u32, u32)> { + for entry in entries { + if entry.name == symbol + || entry.signature.as_deref() == Some(symbol) + || crate::lang::css::outline_name_matches(entry.kind, &entry.name, symbol) + || crate::lang::document::outline_name_matches(entry.kind, &entry.name, symbol) + { + return Some((entry.start_line, entry.end_line)); + } + if let Some((start, end)) = find_exact_in_entries(&entry.children, symbol) { + return Some((start, end)); + } + } + None +} + +/// Resolve `Q.N` against outline entries, threading container names down into +/// children (class/struct/module/interface/enum) and matching Go methods by +/// receiver type parsed from the signature. Returns every matching range. +fn qualified_outline_ranges( + entries: &[OutlineEntry], + lang: Option, + qualifier: &str, + plain: &str, +) -> Vec<(u32, u32)> { + let mut out = Vec::new(); + collect_qualified(entries, lang, qualifier, plain, None, &mut out); + out +} + +fn collect_qualified( + entries: &[OutlineEntry], + lang: Option, + qualifier: &str, + plain: &str, + container: Option<&str>, + out: &mut Vec<(u32, u32)>, +) { + for entry in entries { + if entry.name == plain { + let container_match = container == Some(qualifier); + let receiver_match = lang == Some(Lang::Go) + && entry.kind == OutlineKind::Function + && entry + .signature + .as_deref() + .and_then(go_receiver_from_signature) + .as_deref() + == Some(qualifier); + if container_match || receiver_match { + out.push((entry.start_line, entry.end_line)); + } + } + let child_container = if outline_container_kind(entry.kind) { + Some(normalize_outline_container(&entry.name)) + } else { + container.map(str::to_string) + }; + collect_qualified( + &entry.children, + lang, + qualifier, + plain, + child_container.as_deref(), + out, + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn receiver_normalization_covers_pointer_value_and_generic() { + assert_eq!(normalize_receiver_type("*Batch"), "Batch"); + assert_eq!(normalize_receiver_type("*syncQueue[T]"), "syncQueue"); + assert_eq!(normalize_receiver_type("syncQueue[T]"), "syncQueue"); + assert_eq!(normalize_receiver_type("Queue"), "Queue"); + assert_eq!(normalize_receiver_type("*pkg[K,V]"), "pkg"); + assert_eq!(normalize_receiver_type(" *Batch "), "Batch"); + } + + #[test] + fn go_receiver_from_signature_distinguishes_method_from_function() { + assert_eq!( + go_receiver_from_signature("func (b *Batch) Set(v int)"), + Some("Batch".to_string()) + ); + assert_eq!( + go_receiver_from_signature("func (b Batch) Value()"), + Some("Batch".to_string()) + ); + assert_eq!( + go_receiver_from_signature("func (q *syncQueue[T]) Push(x T)"), + Some("syncQueue".to_string()) + ); + // A plain function has no receiver group right after `func`. + assert_eq!(go_receiver_from_signature("func Set(x int) int"), None); + } +} diff --git a/src/read/section.rs b/src/read/section.rs index 059572a..510187f 100644 --- a/src/read/section.rs +++ b/src/read/section.rs @@ -1044,7 +1044,10 @@ fn resolve_symbol(buf: &[u8], path: &Path, symbol: &str) -> Option<(usize, usize let content = std::str::from_utf8(buf).ok()?; let lang = detect_file_type(path).structural_lang()?; let entries = lang_get_outline_entries(content, lang); - find_symbol_in_entries(&entries, symbol) + // Shared US-064 resolver: exact dotted-name precedence first, then `Q.N` + // qualifier + plain-name interpretation (container / Go receiver). + crate::lang::qualified::resolve_selector_first(&entries, Some(lang), symbol) + .map(|(start, end)| (start as usize, end as usize)) } /// Collect symbol names from outline entries (recursively) with their line ranges, @@ -1094,24 +1097,6 @@ fn collect_symbol_names<'a>(entries: &'a [OutlineEntry], out: &mut Vec<(&'a str, } } -/// Recursively search for a symbol in outline entries. -fn find_symbol_in_entries(entries: &[OutlineEntry], symbol: &str) -> Option<(usize, usize)> { - for entry in entries { - if entry.name == symbol - || entry.signature.as_deref() == Some(symbol) - || crate::lang::css::outline_name_matches(entry.kind, &entry.name, symbol) - || crate::lang::document::outline_name_matches(entry.kind, &entry.name, symbol) - { - return Some((entry.start_line as usize, entry.end_line as usize)); - } - // Search children (methods inside class, etc.) - if let Some(range) = find_symbol_in_entries(&entry.children, symbol) { - return Some(range); - } - } - None -} - #[cfg(test)] mod precision_tests { use super::*; diff --git a/src/search/display/semantic.rs b/src/search/display/semantic.rs index f212a0c..440fe87 100644 --- a/src/search/display/semantic.rs +++ b/src/search/display/semantic.rs @@ -47,6 +47,14 @@ pub(in crate::search) struct SemanticChild { pub(super) struct ContextTarget { pub(super) start_line: u32, pub(super) end_line: u32, + /// Parser-backed symbol selector (bare name or `Type.method`) that resolves + /// back to this target's range, or the closest stable selector when + /// `symbol_backed` is false. + pub(super) selector: String, + /// True when `selector` round-trips to exactly `(start_line, end_line)` in + /// this file, so the `show path --section ` footer is safe to + /// emit. False targets fall back to a numeric range command. + pub(super) symbol_backed: bool, } pub(super) fn context_target_for_match(m: &Match, cache: &OutlineCache) -> Option { @@ -60,20 +68,32 @@ pub(super) fn context_target_for_match(m: &Match, cache: &OutlineCache) -> Optio return None; } + let entries = structured_outline_entries(&m.path, cache)?; + if m.is_definition { - if let Some(candidate) = semantic_candidate_for_match(m, cache) { + let range = m.def_range.unwrap_or((m.line, m.line)); + if let Some(candidate) = best_semantic_candidate(&entries, m) { if candidate.kind == OutlineKind::Function { - return Some(ContextTarget { - start_line: candidate.start_line, - end_line: candidate.end_line, - }); + // US-064: `m.def_name` retains the parser-backed `Q.N` form for + // qualified matches, so the footer carries the same selector + // the discover query used instead of reconstructing it. + let selector = m.def_name.clone().unwrap_or_else(|| candidate.name.clone()); + return Some(build_target( + &m.path, + &entries, + candidate.start_line, + candidate.end_line, + selector, + )); } } - if let Some((start_line, end_line)) = function_definition_range_from_outline(m, cache) { - return Some(ContextTarget { - start_line, - end_line, - }); + if let Some((start_line, end_line)) = + find_function_definition_range(&entries, range, m.def_name.as_deref()) + { + let selector = m.def_name.clone().unwrap_or_else(|| start_line.to_string()); + return Some(build_target( + &m.path, &entries, start_line, end_line, selector, + )); } return None; } @@ -82,12 +102,37 @@ pub(super) fn context_target_for_match(m: &Match, cache: &OutlineCache) -> Optio return None; } - let entries = structured_outline_entries(&m.path, cache)?; let candidate = best_enclosing_function(&entries, m.line)?; - Some(ContextTarget { - start_line: candidate.start_line, - end_line: candidate.end_line, - }) + let selector = candidate.name.clone(); + Some(build_target( + &m.path, + &entries, + candidate.start_line, + candidate.end_line, + selector, + )) +} + +/// Build a `ContextTarget` from a candidate range and parser-backed selector. +/// `symbol_backed` is true only when the selector resolves back to exactly this +/// range (round-trip check), so the footer never emits a symbol command that +/// would read a different body. +fn build_target( + path: &Path, + entries: &[OutlineEntry], + start_line: u32, + end_line: u32, + selector: String, +) -> ContextTarget { + let lang = crate::lang::detect_file_type(path).structural_lang(); + let symbol_backed = crate::lang::qualified::resolve_selector_first(entries, lang, &selector) + == Some((start_line, end_line)); + ContextTarget { + start_line, + end_line, + selector, + symbol_backed, + } } pub(super) fn format_definition_semantic_match( @@ -413,13 +458,6 @@ fn collect_semantic_candidates( } } -fn function_definition_range_from_outline(m: &Match, cache: &OutlineCache) -> Option<(u32, u32)> { - let range = m.def_range?; - let wanted = m.def_name.as_deref(); - let entries = structured_outline_entries(&m.path, cache)?; - find_function_definition_range(&entries, range, wanted) -} - fn find_function_definition_range( entries: &[OutlineEntry], range: (u32, u32), diff --git a/src/search/display/structural_targets.rs b/src/search/display/structural_targets.rs index ca625e5..ef47860 100644 --- a/src/search/display/structural_targets.rs +++ b/src/search/display/structural_targets.rs @@ -18,6 +18,12 @@ struct StructuralTarget { path: PathBuf, start_line: u32, end_line: u32, + /// Parser-backed symbol selector (bare name or `Type.method`) that resolves + /// back to this target's range when `symbol_backed` is true. + selector: String, + /// True when the footer may emit `show path --section ` safely + /// (the selector round-trips to exactly this range in this file). + symbol_backed: bool, } impl StructuralTarget { @@ -110,6 +116,8 @@ fn collect_structural_targets( path: m.path.clone(), start_line: target.start_line, end_line: target.end_line, + selector: target.selector, + symbol_backed: target.symbol_backed, }); if targets.len() == 3 { break; @@ -158,40 +166,18 @@ fn show_actions_for_targets( )); } - if narrow.len() == 1 { - let target = narrow[0]; + // Each narrow target is offered as its own symbol-addressed read command + // (`show --section `). Different targets carry different + // selectors, so they can no longer be merged into one numeric batched + // `path:A-B,path:C-D` command. + for (index, target) in narrow.iter().enumerate() { actions.push(NextAction::from_evidence( show_command_for_target(target, scope), "read confirmed structural source target", - 10, + 10 + index as u16, EvidenceSource::Ast, target.anchor(), )); - } else if !narrow.is_empty() - && narrow - .iter() - .any(|target| target.requires_section_form(scope)) - { - for (index, target) in narrow.iter().enumerate() { - actions.push(NextAction::from_evidence( - show_command_for_target(target, scope), - "read confirmed structural source target", - 10 + index as u16, - EvidenceSource::Ast, - target.anchor(), - )); - } - } else if !narrow.is_empty() { - let joined = narrow - .iter() - .map(|target| target.location_arg_relative_to(scope)) - .collect::>() - .join(","); - actions.push(NextAction::guidance( - format!("srcwalk show {}", quote_or_placeholder(&joined)), - "read confirmed structural source targets", - 10, - )); } actions } @@ -222,6 +208,18 @@ fn truncate_label(reason: &str) -> &str { } fn show_command_for_target(target: &StructuralTarget, scope: &Path) -> String { + // Symbol form: `show --section ` for a round-tripping + // parser-backed selector. The path is quoted separately so a comma inside + // a quoted path never becomes a multi-target command. + if target.symbol_backed { + return format!( + "srcwalk show {} --section {}", + quote_or_placeholder(&target.path_arg_relative_to(scope)), + quote_or_placeholder(&target.selector) + ); + } + + // Numeric fallback for exceptional targets with no stable symbol selector. if target.requires_section_form(scope) { return format!( "srcwalk show {} --section {}", @@ -249,6 +247,23 @@ mod tests { path: PathBuf::from(path), start_line, end_line, + selector: String::new(), + symbol_backed: false, + } + } + + fn symbol_target( + path: &str, + start_line: u32, + end_line: u32, + selector: &str, + ) -> StructuralTarget { + StructuralTarget { + path: PathBuf::from(path), + start_line, + end_line, + selector: selector.to_string(), + symbol_backed: true, } } @@ -274,11 +289,39 @@ mod tests { scope, &RenderedSourceLines::default(), ); - assert_eq!(actions.len(), 1); - assert_eq!( - actions[0].command(), - "srcwalk show 'a file.rs:1-1,b file.rs:2-2'" - ); + // Distinct targets are no longer merged into one numeric command; + // each is offered on its own line. + assert_eq!(actions.len(), 2); + assert_eq!(actions[0].command(), "srcwalk show 'a file.rs:1-1'"); + assert_eq!(actions[1].command(), "srcwalk show 'b file.rs:2-2'"); + } + + #[test] + fn symbol_target_renders_symbol_section_command() { + let scope = Path::new(""); + let command = show_command_for_target(&symbol_target("lib.rs", 1, 3, "target"), scope); + assert_eq!(command, "srcwalk show lib.rs --section target"); + } + + #[test] + fn symbol_target_preserves_qualified_selector() { + let scope = Path::new(""); + let command = show_command_for_target(&symbol_target("batch.go", 3, 3, "Batch.Set"), scope); + assert_eq!(command, "srcwalk show batch.go --section Batch.Set"); + } + + #[test] + fn symbol_target_quotes_space_path_and_selector() { + let scope = Path::new(""); + let command = show_command_for_target(&symbol_target("a file.rs", 1, 3, "my fn"), scope); + assert_eq!(command, "srcwalk show 'a file.rs' --section 'my fn'"); + } + + #[test] + fn symbol_target_keeps_comma_path_quoted() { + let scope = Path::new(""); + let command = show_command_for_target(&symbol_target("a,file.rs", 1, 3, "target"), scope); + assert_eq!(command, "srcwalk show 'a,file.rs' --section target"); } #[test] diff --git a/src/search/symbol.rs b/src/search/symbol.rs index e54e325..051dc0a 100644 --- a/src/search/symbol.rs +++ b/src/search/symbol.rs @@ -7,10 +7,9 @@ mod glob_search; mod suggest; mod usages; +pub(crate) use crate::lang::qualified::{normalize_receiver_type, split_dot_symbol_query}; use comments::tag_comment_matches; use definitions::find_definitions_with_artifact; -pub(crate) use definitions::normalize_receiver_type; -pub(crate) use definitions::split_dot_symbol_query; #[cfg(test)] use definitions::{find_artifact_anchor_defs, find_defs_treesitter}; use usages::find_usages_with_artifact; diff --git a/src/search/symbol/definitions.rs b/src/search/symbol/definitions.rs index ef118c9..c12189b 100644 --- a/src/search/symbol/definitions.rs +++ b/src/search/symbol/definitions.rs @@ -6,6 +6,10 @@ use std::time::SystemTime; use crate::error::SrcwalkError; use crate::lang::detect_file_type; use crate::lang::outline::outline_language; +use crate::lang::qualified::{ + normalize_outline_container, normalize_receiver_type, outline_container_kind, + split_dot_symbol_query, +}; use crate::lang::treesitter::{ definition_weight, elixir_definition_weight, extract_base_list_targets, extract_definition_name, extract_elixir_definition_name, extract_impl_trait, extract_impl_type, @@ -307,18 +311,6 @@ fn outline_entry_matches_query(entry: &OutlineEntry, query: &str) -> bool { || crate::lang::document::outline_name_matches(entry.kind, &entry.name, query) } -/// US-064: split a `Q.N` symbol query — exactly one dot, both sides non-empty. -/// Multi-dot queries (`a.b.c`) and trailing/leading dots return `None`. -pub(crate) fn split_dot_symbol_query(query: &str) -> Option<(&str, &str)> { - let mut parts = query.split('.'); - let qualifier = parts.next()?; - let plain = parts.next()?; - if parts.next().is_some() || qualifier.is_empty() || plain.is_empty() { - return None; - } - Some((qualifier, plain)) -} - /// US-064: extract a Go receiver type from a `method_declaration` node. /// The receiver is the first `parameter_list` child; its type is the last /// named child of the receiver's `parameter_declaration`. @@ -343,19 +335,6 @@ fn go_receiver_type_from_node(node: tree_sitter::Node, lines: &[&str]) -> Option Some(normalize_receiver_type(&text)) } -/// US-064: normalize a Go receiver type — strip leading `*` and generic -/// params: `*Batch` → `Batch`, `syncQueue[T]` → `syncQueue`. Shared with the -/// display layer's ambiguity assist (single source of truth). -pub(crate) fn normalize_receiver_type(receiver: &str) -> String { - let stripped = receiver.trim().trim_start_matches('*').trim(); - stripped - .chars() - .take_while(|&c| c != '[') - .collect::() - .trim() - .to_string() -} - /// US-064: container name if `node` is a container (class/struct/object/ /// impl/module/enum). Rust `impl X` / `impl T for X` counts as `X` /// (`extract_impl_type` returns the implemented type). @@ -399,26 +378,6 @@ fn qualified_def_matches( && go_receiver_type_from_node(node, lines).as_deref() == Some(qualifier) } -/// US-064: is this outline kind a container that qualifies its members? -fn outline_container_kind(kind: OutlineKind) -> bool { - matches!( - kind, - OutlineKind::Class - | OutlineKind::Struct - | OutlineKind::Module - | OutlineKind::Interface - | OutlineKind::Enum - ) -} - -/// US-064: normalize an outline container name — `impl X` entries count as `X`. -fn normalize_outline_container(name: &str) -> String { - name.strip_prefix("impl ") - .unwrap_or(name) - .trim() - .to_string() -} - fn collect_outline_defs( entries: &[OutlineEntry], query: &str, diff --git a/tests/intent_first_cli.rs b/tests/intent_first_cli.rs index 67186ce..ffaa467 100644 --- a/tests/intent_first_cli.rs +++ b/tests/intent_first_cli.rs @@ -1506,12 +1506,16 @@ fn caller() -> i32 { "{stdout}" ); assert!( - stdout.contains("> Next: srcwalk show 'lib.rs:1-3,lib.rs:7-9'"), + stdout.contains("> Next: srcwalk show lib.rs --section target"), + "{stdout}" + ); + assert!( + stdout.contains("> Next: srcwalk show lib.rs --section caller"), "{stdout}" ); assert_eq!( stdout - .matches("> Next: srcwalk show 'lib.rs:1-3,lib.rs:7-9'") + .matches("> Next: srcwalk show lib.rs --section target") .count(), 1, "confirmed structural next action should be deduplicated:\n{stdout}" @@ -1595,15 +1599,19 @@ fn discover_multiple_structural_matches_suggest_batched_show_target() { "{stdout}" ); assert!( - stdout.contains("> Next: srcwalk show 'a/lib.rs:1-1,b/lib.rs:1-1'"), - "expected one batched show next action:\n{stdout}" + stdout.contains("> Next: srcwalk show a/lib.rs --section target"), + "expected symbol show next action:\n{stdout}" + ); + assert!( + stdout.contains("> Next: srcwalk show b/lib.rs --section target"), + "expected symbol show next action:\n{stdout}" ); assert_eq!( stdout - .matches("> Next: srcwalk show 'a/lib.rs:1-1,b/lib.rs:1-1'") + .matches("> Next: srcwalk show a/lib.rs --section target") .count(), 1, - "batched show next action should be deduplicated:\n{stdout}" + "symbol show next action should be deduplicated:\n{stdout}" ); assert!( !stdout.contains("srcwalk context a/lib.rs:1-1"), @@ -1627,7 +1635,7 @@ fn discover_structural_show_targets_quote_spaces_and_comma_paths() { assert!(output.status.success()); let stdout = String::from_utf8_lossy(&output.stdout); assert!( - stdout.contains("> Next: srcwalk show 'a file.rs:1-1'"), + stdout.contains("> Next: srcwalk show 'a file.rs' --section target"), "space-bearing target must be shell-quoted:\n{stdout}" ); @@ -1643,8 +1651,8 @@ fn discover_structural_show_targets_quote_spaces_and_comma_paths() { assert!(output.status.success()); let stdout = String::from_utf8_lossy(&output.stdout); assert!( - stdout.contains("> Next: srcwalk show 'a,file.rs' --section 1-1"), - "comma-bearing path must use --section instead of ambiguous inline target:\n{stdout}" + stdout.contains("> Next: srcwalk show 'a,file.rs' --section target"), + "comma-bearing path must use --section with a symbol selector:\n{stdout}" ); assert!( !stdout.contains("srcwalk show a,file.rs:1-1"), @@ -1692,7 +1700,11 @@ export function startServer() { "{stdout}" ); assert!( - stdout.contains("> Next: srcwalk show 'server.ts:3-8,server.ts:10-12'"), + stdout.contains("> Next: srcwalk show server.ts --section createGatewayServer"), + "{stdout}" + ); + assert!( + stdout.contains("> Next: srcwalk show server.ts --section startServer"), "{stdout}" ); assert!( diff --git a/tests/us060b_anchor_seam.rs b/tests/us060b_anchor_seam.rs index 97f19b7..e18a495 100644 --- a/tests/us060b_anchor_seam.rs +++ b/tests/us060b_anchor_seam.rs @@ -82,10 +82,11 @@ fn discover_offers_no_bare_range_wider_than_forty() { String::from_utf8_lossy(&out.stderr) ); let stdout = String::from_utf8_lossy(&out.stdout); - // The wide definition range is anchored, not offered bare. + // The wide definition range is anchored to a symbol-addressed expand + // command, not offered bare. assert!( - stdout.contains("> expand: srcwalk show target.js:"), - "wide range should be anchored with an expand command, got:\n{stdout}" + stdout.contains("> expand: srcwalk show target.js --section target"), + "wide range should be anchored with a symbol expand command, got:\n{stdout}" ); // No bare offer exposes a >40-line range. let widths = bare_offered_widths(&stdout); diff --git a/tests/us063_offer_dedupe.rs b/tests/us063_offer_dedupe.rs index 7531002..dc688c9 100644 --- a/tests/us063_offer_dedupe.rs +++ b/tests/us063_offer_dedupe.rs @@ -69,7 +69,7 @@ fn discover_keeps_offer_when_source_not_rendered() { ); let stdout = String::from_utf8_lossy(&out.stdout); assert!( - stdout.contains("> Next: srcwalk show lib.js:1-6"), + stdout.contains("> Next: srcwalk show lib.js --section target"), "unrendered target should still be offered:\n{stdout}" ); let _ = fs::remove_dir_all(&dir); diff --git a/tests/us065_symbol_section_footer.rs b/tests/us065_symbol_section_footer.rs new file mode 100644 index 0000000..4b56871 --- /dev/null +++ b/tests/us065_symbol_section_footer.rs @@ -0,0 +1,247 @@ +//! Symbol-addressed confirmed-structural-target footer + qualified `--section` +//! resolution. +//! +//! The discover footer points to `srcwalk show --section ` +//! (bare or `Type.method`) instead of a numeric range, so models read the +//! parser-backed symbol body rather than guessing numeric ranges. The +//! `--section` reader resolves `Q.N` receiver/container-qualified symbols +//! matching US-064 discover semantics. + +use std::fs; +use std::path::PathBuf; +use std::process::Command; + +fn srcwalk() -> Command { + Command::new(env!("CARGO_BIN_EXE_srcwalk")) +} + +struct Fixture { + dir: PathBuf, +} + +impl Fixture { + fn new(name: &str, files: &[(&str, &str)]) -> Self { + let dir = std::env::temp_dir().join(format!( + "us065_footer_{name}_{}_{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()) + )); + fs::create_dir_all(&dir).unwrap(); + for (rel, content) in files { + let path = dir.join(rel); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).unwrap(); + } + fs::write(path, content).unwrap(); + } + Self { dir } + } + + fn run(&self, args: &[&str]) -> (bool, String) { + let out = srcwalk() + .current_dir(&self.dir) + .args(args) + .output() + .unwrap(); + ( + out.status.success(), + String::from_utf8_lossy(&out.stdout).into_owned() + + &String::from_utf8_lossy(&out.stderr), + ) + } + + fn discover(&self, args: &[&str]) -> String { + let (ok, out) = self.run(args); + assert!(ok, "command {:?} failed:\n{out}", args); + out + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.dir); + } +} + +// ---------------------------------------------------------------- footer A + +#[test] +fn discover_bare_function_emits_symbol_section_command() { + let fx = Fixture::new( + "bare_fn", + &[( + "lib.rs", + "fn target() -> i32 {\n helper()\n}\n\nfn helper() -> i32 { 1 }\n", + )], + ); + let out = fx.discover(&["discover", "target", "--scope", "."]); + assert!(out.contains("## Confirmed structural targets"), "{out}"); + assert!( + out.contains("> Next: srcwalk show lib.rs --section target"), + "{out}" + ); + assert!( + !out.contains("srcwalk show 'lib.rs:1-3'") && !out.contains("srcwalk show lib.rs:1-3"), + "no numeric read command should be emitted:\n{out}" + ); +} + +#[test] +fn discover_qualified_preserves_qualified_selector() { + let fx = Fixture::new( + "qualified", + &[( + "batch.go", + "package db\n\ntype Batch struct{}\n\nfunc (b *Batch) Set(v int) {}\n", + )], + ); + let out = fx.discover(&["discover", "Batch.Set", "--as", "symbol", "--scope", "."]); + assert!( + out.contains("> Next: srcwalk show batch.go --section Batch.Set"), + "{out}" + ); +} + +#[test] +fn ambiguous_bare_name_falls_back_to_numeric_for_unresolvable_target() { + let fx = Fixture::new( + "ambiguous", + &[( + "lib.rs", + "fn helper() -> i32 { 1 }\nfn other() -> i32 { 2 }\nfn helper() -> i32 { 3 }\n", + )], + ); + let out = fx.discover(&["discover", "helper", "--scope", "."]); + // The first `helper` round-trips via the bare symbol; the second same-name + // `helper` cannot round-trip (the bare selector reads the first), so it + // must fall back to a numeric range rather than point at the wrong body. + assert!( + out.contains("> Next: srcwalk show lib.rs --section helper"), + "{out}" + ); + assert!(out.contains("> Next: srcwalk show lib.rs:3-3"), "{out}"); +} + +#[test] +fn discover_quotes_space_and_comma_paths_in_symbol_command() { + let fx = Fixture::new("quoted", &[("a file.rs", "fn target() -> i32 { 1 }\n")]); + let out = fx.discover(&["discover", "target", "--scope", "."]); + assert!( + out.contains("> Next: srcwalk show 'a file.rs' --section target"), + "{out}" + ); + + fs::remove_file(fx.dir.join("a file.rs")).unwrap(); + fs::write(fx.dir.join("a,file.rs"), "fn target() -> i32 { 1 }\n").unwrap(); + let out = fx.discover(&["discover", "target", "--scope", "."]); + assert!( + out.contains("> Next: srcwalk show 'a,file.rs' --section target"), + "comma path must stay quoted and single-target:\n{out}" + ); +} + +// ------------------------------------------------------- section resolution B + +#[test] +fn rust_impl_qualified_section_reads_correct_method() { + let fx = Fixture::new( + "rust_impl", + &[( + "service.rs", + "pub struct Service;\nimpl Service {\n pub fn run(&self) {}\n pub fn stop(&self) {}\n}\n", + )], + ); + let (ok, out) = fx.run(&["show", "service.rs", "--section", "Service.run"]); + assert!(ok, "{out}"); + assert!(out.contains("pub fn run(&self)"), "{out}"); + assert!(!out.contains("pub fn stop"), "wrong method body:\n{out}"); + + // Bare method still works. + let (ok, out) = fx.run(&["show", "service.rs", "--section", "stop"]); + assert!(ok, "{out}"); + assert!(out.contains("pub fn stop(&self)"), "{out}"); +} + +#[test] +fn nested_classes_same_method_qualified_selects_correct_and_wrong_fails() { + let fx = Fixture::new( + "py_two_classes", + &[( + "config.py", + "class Alpha:\n def run(self):\n return 1\n\nclass Beta:\n def run(self):\n return 2\n", + )], + ); + let (ok, out) = fx.run(&["show", "config.py", "--section", "Alpha.run"]); + assert!(ok, "{out}"); + assert!( + out.contains("return 1"), + "Alpha.run must select Alpha's body:\n{out}" + ); + assert!(!out.contains("return 2"), "wrong container body:\n{out}"); + + let (ok, out) = fx.run(&["show", "config.py", "--section", "Beta.run"]); + assert!(ok, "{out}"); + assert!( + out.contains("return 2"), + "Beta.run must select Beta's body:\n{out}" + ); + + // Wrong qualifier is rejected. + let (ok, _) = fx.run(&["show", "config.py", "--section", "Nope.run"]); + assert!(!ok, "wrong qualifier must not silently resolve"); +} + +#[test] +fn go_receiver_qualified_section_reads_pointer_value_generic() { + let fx = Fixture::new( + "go_receivers", + &[( + "db/batch.go", + "package db\n\ntype Batch struct{}\ntype syncQueue[T any] struct{}\n\nfunc (b *Batch) Ptr() {}\nfunc (b Batch) Val() {}\nfunc (q *syncQueue[T]) Gen() {}\n", + )], + ); + for (selector, body) in [ + ("Batch.Ptr", "func (b *Batch) Ptr()"), + ("Batch.Val", "func (b Batch) Val()"), + ("syncQueue.Gen", "func (q *syncQueue[T]) Gen()"), + ] { + let (ok, out) = fx.run(&["show", "db/batch.go", "--section", selector]); + assert!(ok, "selector {selector} failed:\n{out}"); + assert!(out.contains(body), "selector {selector} wrong body:\n{out}"); + } +} + +#[test] +fn exact_dotted_outline_name_wins_before_qualified_interpretation() { + let fx = Fixture::new( + "elixir_dotted", + &[( + "app.ex", + "defmodule Foo.Bar do\n def hello do\n :world\n end\nend\n", + )], + ); + // `Foo.Bar` is a real dotted module name; it must resolve as the module, + // not as qualifier `Foo` + member `Bar`. + let (ok, out) = fx.run(&["show", "app.ex", "--section", "Foo.Bar"]); + assert!(ok, "{out}"); + assert!(out.contains("defmodule Foo.Bar"), "{out}"); +} + +#[test] +fn multi_dot_and_empty_side_selectors_reject_without_exact_match() { + let fx = Fixture::new( + "invalid_dots", + &[( + "app.ex", + "defmodule Foo.Bar do\n def hello do\n :world\n end\nend\n", + )], + ); + // Multi-dot is not a qualified symbol (no exact dotted name matches). + let (ok, _) = fx.run(&["show", "app.ex", "--section", "Foo.Bar.hello"]); + assert!(!ok, "multi-dot must not resolve as a qualified symbol"); + // Emptydot side is invalid. + let (ok, _) = fx.run(&["show", "app.ex", "--section", ".Bar"]); + assert!(!ok, "leading-dot must not resolve"); +} From 57934c05223fad51dbb0077f5e1bceba2012033d Mon Sep 17 00:00:00 2001 From: sting8k Date: Tue, 11 Aug 2026 11:47:53 +0700 Subject: [PATCH 02/26] feat: symbol-first confirmed-target action hierarchy For confirmed structural targets, promote the strongest body address to the single primary action instead of letting numeric ranges compete: - Stable symbol-backed targets (wide or narrow) emit the symbol command as the primary `> Next:`; the numeric range stays visible as a plain, non-action ` evidence anchor: :` metadata line (START line only, never a full body range and never a `>`-shaped action hint). - Ambiguous / non-round-tripping selectors keep the numeric command as the primary `> Next:` and are labeled once at block level with a fallback note. - Header teaches the classification (run printed Next; symbol when stable, numeric as fallback) instead of implying every target is symbolic. - The trailing generic "read the confirmed structural target above" guidance is suppressed whenever a confirmed-target block exists, so it cannot compete as a second primary action; numeric exact-hit guidance is preserved for non-structural text/access/name-occurrence searches. - Non-structural text/access/partial-completion hints stay numeric unchanged. Carries the parser-backed selector/round-trip from US-065 through ContextTarget; no symbol identity inferred from rendered strings. Preserves US-060b bounded wide evidence, US-063 dedupe/suppression, line caps, and shell quoting. --- skills/srcwalk/GUIDE.md | 2 +- src/evidence/next_action.rs | 18 ++ src/search/display/mod.rs | 17 +- src/search/display/structural_targets.rs | 282 +++++++++++++++++------ tests/intent_first_cli.rs | 11 +- tests/us060b_anchor_seam.rs | 34 ++- tests/us065_symbol_section_footer.rs | 22 ++ 7 files changed, 296 insertions(+), 90 deletions(-) diff --git a/skills/srcwalk/GUIDE.md b/skills/srcwalk/GUIDE.md index 48ae6af..194dd96 100644 --- a/skills/srcwalk/GUIDE.md +++ b/skills/srcwalk/GUIDE.md @@ -66,7 +66,7 @@ Use auto overview depth first; explicit `--depth N` is strict. Narrow `overview 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. -If `discover` prints `## Confirmed structural targets`, run the printed `srcwalk show ...` command verbatim. It is symbol-addressed (`--section `) when the selector round-trips to the exact body, with a numeric `:` fallback for ambiguous names. 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. 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/search/display/mod.rs b/src/search/display/mod.rs index 80513e1..359c9ba 100644 --- a/src/search/display/mod.rs +++ b/src/search/display/mod.rs @@ -951,15 +951,18 @@ pub(super) fn format_search_result_with_header( ); } - if result.total_found > 0 { - let guidance = if has_structural_next_targets { - "read the confirmed structural target above, or use `srcwalk context ` only when you need a Flow Map or call neighborhood." - } else { - "read exact hit evidence with `srcwalk show : -C 10`." - }; + // When a confirmed-structural-target block exists, it already owns the + // next action(s); appending a generic guidance `> Next:` here would create + // a competing primary action. Only add the numeric exact-hit guidance when + // there is no structural target (text/access/name occurrence evidence). + if result.total_found > 0 && !has_structural_next_targets { append_next_action( &mut footer, - NextAction::guidance(guidance, "read exact hit evidence", 50), + NextAction::guidance( + "read exact hit evidence with `srcwalk show : -C 10`.", + "read exact hit evidence", + 50, + ), ); } diff --git a/src/search/display/structural_targets.rs b/src/search/display/structural_targets.rs index ef47860..d71cfd3 100644 --- a/src/search/display/structural_targets.rs +++ b/src/search/display/structural_targets.rs @@ -14,6 +14,18 @@ use crate::types::SearchResult; use super::semantic; use super::RenderedSourceLines; +/// Header line for the confirmed-target block. It teaches the classification +/// (run the printed `Next` command; symbol when stable, numeric as a safe +/// fallback) instead of claiming every target is symbol-addressed. +const CONFIRMED_TARGETS_HEADER: &str = + "## Confirmed structural targets - run the printed Next command (symbol when stable; numeric as fallback)"; + +/// Single line emitted after any numeric-fallback targets. Kept at block level +/// so several fallbacks in one output share one explanation instead of +/// repeating it after every target. +const NUMERIC_FALLBACK_NOTE: &str = + "> Note: numeric fallback - no unique symbol selector resolves to the exact body, so the printed range is the safe read."; + struct StructuralTarget { path: PathBuf, start_line: u32, @@ -69,7 +81,8 @@ pub(super) fn append_structural_next_targets( return false; } - let actions = show_actions_for_targets(&targets, &result.scope, rendered_lines); + let (actions, fallback_count) = + show_actions_for_targets(&targets, &result.scope, rendered_lines); let rendered = render_next_actions(&actions); if rendered.is_empty() { let target = &targets[0]; @@ -92,8 +105,15 @@ pub(super) fn append_structural_next_targets( } return true; } - out.push_str("\n\n## Confirmed structural targets\n"); + out.push('\n'); + out.push('\n'); + out.push_str(CONFIRMED_TARGETS_HEADER); + out.push('\n'); out.push_str(&rendered); + if fallback_count > 0 { + out.push('\n'); + out.push_str(NUMERIC_FALLBACK_NOTE); + } true } @@ -126,11 +146,13 @@ fn collect_structural_targets( targets } +/// Build the confirmed-target actions plus how many of them are numeric +/// fallbacks (used to emit a single block-level explanation). fn show_actions_for_targets( targets: &[StructuralTarget], scope: &Path, rendered: &RenderedSourceLines, -) -> Vec { +) -> (Vec, usize) { let ranges = targets .iter() .map(|target| (target.start_line, target.end_line)) @@ -145,32 +167,49 @@ fn show_actions_for_targets( .collect::>(); if kept_targets.is_empty() { - return Vec::new(); + return (Vec::new(), 0); } - // US-060b: split wide (>W-line) targets out of every offer path so each - // anchors to `path:line (label)` + an `expand: srcwalk show path:A-B` - // command instead of being offered bare. The expand command preserves the - // exact range (section form for comma paths), so the full range is always - // exactly one printed command away. + // US-060b: split wide (>W-line) targets out so their numeric range anchors + // to a bounded `> anchor:` evidence line instead of being offered bare. let (wide, narrow): (Vec<_>, Vec<_>) = kept_targets.into_iter().partition(|target| { precision::should_anchor_range((target.end_line - target.start_line + 1) as usize) }); let mut actions = Vec::new(); + let mut fallback_count = 0; + for target in &wide { - actions.push(NextAction::guidance( - anchored_offer(target, scope, "read confirmed structural source target"), - "read confirmed structural source target", - 10, - )); + if target.symbol_backed { + // Stable parser-backed selector: the symbol command is the primary + // action; the numeric range is non-action evidence metadata. + actions.push( + NextAction::guidance( + show_command_for_target(target, scope), + "read confirmed structural source target", + 10, + ) + .with_preamble([anchor_line(target, scope)]), + ); + } else { + // Ambiguous / non-round-tripping selector: numeric fallback stays + // the primary action and is honestly labeled at block level. + fallback_count += 1; + actions.push(NextAction::guidance( + show_command_for_target(target, scope), + "read confirmed structural source target", + 10, + )); + } } - // Each narrow target is offered as its own symbol-addressed read command - // (`show --section `). Different targets carry different - // selectors, so they can no longer be merged into one numeric batched - // `path:A-B,path:C-D` command. + // Each narrow target is offered as its own read command. Symbol-backed + // targets use `show --section `; the rest fall back to a + // numeric range and are labeled at block level. for (index, target) in narrow.iter().enumerate() { + if !target.symbol_backed { + fallback_count += 1; + } actions.push(NextAction::from_evidence( show_command_for_target(target, scope), "read confirmed structural source target", @@ -179,34 +218,21 @@ fn show_actions_for_targets( target.anchor(), )); } - actions + (actions, fallback_count) } -/// US-060b: build the anchored offer for a wide target — a single-line -/// `path:start (label)` anchor plus an `> expand:` command that retrieves the -/// full range in exactly one printed command (preserving section form for comma -/// paths). Rendered as two `> `-prefixed lines by `render_next_actions`. -fn anchored_offer(target: &StructuralTarget, scope: &Path, reason: &str) -> String { - let label = truncate_label(reason); - let path = format::rel_nonempty(&target.path, scope); +/// US-060b: keep the numeric range of a wide target visible as evidence while +/// making clear it is a bounded preview, not the body address. Rendered as a +/// plain (non-action) line using only the START line, so it never looks like a +/// hint that could be re-read as a numeric range. The symbol command on the +/// `> Next:` line is the recommended action. +fn anchor_line(target: &StructuralTarget, scope: &Path) -> String { format!( - "{}:{} ({label})\n> expand: {}", - path, - target.start_line, - show_command_for_target(target, scope) + " evidence anchor: {} (bounded preview; not the body address)", + Anchor::line(&target.path, target.start_line).display_relative_to(scope) ) } -/// Keep the anchor label short enough for a single-line `path:line (label)`. -fn truncate_label(reason: &str) -> &str { - let trimmed = reason.trim(); - if trimmed.len() <= 40 { - trimmed - } else { - &trimmed[..trimmed.floor_char_boundary(40)] - } -} - fn show_command_for_target(target: &StructuralTarget, scope: &Path) -> String { // Symbol form: `show --section ` for a round-tripping // parser-backed selector. The path is quoted separately so a comma inside @@ -284,13 +310,12 @@ mod tests { #[test] fn batched_show_quotes_combined_space_targets() { let scope = Path::new(""); - let actions = show_actions_for_targets( + let (actions, _) = show_actions_for_targets( &[target("a file.rs", 1, 1), target("b file.rs", 2, 2)], scope, &RenderedSourceLines::default(), ); - // Distinct targets are no longer merged into one numeric command; - // each is offered on its own line. + // Distinct narrow numeric targets stay on their own lines. assert_eq!(actions.len(), 2); assert_eq!(actions[0].command(), "srcwalk show 'a file.rs:1-1'"); assert_eq!(actions[1].command(), "srcwalk show 'b file.rs:2-2'"); @@ -327,7 +352,7 @@ mod tests { #[test] fn batched_show_splits_comma_paths() { let scope = Path::new(""); - let actions = show_actions_for_targets( + let (actions, _) = show_actions_for_targets( &[target("a,file.rs", 1, 1), target("b.rs", 2, 2)], scope, &RenderedSourceLines::default(), @@ -342,7 +367,7 @@ mod tests { #[test] fn over_cap_singleton_emits_no_action() { - let actions = show_actions_for_targets( + let (actions, _) = show_actions_for_targets( &[target("large.rs", 1, 201)], Path::new(""), &RenderedSourceLines::default(), @@ -353,7 +378,7 @@ mod tests { #[test] fn over_cap_ranges_skip_and_keep_contiguous_priorities() { let scope = Path::new(""); - let actions = show_actions_for_targets( + let (actions, fallbacks) = show_actions_for_targets( &[ target("a,file.rs", 1, 150), target("b,file.rs", 1, 51), @@ -364,56 +389,152 @@ mod tests { ); // The 201-line `b` range is dropped by the line cap; the surviving `a` - // (150) and `c` (50) are both >W so they anchor to path:line + expand. + // (150) and `c` (50) are both >W and non-symbol-backed, so they become + // numeric fallback commands (section form for comma paths). assert_eq!(actions.len(), 2); + assert_eq!(fallbacks, 2); assert_eq!( actions[0].command(), - "a,file.rs:1 (read confirmed structural source target)\n> expand: srcwalk show 'a,file.rs' --section 1-150" + "srcwalk show 'a,file.rs' --section 1-150" ); assert_eq!(actions[0].rank(), 10); assert_eq!( actions[1].command(), - "c,file.rs:1 (read confirmed structural source target)\n> expand: srcwalk show 'c,file.rs' --section 1-50" + "srcwalk show 'c,file.rs' --section 1-50" ); assert_eq!(actions[1].rank(), 10); } #[test] - fn wide_range_offered_anchors_but_w_boundary_does_not() { + fn wide_boundary_stays_plain_offer() { let scope = Path::new(""); // Width W (40) is the boundary: exactly 40 lines stays a plain offer. - let boundary = show_actions_for_targets( + let (actions, fallbacks) = show_actions_for_targets( &[target("p.rs", 1, 40)], scope, &RenderedSourceLines::default(), ); - assert_eq!(boundary.len(), 1); + assert_eq!(actions.len(), 1); + assert_eq!(fallbacks, 1); + assert_eq!(actions[0].command(), "srcwalk show p.rs:1-40"); + } + + #[test] + fn wide_numeric_fallback_uses_numeric_command_primary() { + let scope = Path::new(""); + // Width W+1 (41) >W, non-symbol-backed: numeric command is the primary + // action (no separate anchor, no `> expand:`). + let (actions, fallbacks) = show_actions_for_targets( + &[target("p.rs", 1, 41)], + scope, + &RenderedSourceLines::default(), + ); + assert_eq!(actions.len(), 1); + assert_eq!(fallbacks, 1); + assert_eq!(actions[0].command(), "srcwalk show p.rs:1-41"); assert!( - !boundary[0].command().contains("expand:"), - "width-40 target must not anchor: {:?}", - boundary[0].command() + !actions[0].command().contains("expand:"), + "{:?}", + actions[0].command() ); - assert_eq!(boundary[0].command(), "srcwalk show p.rs:1-40"); + } - // Width W+1 (41) must anchor to `path:line (label)` + `> expand:`. - let wide = show_actions_for_targets( - &[target("p.rs", 1, 41)], + #[test] + fn wide_symbol_backed_promotes_symbol_command_to_primary() { + let scope = Path::new(""); + // Wide symbol-backed target: the symbol command is the primary action + // and the numeric range is non-action evidence metadata. + let (actions, fallbacks) = show_actions_for_targets( + &[symbol_target( + "semantic.rs", + 156, + 272, + "format_definition_semantic_match_with_path", + )], scope, &RenderedSourceLines::default(), ); - assert_eq!(wide.len(), 1); + assert_eq!(actions.len(), 1); + assert_eq!(fallbacks, 0); + assert_eq!( + actions[0].command(), + "srcwalk show semantic.rs --section format_definition_semantic_match_with_path" + ); + assert_eq!( + actions[0].reason(), + "read confirmed structural source target" + ); + } + + #[test] + fn wide_symbol_backed_anchor_is_non_action_metadata() { + let scope = Path::new(""); + let (actions, _) = show_actions_for_targets( + &[symbol_target("semantic.rs", 156, 272, "Type.method")], + scope, + &RenderedSourceLines::default(), + ); + let preamble = &actions[0]; + // The action's command is the symbol command; the anchor is plain + // metadata using the START line only, never a competing action or a + // repeat of the full body range. + assert_eq!( + preamble.command(), + "srcwalk show semantic.rs --section Type.method" + ); + let rendered = render_next_actions(std::slice::from_ref(preamble)); + assert_eq!( + rendered, + " evidence anchor: semantic.rs:156 (bounded preview; not the body address)\n> Next: srcwalk show semantic.rs --section Type.method" + ); + assert!(!rendered.contains("expand:"), "{rendered}"); + assert!(!rendered.contains("> Next: semantic.rs"), "{rendered}"); assert!( - wide[0] - .command() - .contains("> expand: srcwalk show p.rs:1-41"), - "width-41 target must anchor with an expand command: {:?}", - wide[0].command() + !rendered.contains("156-272"), + "anchor must not repeat the full range: {rendered}" ); assert!( - wide[0].command().starts_with("p.rs:1 ("), - "{:?}", - wide[0].command() + !rendered.starts_with('>'), + "anchor must be plain metadata, not action-shaped: {rendered}" + ); + } + + #[test] + fn narrow_symbol_backed_has_exactly_one_symbol_next() { + let scope = Path::new(""); + let (actions, fallbacks) = show_actions_for_targets( + &[symbol_target("lib.rs", 1, 3, "helper")], + scope, + &RenderedSourceLines::default(), + ); + assert_eq!(actions.len(), 1); + assert_eq!(fallbacks, 0); + let rendered = render_next_actions(&actions); + assert_eq!(rendered, "> Next: srcwalk show lib.rs --section helper"); + assert!(!rendered.contains("expand:"), "{rendered}"); + assert!(!rendered.contains(":1-3"), "{rendered}"); + } + + #[test] + fn header_teaches_classification() { + assert!(CONFIRMED_TARGETS_HEADER.contains("run the printed Next command")); + assert!(CONFIRMED_TARGETS_HEADER.contains("symbol when stable")); + assert!(CONFIRMED_TARGETS_HEADER.contains("numeric as fallback")); + } + + #[test] + fn numeric_fallback_note_is_single_block_level() { + // Two non-symbol-backed wide targets -> one shared fallback note at + // block level, not repeated per target. + let (actions, fallbacks) = show_actions_for_targets( + &[target("a.rs", 1, 41), target("b.rs", 1, 41)], + Path::new(""), + &RenderedSourceLines::default(), ); + assert_eq!(actions.len(), 2); + assert_eq!(fallbacks, 2); + assert!(NUMERIC_FALLBACK_NOTE.starts_with("> Note:")); + assert!(NUMERIC_FALLBACK_NOTE.contains("numeric fallback")); } #[test] @@ -427,14 +548,14 @@ mod tests { ); // Full containment (1-6) -> offer suppressed. - let full = show_actions_for_targets(&[target("p.rs", 1, 6)], scope, &rendered); + let (full, _) = show_actions_for_targets(&[target("p.rs", 1, 6)], scope, &rendered); assert!( full.is_empty(), "fully-rendered target must be suppressed: {full:?}" ); // Partial overlap (1-3 all rendered, 4-8 not) -> offer kept. - let partial = show_actions_for_targets(&[target("p.rs", 1, 8)], scope, &rendered); + let (partial, _) = show_actions_for_targets(&[target("p.rs", 1, 8)], scope, &rendered); assert_eq!(partial.len(), 1, "partial overlap must keep the offer"); assert!( partial[0].command().contains('8'), @@ -443,7 +564,26 @@ mod tests { ); // No overlap (20-25) -> offer kept. - let none = show_actions_for_targets(&[target("p.rs", 20, 25)], scope, &rendered); + let (none, _) = show_actions_for_targets(&[target("p.rs", 20, 25)], scope, &rendered); assert_eq!(none.len(), 1); } + + #[test] + fn mixed_symbol_and_fallback_emit_one_primary_action_each() { + let scope = Path::new(""); + let (actions, fallbacks) = show_actions_for_targets( + &[ + symbol_target("a.rs", 1, 3, "stableOne"), + target("b.rs", 1, 41), + ], + scope, + &RenderedSourceLines::default(), + ); + // One canonical primary action per emitted target. + assert_eq!(actions.len(), 2); + assert_eq!(fallbacks, 1); + let rendered = render_next_actions(&actions); + assert_eq!(rendered.matches("> Next:").count(), 2, "{rendered}"); + assert!(!rendered.contains("expand:"), "{rendered}"); + } } diff --git a/tests/intent_first_cli.rs b/tests/intent_first_cli.rs index ffaa467..1563992 100644 --- a/tests/intent_first_cli.rs +++ b/tests/intent_first_cli.rs @@ -1521,9 +1521,10 @@ fn caller() -> i32 { "confirmed structural next action should be deduplicated:\n{stdout}" ); assert!( - stdout.contains("read the confirmed structural target above"), - "discover footer should route structural candidates to show first:\n{stdout}" + !stdout.contains("read the confirmed structural target above"), + "confirmed-target block owns the next action; no generic guidance may follow:\n{stdout}" ); + assert!( !stdout.contains("use --expand to inline definition source"), "confirmed structural target should suppress definition expand guidance:\n{stdout}" @@ -1565,9 +1566,11 @@ fn discover_over_cap_structural_target_omits_action_and_heading() { stdout.contains("> Caveat: confirmed structural target lib.rs:1-201 spans 201 lines, over the 200-line next-action bound."), "{stdout}" ); + // A structural target exists (just over the cap), so the generic guidance + // is suppressed too; the caveat block owns the message. assert!( - stdout.contains("read the confirmed structural target above"), - "existing prose footer must remain unchanged:\n{stdout}" + !stdout.contains("read the confirmed structural target above"), + "structural-target query must suppress generic guidance:\n{stdout}" ); let _ = fs::remove_dir_all(&dir); diff --git a/tests/us060b_anchor_seam.rs b/tests/us060b_anchor_seam.rs index e18a495..7fcfc66 100644 --- a/tests/us060b_anchor_seam.rs +++ b/tests/us060b_anchor_seam.rs @@ -1,7 +1,8 @@ //! US-060b: no offered range wider than W=40 lines appears bare in discover / -//! trace output. Wide ranges are anchored to `path:line (label)` + an -//! `expand: srcwalk show path:A-B` command, so the full range is always exactly -//! one printed command away. +//! trace output. Wide ranges are anchored to a bounded `> anchor: path:line` +//! evidence line plus a primary `> Next:` command (symbol-addressed when the +//! selector round-trips; a numeric range otherwise), so the full body is +//! always exactly one printed command away. use std::fs; use std::path::PathBuf; @@ -82,12 +83,31 @@ fn discover_offers_no_bare_range_wider_than_forty() { String::from_utf8_lossy(&out.stderr) ); let stdout = String::from_utf8_lossy(&out.stdout); - // The wide definition range is anchored to a symbol-addressed expand - // command, not offered bare. + // The wide definition range is symbol-addressed: the symbol command is the + // primary `> Next:` action, and the numeric range is non-action evidence + // metadata (a bounded START-line preview), never a competing `> expand:` + // or an action-shaped `> anchor:` line repeating the full body range. assert!( - stdout.contains("> expand: srcwalk show target.js --section target"), - "wide range should be anchored with a symbol expand command, got:\n{stdout}" + stdout.contains("> Next: srcwalk show target.js --section target"), + "wide range should be symbol-addressed as the primary next action, got:\n{stdout}" ); + assert!( + stdout.contains(" evidence anchor: target.js:1 (bounded preview; not the body address)"), + "START-line anchor should appear as plain metadata, got:\n{stdout}" + ); + assert!( + !stdout.contains("> anchor:"), + "anchor must not be action-shaped (no '> anchor:'), got:\n{stdout}" + ); + assert!( + !stdout.contains("evidence anchor: target.js:1-83"), + "anchor must not repeat the full body range, got:\n{stdout}" + ); + assert!( + !stdout.contains("> expand:"), + "no expand line may compete with the symbol next action:\n{stdout}" + ); + // No bare offer exposes a >40-line range. let widths = bare_offered_widths(&stdout); assert!( diff --git a/tests/us065_symbol_section_footer.rs b/tests/us065_symbol_section_footer.rs index 4b56871..86fe7d5 100644 --- a/tests/us065_symbol_section_footer.rs +++ b/tests/us065_symbol_section_footer.rs @@ -86,6 +86,12 @@ fn discover_bare_function_emits_symbol_section_command() { !out.contains("srcwalk show 'lib.rs:1-3'") && !out.contains("srcwalk show lib.rs:1-3"), "no numeric read command should be emitted:\n{out}" ); + // The confirmed block owns the next action; no generic guidance may + // follow it as a competing primary `> Next:`. + assert!( + !out.contains("read the confirmed structural target above"), + "generic guidance must not follow a confirmed-target block:\n{out}" + ); } #[test] @@ -142,6 +148,22 @@ fn discover_quotes_space_and_comma_paths_in_symbol_command() { ); } +#[test] +fn non_structural_search_keeps_numeric_exact_hit_guidance() { + let fx = Fixture::new( + "text_hit", + &[("lib.rs", "fn main() {\n // nothing structural here\n}\n")], + ); + // A plain text search yields no confirmed structural target, so the + // numeric exact-hit guidance must remain (not be replaced by nothing). + let out = fx.discover(&["discover", "nothing", "--as", "text", "--scope", "."]); + assert!(!out.contains("## Confirmed structural targets"), "{out}"); + assert!( + out.contains("read exact hit evidence with `srcwalk show : -C 10`"), + "non-structural search must keep numeric exact-hit guidance:\n{out}" + ); +} + // ------------------------------------------------------- section resolution B #[test] From 7c23a6f91ebde5f99793952f779272397655859a Mon Sep 17 00:00:00 2001 From: sting8k Date: Tue, 11 Aug 2026 17:01:32 +0700 Subject: [PATCH 03/26] feat: add scope-aware Go owner call evidence --- src/commands/find.rs | 114 ++- src/evidence/mod.rs | 1 + src/evidence/owner_links.rs | 1728 +++++++++++++++++++++++++++++++++++ tests/intent_first_cli.rs | 218 +++++ 4 files changed, 2058 insertions(+), 3 deletions(-) create mode 100644 src/evidence/owner_links.rs diff --git a/src/commands/find.rs b/src/commands/find.rs index ca2504d..13bbc4c 100644 --- a/src/commands/find.rs +++ b/src/commands/find.rs @@ -10,6 +10,10 @@ 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::{ + build_owner_link_evidence, OwnerAnchor, 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; @@ -197,14 +201,30 @@ 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 { + term: &result.term, + 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 +239,7 @@ 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 total_found > 0 && (!has_specific_next || artifact.enabled()) { let rendered = render_next_actions(&[NextAction::guidance( "read raw hit evidence with `srcwalk show : -C 10`.", @@ -249,6 +270,7 @@ fn render_text_or_term_details( term_results: &[TextOrTermResult], term_limit: usize, scope: &Path, + owner_links: &OwnerLinkEvidence, ) -> String { use std::fmt::Write as _; @@ -261,11 +283,22 @@ fn render_text_or_term_details( result.term, result.total_found ); for m in &result.matches { + let owner = 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 + ) + }); let _ = write!( rendered, - "\n {}:{} — {}", + "\n {}:{}{} — {}", format::rel_nonempty(&m.path, scope), m.line, + owner, m.text.trim() ); } @@ -288,6 +321,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 +391,7 @@ fn render_text_or_file_rollup( file.lines.len() - TEXT_OR_ROLLUP_LINE_LIMIT ); } + render_text_or_owner_rollup(&mut rendered, &file.path, scope, owner_links); let windows = text_or_select_hit_windows(file); if !windows.is_empty() { let summaries = windows @@ -428,6 +463,79 @@ fn render_text_or_file_rollup( } } +fn render_text_or_owner_rollup( + rendered: &mut String, + path: &Path, + scope: &Path, + owner_links: &OwnerLinkEvidence, +) { + use std::fmt::Write as _; + + let mut owners: BTreeMap> = BTreeMap::new(); + for hit in owner_links.hits.iter().filter(|hit| hit.path == path) { + *owners + .entry(hit.owner.clone()) + .or_default() + .entry(hit.term.clone()) + .or_insert(0) += 1; + } + if owners.is_empty() { + return; + } + let summaries = owners + .into_iter() + .map(|(owner, terms)| { + let terms = terms + .into_iter() + .map(|(term, count)| format!("{term}({count})")) + .collect::>() + .join(","); + format!( + "{}@{}:{}-{} terms={terms}", + owner.qualified_name(), + format::rel_nonempty(&owner.path, scope), + owner.start_line, + owner.end_line + ) + }) + .collect::>() + .join("; "); + let _ = write!(rendered, "\n owners: {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(); + if owner_links.edges.is_empty() { + if owner_links.attributed_owner_count() >= 2 { + let _ = write!(rendered, "\n\n{OWNER_LINK_ZERO_EDGE}"); + } + } else { + rendered.push_str("\n\n## Mechanically resolved Go call sites"); + for edge in owner_links.edges.iter().take(OWNER_LINK_EDGE_CAP) { + let _ = write!( + rendered, + "\n- {} contains call named `{}` at {}:{}; candidate definition `{}` is {}:{}-{} ({}).", + edge.caller.qualified_name(), + edge.callee_name, + format::rel_nonempty(&edge.caller.path, scope), + edge.call_line, + edge.candidate.qualified_name(), + format::rel_nonempty(&edge.candidate.path, scope), + edge.candidate.start_line, + edge.candidate.end_line, + edge.mechanism.label() + ); + } + } + let _ = write!(rendered, "\n\n{OWNER_LINK_CAVEAT}"); + rendered +} + struct TextOrFileRollup { path: PathBuf, term_counts: BTreeMap, diff --git a/src/evidence/mod.rs b/src/evidence/mod.rs index 65db209..b09b17a 100644 --- a/src/evidence/mod.rs +++ b/src/evidence/mod.rs @@ -4,6 +4,7 @@ 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) use anchor::Anchor; pub(crate) use atom::{EvidenceAtom, EvidenceKind, EvidenceRole}; diff --git a/src/evidence/owner_links.rs b/src/evidence/owner_links.rs new file mode 100644 index 0000000..d78d78c --- /dev/null +++ b/src/evidence/owner_links.rs @@ -0,0 +1,1728 @@ +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."; + +#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)] +pub(crate) struct OwnerAnchor { + pub(crate) path: PathBuf, + pub(crate) name: String, + pub(crate) receiver_var: Option, + pub(crate) receiver_type: Option, + pub(crate) package_dir: PathBuf, + pub(crate) start_line: u32, + pub(crate) end_line: u32, +} + +impl OwnerAnchor { + pub(crate) fn qualified_name(&self) -> String { + self.receiver_type.as_ref().map_or_else( + || self.name.clone(), + |receiver| format!("{receiver}.{}", self.name), + ) + } + + 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) term: String, + 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, +} + +impl OwnerCallMechanism { + pub(crate) const fn label(self) -> &'static str { + match self { + Self::SingleAssignmentLocalConstructor => "single-assignment local constructor", + Self::CrossFileSameQualifiedReceiver | Self::SameFileSameQualifiedReceiver => { + "same package-qualified receiver type" + } + Self::SamePackageBareInvocation => "same-package bare invocation", + } + } +} + +#[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, +} + +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 attributed_owner_count(&self) -> usize { + self.hits + .iter() + .map(|hit| hit.owner.clone()) + .collect::>() + .len() + } + + pub(crate) fn has_owners(&self) -> bool { + !self.hits.is_empty() + } +} + +pub(crate) struct OwnerLinkHitInput<'a> { + pub(crate) term: &'a str, + 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 { + let mut by_path: BTreeMap>> = BTreeMap::new(); + for input in inputs { + if crate::lang::detect_file_type(input.path) == crate::types::FileType::Code(Lang::Go) { + 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 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 { + term: input.term.to_string(), + 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, + }, + ); + } + + let candidate_owners = hits + .iter() + .map(|hit| hit.owner.clone()) + .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)) + }); + + OwnerLinkEvidence { hits, edges } +} + +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()); + 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, + }, + }); + } + 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, + }, + }); + } + } + } + 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 { + term, + 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 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, + }, + }, + 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, + }, + }, + ]; + 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(); + } +} diff --git a/tests/intent_first_cli.rs b/tests/intent_first_cli.rs index 1563992..12f68b7 100644 --- a/tests/intent_first_cli.rs +++ b/tests/intent_first_cli.rs @@ -2,6 +2,8 @@ use std::fs; use std::path::PathBuf; use std::process::Command; +const OWNER_LINK_ZERO_EDGE: &str = "No direct name-level call evidence among hit owners. Dynamic dispatch, DI, callbacks, and protocol wiring are not ruled out."; + fn srcwalk() -> Command { Command::new(env!("CARGO_BIN_EXE_srcwalk")) } @@ -1058,6 +1060,222 @@ fn discover_match_any_text_comma_terms_are_literal_or() { let _ = fs::remove_dir_all(&dir); } +#[test] +fn discover_text_or_go_owners_render_mechanical_call_evidence() { + let dir = temp_repo("discover_text_or_go_owner_edges"); + fs::write( + dir.join("feature.go"), + "package feature\ntype DB struct{}\nfunc (d *DB) Apply() { /* alpha */ }\nfunc (d *DB) Set() { /* beta */ d.Apply() }\n", + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", + "alpha,beta", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("[owner DB.Apply@3-3]"), "{stdout}"); + assert!(stdout.contains("[owner DB.Set@4-4]"), "{stdout}"); + assert!( + stdout.contains("## Mechanically resolved Go call sites"), + "{stdout}" + ); + assert!( + stdout.contains("DB.Set contains call named `Apply`"), + "{stdout}" + ); + assert!( + stdout.contains("candidate definition `DB.Apply`"), + "{stdout}" + ); + assert!( + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + assert!(!stdout.contains(OWNER_LINK_ZERO_EDGE), "{stdout}"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_text_or_go_owner_render_caps_edge_bullets_at_ten() { + let dir = temp_repo("discover_text_or_go_owner_cap"); + // 12 candidate methods on the same receiver; Run calls each once so the + // builder emits 12 edges but the renderer must cap the bullet list at 10. + let mut src = String::from("package p\ntype DB struct{}"); + for i in 0..12 { + src.push_str(&format!("\nfunc (d *DB) M{i}() {{ /* body */ }}")); + } + src.push_str("\nfunc (d *DB) Run() {\n"); + for i in 0..12 { + src.push_str(&format!(" d.M{i}()\n")); + } + src.push('}'); + fs::write(dir.join("cap.go"), src).unwrap(); + + let output = srcwalk() + .args([ + "discover", "body,Run", "--match", "any", "--as", "text", "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stdout.contains("## Mechanically resolved Go call sites"), + "{stdout}" + ); + let bullets = stdout + .lines() + .filter(|l| l.starts_with("- ") && l.contains("contains call named")) + .count(); + assert_eq!(bullets, 10, "{stdout}"); + assert!(!stdout.contains("M11"), "{stdout}"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_text_or_go_owner_only_prints_exact_zero_edge_line_once() { + let dir = temp_repo("discover_text_or_go_owner_zero_edge"); + fs::write( + dir.join("feature.go"), + "package feature\nfunc First() { /* alpha */ }\nfunc Second() { /* beta */ }\n", + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", + "alpha,beta", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert_eq!(stdout.matches(OWNER_LINK_ZERO_EDGE).count(), 1, "{stdout}"); + assert!( + !stdout.contains("## Mechanically resolved Go call sites"), + "{stdout}" + ); + assert!( + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_text_or_single_go_owner_keeps_caveat_without_zero_edge_line() { + let dir = temp_repo("discover_text_or_go_single_owner"); + fs::write( + dir.join("feature.go"), + "package feature\nfunc First() { /* alpha beta */ }\n", + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", + "alpha,beta", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("[owner First@2-2]"), "{stdout}"); + assert!(!stdout.contains(OWNER_LINK_ZERO_EDGE), "{stdout}"); + assert!( + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_text_or_owner_caveat_survives_budget_truncation() { + let dir = temp_repo("discover_text_or_go_owner_budget"); + fs::write( + dir.join("feature.go"), + "package feature\nfunc First() { /* alpha beta */ }\n", + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", + "alpha,beta", + "--match", + "any", + "--as", + "text", + "--budget", + "30", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("... truncated"), "{stdout}"); + assert!( + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + #[test] fn discover_match_any_text_or_large_output_rolls_up_by_file() { let dir = temp_repo("discover_text_or_file_rollup"); From ffcd7429f7e88c12ee25daa24540d550a9f4ea4f Mon Sep 17 00:00:00 2001 From: sting8k Date: Tue, 11 Aug 2026 17:43:09 +0700 Subject: [PATCH 04/26] perf: compact owner call evidence rendering --- src/commands/find.rs | 449 ++++++++++++++++++++++++++++++++++-- src/evidence/owner_links.rs | 23 +- tests/intent_first_cli.rs | 24 +- 3 files changed, 432 insertions(+), 64 deletions(-) diff --git a/src/commands/find.rs b/src/commands/find.rs index 13bbc4c..8b824c3 100644 --- a/src/commands/find.rs +++ b/src/commands/find.rs @@ -11,8 +11,8 @@ use crate::commands::multi_scope::{ }; use crate::commands::section_disambiguation::disambiguate_glob_for_section; use crate::evidence::owner_links::{ - build_owner_link_evidence, OwnerAnchor, OwnerLinkEvidence, OwnerLinkHitInput, - OWNER_LINK_CAVEAT, OWNER_LINK_EDGE_CAP, OWNER_LINK_ZERO_EDGE, + 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}; @@ -30,6 +30,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(',') @@ -38,6 +52,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, @@ -155,6 +187,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(), @@ -173,7 +206,7 @@ pub(crate) fn run_text_or_filtered_with_artifact( let mut total_files = BTreeSet::new(); let mut term_results = Vec::with_capacity(terms.len()); - for term in &terms { + for (query_term_index, term) in &indexed_terms { let mut result = search::search_content_raw_with_artifact(term, scope, glob, artifact)?; search::apply_general_filter(&mut result, scope, cache, filter)?; total_found += result.total_found; @@ -193,6 +226,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, @@ -208,7 +242,6 @@ pub(crate) fn run_text_or_filtered_with_artifact( .iter() .flat_map(|result| { result.matches.iter().map(|matched| OwnerLinkHitInput { - term: &result.term, path: &matched.path, line: matched.line, }) @@ -259,6 +292,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, @@ -391,7 +428,7 @@ fn render_text_or_file_rollup( file.lines.len() - TEXT_OR_ROLLUP_LINE_LIMIT ); } - render_text_or_owner_rollup(&mut rendered, &file.path, scope, owner_links); + 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 @@ -466,18 +503,29 @@ fn render_text_or_file_rollup( fn render_text_or_owner_rollup( rendered: &mut String, path: &Path, - scope: &Path, owner_links: &OwnerLinkEvidence, + term_results: &[TextOrTermResult], ) { use std::fmt::Write as _; - let mut owners: BTreeMap> = BTreeMap::new(); - for hit in owner_links.hits.iter().filter(|hit| hit.path == path) { - *owners - .entry(hit.owner.clone()) - .or_default() - .entry(hit.term.clone()) - .or_insert(0) += 1; + // 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; @@ -487,20 +535,30 @@ fn render_text_or_owner_rollup( .map(|(owner, terms)| { let terms = terms .into_iter() - .map(|(term, count)| format!("{term}({count})")) + .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={terms}", + "{}:{}-{}[{terms}]", owner.qualified_name(), - format::rel_nonempty(&owner.path, scope), owner.start_line, owner.end_line ) }) .collect::>() .join("; "); - let _ = write!(rendered, "\n owners: {summaries}"); + let _ = write!( + rendered, + "\n owners (#N=Nth query term; *K=hits): {summaries}" + ); } fn render_owner_link_appendix(owner_links: &OwnerLinkEvidence, scope: &Path) -> String { @@ -515,20 +573,32 @@ fn render_owner_link_appendix(owner_links: &OwnerLinkEvidence, scope: &Path) -> let _ = write!(rendered, "\n\n{OWNER_LINK_ZERO_EDGE}"); } } else { - rendered.push_str("\n\n## Mechanically resolved Go call sites"); + 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- {} contains call named `{}` at {}:{}; candidate definition `{}` is {}:{}-{} ({}).", + "\n- [{}] {} calls {}@{call_path}:{}; candidate {}{cand_loc}", + owner_call_mechanism_tag(edge.mechanism), edge.caller.qualified_name(), edge.callee_name, - format::rel_nonempty(&edge.caller.path, scope), edge.call_line, - edge.candidate.qualified_name(), - format::rel_nonempty(&edge.candidate.path, scope), - edge.candidate.start_line, - edge.candidate.end_line, - edge.mechanism.label() + edge.candidate.qualified_name() ); } } @@ -1767,3 +1837,332 @@ 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 { + 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, + } + } + + 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(), + }; + 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 out = render(&[same_file, cross_file, bare]); + let bullets: Vec<&str> = out.lines().filter(|l| l.starts_with("- ")).collect(); + assert_eq!(bullets.len(), 3, "{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"); + + // 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 e0 = parse_edge(bullets[0]).unwrap(); + assert_eq!(e0.call_file, r"C:\repo\pkg\a.go"); + assert_eq!(e0.call_line, 22); + assert_eq!(e0.cand_file, r"C:\repo\pkg\a.go"); + assert_eq!(e0.def_range, "30-60"); + + let e1 = parse_edge(bullets[1]).unwrap(); + assert_eq!(e1.call_file, r"C:\repo\pkg\a.go"); + assert_eq!(e1.call_line, 12); + assert_eq!(e1.cand_file, r"C:\repo\pkg\sub.go"); + 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(), + }; + 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(), + }; + 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}"); + } +} diff --git a/src/evidence/owner_links.rs b/src/evidence/owner_links.rs index d78d78c..834ffe4 100644 --- a/src/evidence/owner_links.rs +++ b/src/evidence/owner_links.rs @@ -37,7 +37,6 @@ impl OwnerAnchor { #[derive(Debug, Clone)] pub(crate) struct OwnedTextHit { - pub(crate) term: String, pub(crate) path: PathBuf, pub(crate) line: u32, pub(crate) owner: OwnerAnchor, @@ -51,18 +50,6 @@ pub(crate) enum OwnerCallMechanism { SamePackageBareInvocation, } -impl OwnerCallMechanism { - pub(crate) const fn label(self) -> &'static str { - match self { - Self::SingleAssignmentLocalConstructor => "single-assignment local constructor", - Self::CrossFileSameQualifiedReceiver | Self::SameFileSameQualifiedReceiver => { - "same package-qualified receiver type" - } - Self::SamePackageBareInvocation => "same-package bare invocation", - } - } -} - #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)] pub(crate) struct OwnerCallEvidence { pub(crate) caller: OwnerAnchor, @@ -100,7 +87,6 @@ impl OwnerLinkEvidence { } pub(crate) struct OwnerLinkHitInput<'a> { - pub(crate) term: &'a str, pub(crate) path: &'a Path, pub(crate) line: u32, } @@ -168,7 +154,6 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own for input in path_inputs { if let Some(owner) = narrowest_owner(&owners, input.line) { hits.push(OwnedTextHit { - term: input.term.to_string(), path: path.clone(), line: input.line, owner: owner.anchor.clone(), @@ -996,14 +981,10 @@ mod tests { dir } - fn inputs<'a>(term: &'a str, path: &'a Path, lines: &[u32]) -> Vec> { + fn inputs<'a>(_term: &'a str, path: &'a Path, lines: &[u32]) -> Vec> { lines .iter() - .map(|line| OwnerLinkHitInput { - term, - path, - line: *line, - }) + .map(|line| OwnerLinkHitInput { path, line: *line }) .collect() } diff --git a/tests/intent_first_cli.rs b/tests/intent_first_cli.rs index 12f68b7..23d26fb 100644 --- a/tests/intent_first_cli.rs +++ b/tests/intent_first_cli.rs @@ -1091,18 +1091,12 @@ fn discover_text_or_go_owners_render_mechanical_call_evidence() { let stdout = String::from_utf8_lossy(&output.stdout); assert!(stdout.contains("[owner DB.Apply@3-3]"), "{stdout}"); assert!(stdout.contains("[owner DB.Set@4-4]"), "{stdout}"); + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); assert!( - stdout.contains("## Mechanically resolved Go call sites"), - "{stdout}" - ); - assert!( - stdout.contains("DB.Set contains call named `Apply`"), - "{stdout}" - ); - assert!( - stdout.contains("candidate definition `DB.Apply`"), + stdout.contains("DB.Set calls Apply@feature.go:4"), "{stdout}" ); + assert!(stdout.contains("candidate DB.Apply@:3-3"), "{stdout}"); assert!( stdout.contains("structural owner and mechanically filtered"), "{stdout}" @@ -1141,13 +1135,10 @@ fn discover_text_or_go_owner_render_caps_edge_bullets_at_ten() { String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - assert!( - stdout.contains("## Mechanically resolved Go call sites"), - "{stdout}" - ); + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); let bullets = stdout .lines() - .filter(|l| l.starts_with("- ") && l.contains("contains call named")) + .filter(|l| l.starts_with("- [") && l.contains(" calls ")) .count(); assert_eq!(bullets, 10, "{stdout}"); assert!(!stdout.contains("M11"), "{stdout}"); @@ -1185,10 +1176,7 @@ fn discover_text_or_go_owner_only_prints_exact_zero_edge_line_once() { ); let stdout = String::from_utf8_lossy(&output.stdout); assert_eq!(stdout.matches(OWNER_LINK_ZERO_EDGE).count(), 1, "{stdout}"); - assert!( - !stdout.contains("## Mechanically resolved Go call sites"), - "{stdout}" - ); + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); assert!( stdout.contains("structural owner and mechanically filtered"), "{stdout}" From 14a9655c37cd9b6b52173e63dd670d2f68ece249 Mon Sep 17 00:00:00 2001 From: sting8k Date: Tue, 11 Aug 2026 19:32:34 +0700 Subject: [PATCH 05/26] chore(release): prepare 1.6.0 owner evidence --- CHANGELOG.md | 13 +++++- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 33 ++++++++++++++ npm/package.json | 2 +- skills/srcwalk/GUIDE.md | 18 ++++---- src/commands/find.rs | 22 +++++++++- tests/intent_first_cli.rs | 92 +++++++++++++++++++++++++++++++++++++++ 8 files changed, 169 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad51b48..37df404 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-11 + +### 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 194dd96..0520f82 100644 --- a/skills/srcwalk/GUIDE.md +++ b/skills/srcwalk/GUIDE.md @@ -70,6 +70,12 @@ If `discover` prints `## Confirmed structural targets`, run the printed `> Next: 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 8b824c3..9c43a8a 100644 --- a/src/commands/find.rs +++ b/src/commands/find.rs @@ -1944,10 +1944,17 @@ mod tests { 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]); + 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(), 3, "{out}"); + assert_eq!(bullets.len(), 4, "{out}"); let e0 = parse_edge(bullets[0]).unwrap(); assert_eq!( @@ -1981,6 +1988,17 @@ mod tests { 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") diff --git a/tests/intent_first_cli.rs b/tests/intent_first_cli.rs index 23d26fb..3960ebc 100644 --- a/tests/intent_first_cli.rs +++ b/tests/intent_first_cli.rs @@ -1264,6 +1264,98 @@ fn discover_text_or_owner_caveat_survives_budget_truncation() { let _ = fs::remove_dir_all(&dir); } +#[test] +fn discover_text_or_non_go_abstains_from_owner_evidence() { + // Owner evidence is Go-only. A non-Go Text OR must not emit owner rollup + // or mechanical-call markers, even though its output uses `- [` bullet + // shapes elsewhere. Assert absence of the exact owner markers, not `- [`. + let dir = temp_repo("discover_text_or_non_go_owner"); + fs::write( + dir.join("app.py"), + "def apply():\n pass\ndef set():\n apply()\ndef flush():\n set()\n", + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", + "apply,set,flush", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(!stdout.contains("owners (#N=Nth query term"), "{stdout}"); + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + !stdout.contains("[recv=same package-qualified receiver type"), + "{stdout}" + ); + assert!( + !stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_text_or_go_compact_rollup_has_owner_line_by_default() { + // Default-on owner attribution: a compact Go Text OR (>=3 terms) yields the + // `owners (#N=...` rollup line with NO opt-in flag. + let dir = temp_repo("discover_text_or_go_owner_default"); + fs::write( + dir.join("db.go"), + "package db\ntype DB struct{}\nfunc (d *DB) Apply() { /* apply body */ }\nfunc (d *DB) Set() { /* set body */ d.Apply() }\nfunc (d *DB) Flush() { /* flush body */ d.Set(); d.Apply() }\n", + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", + "apply body,set body,flush body", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stdout.contains("owners (#N=Nth query term; *K=hits)"), + "{stdout}" + ); + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + stdout.contains("[recv] DB.Set calls Apply@db.go:4; candidate DB.Apply@:3-3"), + "{stdout}" + ); + assert!( + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + #[test] fn discover_match_any_text_or_large_output_rolls_up_by_file() { let dir = temp_repo("discover_text_or_file_rollup"); From de8246a6eaba9a5901b35013cb09dcf376e8b417 Mon Sep 17 00:00:00 2001 From: sting8k Date: Tue, 11 Aug 2026 19:48:03 +0700 Subject: [PATCH 06/26] docs: specify output compaction grouping --- .../US-065-output-compaction-file-grouping.md | 342 ++++++++++++++++++ 1 file changed, 342 insertions(+) create mode 100644 docs/stories/US-065-output-compaction-file-grouping.md diff --git a/docs/stories/US-065-output-compaction-file-grouping.md b/docs/stories/US-065-output-compaction-file-grouping.md new file mode 100644 index 0000000..af72519 --- /dev/null +++ b/docs/stories/US-065-output-compaction-file-grouping.md @@ -0,0 +1,342 @@ +# US-065 Output Compaction: Group Repeated Paths And Hoist Stable Metadata + +## Status + +ready for implementation — **blocked until srcwalk 1.6.0 ships** + +## Lane + +normal (with stronger validation) + +## Intake Record + +- Input type: measured output-efficiency follow-up from the Go owner-evidence + validation. +- Risk flags: existing output behavior and agent-visible public contracts; path + rendering is platform-sensitive. No matching, ranking, evidence, or semantic + relation changes. +- Implementation owner: Toby after the 1.6.0 release is complete. +- Single working branch: `feat/owner-evidence-output-compaction`; continue on + this branch after the 1.6.0 release commit. Do not create a second feature + branch for US-065. +- Scope split: this story ships independently before multi-language owner + attribution. Multi-language owners are explicitly out of scope here. + +## Problem Statement + +Several high-frequency navigation outputs repeat a copy-pasteable repository path +on every hit even when adjacent entries are from the same file. One discover +section spends about 25% of its bytes repeating paths. Definition output also +repeats an identical provenance line per entry even though Tests and Comments +already hoist it once per section. + +Measured redundant surfaces on `benchmark/fixtures/repos/pebble`: + +1. Text OR per-term details (`render_text_or_term_details`): every hit repeats the + full path; 10 same-file hits print the path 10 times. +2. Single-term discover Tests and Comments facets: every hit repeats the path. +3. `trace callers`: every visible call site repeats the path. +4. Discover Definitions: identical `source · kind · confidence` provenance is + printed after every definition (172 repetitions in one audit query). + +Estimated opportunity on exploratory commands: 15–25% less stdout without +removing evidence. + +## Existing Conventions To Reuse + +Do not invent a new packet grammar. Reuse these shipped shapes: + +- Discover name occurrences: `batch.go [4 name occurrences]` followed by + indented `:LINE | text` rows. +- Text OR file-rollup: one file header with indented hits and terms. +- Deps: one directory/file header with indented children. +- Assess: callers grouped by file. + +The new shape must look like these existing grouped packets. + +## Feature Shape Gate + +1. Product fit: yes — reduces context bloat in the commands agents call most. +2. Intent shape: default rendering improvement; no new command, flag, config, or + environment variable. +3. Cognitive load: none — the existing file-group convention is reused. +4. Evidence source: unchanged. Every hit, line, owner anchor, caller attribute, + and provenance tuple remains visible. +5. Output bounds: output must not grow for single-hit files; ordering, limits, + pagination, collapse pointers, and budgets remain unchanged. +6. Platform scope: displayed paths stay copy-pasteable from the current working + directory. Windows verification is mandatory. +7. Validation: unit, integration, byte-accounting, round-trip, and Windows tests. +8. Agent-facing UX: update GUIDE/README only if an affected example or stated + packet shape exists there. + +## Hard Invariants + +1. **Never shorten or strip the scope prefix from a displayed path.** Grouping + means printing the same current `rel_nonempty`/anchor path once as a file + header, not changing the path value. +2. A printed group path must remain directly copy-pasteable into `srcwalk show` + and printed `> Next:` commands from the command's working directory. +3. No hit, definition, call site, owner anchor, metadata tuple, receiver, arg + count, expansion, caveat, omission note, or pointer may disappear. +4. Preserve the current evidence order. File groups follow first appearance; + entries inside each group retain current relative order. Do not re-rank. +5. Apply current pagination, limits, top-K collapse, budgets, and omission + accounting **before** presentation grouping. Grouping must not change which + entries are visible or reachable. +6. A file with one visible entry keeps its current one-line shape. Group only + files with at least two visible entries so compaction cannot create bloat. +7. Same input and worker count produce deterministic, byte-stable output. +8. Identity-equivalence acceptance is measured with `--no-budget` (or a budget + large enough to render the complete compared slice). On budgeted paths, + compaction must never lose a previously visible entry; it may retain extra + detail that now fits inside the same budget. + +## Product Contract + +### A. Text OR Per-Term Details + +Seam: `render_text_or_term_details` in `src/commands/find.rs`. + +Current repeated shape: + +```text + path/to/file.go:10 [owner Foo@1-30] — text + path/to/file.go:20 [owner Foo@1-30] — text +``` + +Required grouped shape for two or more hits in one file: + +```text + path/to/file.go [2 matches] + :10 [owner Foo@1-30] — text + :20 [owner Foo@1-30] — text +``` + +Single-hit files remain byte-identical to current output. + +The `[N matches]` noun is intentionally facet-local rather than copied from +`[N name occurrences]`; the evidence kind is already established by the enclosing +term section. + +#### Owner-tag compaction + +Owner information is evidence and must not be dropped. Within a multi-hit file +group: + +- A contiguous run of **three or more** hits with the exact same owner anchor + (`qualified name`, start, end) prints the owner once as a subgroup header. + K=3 is deliberate: K=2 can grow output after subgroup indentation and the + `[2 hits]` label, violating the no-growth invariant: + + ```text + [owner Foo@1-30] [3 hits] + :10 — text + :20 — text + :24 — text + ``` + +- Runs of one or two, a unique owner, mixed owner, or unattributed hit stay + inline on their hit rows. +- Only contiguous equal-owner runs may be folded; do not reorder hits to create + owner groups. +- Owner grouping is presentation-only. It must use the existing owner evidence + already attached to each hit and must not invoke new analysis. + +### B. Single-Term Tests And Comments + +Seams: Tests and Comments facet loops in +`format_search_result_with_header` (`src/search/display/mod.rs`). + +For each facet independently, group two or more visible hits from the same file: + +```text +### Tests (3) +source: ... + commit_test.go [2 matches] + :100 — first snippet + :130 — second snippet + db_test.go:50 — single-hit snippet +``` + +- Keep the existing section-level provenance behavior. +- Tests and Comments do not share a group even when paths match. +- Single-hit rows remain in their current shape. + +### C. Trace Callers + +Seam: source-mode rendering in +`search_callers_expanded_with_artifact` (`src/search/callers/single.rs`). Artifact +caller grouping is already separate and is not redesigned. + +After current filtering, ranking, offset, limit, and top-K collapse select the +visible call sites, group two or more visible entries from the same file: + +```text +<- calls + pkg/file.go [2 call sites] + [fn] CallerA :40 args=1 + [fn] CallerB :72 prefix=x(type) args=2 +``` + +- Grouping occurs only on the already-selected visible page. It must not turn + `precision::K` from call sites into file groups. +- `+N more` and `--offset` pointers remain byte-identical and enumerate the same + remaining call sites. +- `--expand` source windows remain attached to the correct child call site and + retain exact source lines. +- Single call sites keep the current line shape. + +### D. Definition Provenance Hoist + +Seams: compact Definitions facet in `format_compact_facet_matches` and definition +formatting/provenance helpers in `src/search/display`. + +A provenance tuple is `(source, displayed kind, confidence)`. For a Definitions +section: + +1. Select the most frequent tuple among visible definitions as the section + default; ties resolve by first occurrence. +2. Print that default once immediately below `### Definitions (N)`. +3. Do not repeat it after entries using the section default. +4. An entry with a different tuple prints its own provenance directly beneath + that entry. +5. All-mixed and one-entry cases must remain honest; no tuple may be inferred or + generalized beyond the entries that carry it. +6. The default is computed from the visible Definitions section instance for + the current invocation/page. It is deterministic per invocation and is never + cached or carried between `--offset` pages. + +This contract applies only to Definitions in this story. Do not refactor every +provenance surface speculatively. + +## Design Seams + +- `src/commands/find.rs::render_text_or_term_details`: stable group-by-path plus + contiguous owner-run rendering. +- `src/search/display/mod.rs::format_search_result_with_header`: Tests/Comments + file groups and Definitions section-default provenance. +- `src/search/display/mod.rs::format_compact_facet_matches` and + `src/search/display/semantic.rs`: suppress per-entry provenance only when it + exactly equals the explicit section default. +- `src/search/callers/single.rs::search_callers_expanded_with_artifact`: group the + final visible source call-site slice, after all selection semantics. +- Use existing path functions (`rel_nonempty`, anchor display) unchanged. +- A small stable grouping helper is acceptable if it serves multiple seams + without erasing their different entry contracts. Do not force a generic + renderer abstraction merely to share a loop. + +## Acceptance Criteria + +### Correctness + +- Every pre-change visible entry maps one-to-one to a post-change entry with the + same path, line/range, text, owner, metadata, and caller fields. +- Multi-hit file paths appear exactly once within their section group; child rows + use `:LINE` or `:START-END` anchors. +- Single-hit files are byte-identical to current output. +- Owner runs fold only for three or more contiguous hits with the exact same + owner; K=2 stays inline, and mixed/unattributed rows stay honest. +- Definitions with uniform provenance print it once. Mixed-provenance fixtures + print the default once and each deviation locally. +- Trace collapse/pagination exposes exactly the same call-site identities before + and after compaction; printed pointer commands return the same remainder. +- Group paths and printed commands round-trip when pasted from repository root, + nested scope, and Windows working directories. + +### Efficiency + +- On the pinned Pebble audit command set, combined stdout bytes decrease by at + least 15% with identical evidence identities and omission counts. +- The Text OR per-term detail section with 10 same-file hits prints the path once + and is strictly smaller. +- No representative command grows in bytes solely because of grouping. +- Report bytes and o200k tokens separately; do not equate stdout bytes with API + billed tokens. + +### Compatibility + +- Non-grouped outputs, artifact callers, Text OR file-rollup mode, ranking, + matching, budgets, caps, and exit codes remain unchanged. +- Existing exact-format integration tests are updated in the same PR; unrelated + snapshots remain byte-identical. +- GUIDE/README examples are updated only where their exact output changed. + +## Pinned Validation Corpus + +Run from `benchmark/fixtures/repos/pebble` (or reproduce equivalent committed +fixtures in integration tests): + +```bash +srcwalk discover 'strictWALTail,readWAL' --match any --as text --scope . --no-budget +srcwalk discover SyncWait --scope . +srcwalk discover Set --as symbol --scope . +srcwalk trace callers Set --scope . +``` + +Record before/after: + +- stdout bytes and o200k tokens; +- ordered evidence identity list `(section, path, line/range, kind, owner)`; +- path occurrence count per section; +- omission/pagination/pointer text; +- pasted `show`/pointer command success. + +If a pinned query no longer exercises the audited surface after fixture changes, +replace it with a committed minimal fixture and document the replacement; do not +relax the acceptance rule. + +## Validation Matrix + +| Layer | Required proof | +| --- | --- | +| Unit | stable first-appearance grouping; single/multi boundary; owner-run K=2 inline / K=3 folded; uniform/mixed/tied provenance defaults; page-local default | +| Integration | exact packets for all four surfaces; single-hit byte identity; no lost evidence identities; collapse/offset/expand caller cases | +| Measurement | pinned Pebble before/after byte + o200k report; combined reduction ≥15% | +| Round-trip | grouped path copied into `show`; unchanged pointer commands execute and return expected remainder | +| Platform | real Windows build/run for grouped relative, nested, and cross-directory paths | +| Release | `cargo fmt`; targeted tests; `cargo test --locked`; `cargo clippy -- -D warnings`; docs/examples aligned | + +## Windows Gate + +This story cannot be declared release-ready from Unix-only tests. On a real +Windows runner: + +1. Build srcwalk. +2. Run one grouped discover Text OR, one grouped Tests/Comments fixture, and one + grouped trace callers fixture. +3. Paste each displayed group path into `srcwalk show`. +4. Run any printed continuation pointer. +5. Confirm no slash conversion, drive-prefix, quoting, or nested-scope regression. + +Parser/string round-trip tests alone do not satisfy this gate. + +## Documentation And Release Notes + +- Release notes: “group repeated same-file hits and hoist stable definition + provenance; evidence, ordering, paths, and reachability unchanged.” +- No GUIDE concept is added: agents already understand file headers and `:LINE` + child rows. Update GUIDE only if an existing exact format statement/example is + invalidated. +- Update any README exact-output example touched by the implementation. + +## Out Of Scope + +- Removing, truncating, or re-ranking evidence. +- Stripping scope prefixes or shortening paths. +- Changing owner inference, owner edge inference, matching, pagination, budgets, + or collapse constants. +- Artifact caller redesign. +- Grouping every renderer in the repository. +- Multi-language owners. Follow-up plan is owners-only (no edges) for TS/JS, + Python, and Rust first; Java, C/C++, and C# second. That work requires a + separate spec and must not block this story. +- Benchmark semantic scoring; this story is presentation-preserving and is gated + by identity equivalence, byte reduction, and round-trip tests. + +## Done Bar + +US-065 is done only when all acceptance criteria pass, the ≥15% pinned-corpus +reduction is recorded, exact-format docs/tests are updated, and real Windows +verification is attached. Internal merge may precede the Windows run only if the +PR is explicitly marked not release-ready. From 27577441cc5d5cc6a9a839beb3e5214293839b64 Mon Sep 17 00:00:00 2001 From: sting8k Date: Tue, 11 Aug 2026 21:37:11 +0700 Subject: [PATCH 07/26] chore: restore unreleased version metadata --- CHANGELOG.md | 2 +- Cargo.lock | 2 +- Cargo.toml | 2 +- npm/package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 37df404..bf377c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ All notable changes to srcwalk are documented here. -## [1.6.0] - 2026-08-11 +## Unreleased ### 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. diff --git a/Cargo.lock b/Cargo.lock index 77d292c..3cfb031 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -678,7 +678,7 @@ checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] name = "srcwalk" -version = "1.6.0" +version = "1.5.0" dependencies = [ "aho-corasick", "clap", diff --git a/Cargo.toml b/Cargo.toml index 4fabdf2..f085df1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "srcwalk" -version = "1.6.0" +version = "1.5.0" edition = "2021" description = "Tree-sitter indexed lookups — smart code reading for AI agents" license = "MIT" diff --git a/npm/package.json b/npm/package.json index 145a02c..bc4db65 100644 --- a/npm/package.json +++ b/npm/package.json @@ -1,6 +1,6 @@ { "name": "srcwalk", - "version": "1.6.0", + "version": "1.5.0", "description": "Code-intelligence CLI for AI agents — tree-sitter outlines, symbol search, caller/callee graphs, deps, overview", "bin": { "srcwalk": "run.js" From e0771e1be9c0a39823cd294b2f70482ecb9d5409 Mon Sep 17 00:00:00 2001 From: sting8k Date: Tue, 11 Aug 2026 21:38:46 +0700 Subject: [PATCH 08/26] feat: compact repeated output evidence --- .../US-065-output-compaction-file-grouping.md | 90 ++- src/commands/find.rs | 182 ++++- src/search/callers/single.rs | 173 +++-- src/search/display/mod.rs | 705 ++++++++++++++++-- src/search/display/semantic.rs | 76 +- tests/js_ts_private_members.rs | 3 + tests/semantic_compact.rs | 140 ++++ 7 files changed, 1230 insertions(+), 139 deletions(-) diff --git a/docs/stories/US-065-output-compaction-file-grouping.md b/docs/stories/US-065-output-compaction-file-grouping.md index af72519..d2896a8 100644 --- a/docs/stories/US-065-output-compaction-file-grouping.md +++ b/docs/stories/US-065-output-compaction-file-grouping.md @@ -2,7 +2,7 @@ ## Status -ready for implementation — **blocked until srcwalk 1.6.0 ships** +implemented — review complete; real Windows verification pending ## Lane @@ -15,10 +15,9 @@ normal (with stronger validation) - Risk flags: existing output behavior and agent-visible public contracts; path rendering is platform-sensitive. No matching, ranking, evidence, or semantic relation changes. -- Implementation owner: Toby after the 1.6.0 release is complete. +- Implementation owner: Toby. - Single working branch: `feat/owner-evidence-output-compaction`; continue on - this branch after the 1.6.0 release commit. Do not create a second feature - branch for US-065. + this branch. Do not create a second feature branch for US-065. - Scope split: this story ships independently before multi-language owner attribution. Multi-language owners are explicitly out of scope here. @@ -113,6 +112,12 @@ Required grouped shape for two or more hits in one file: :20 [owner Foo@1-30] — text ``` +Grouping is **conditional**: it is applied only when the grouped form is strictly +smaller in bytes than the current repeated inline form. Short paths (e.g. a +2-hit `batch.go`) can tie or grow under a group header, so such groups stay +inline to honor the no-growth invariant. Render both candidates and pick the +smaller; on a tie keep the inline (ungrouped) form. + Single-hit files remain byte-identical to current output. The `[N matches]` noun is intentionally facet-local rather than copied from @@ -162,6 +167,8 @@ source: ... - Keep the existing section-level provenance behavior. - Tests and Comments do not share a group even when paths match. - Single-hit rows remain in their current shape. +- As in Seam A, grouping is conditional: render both candidates and pick the + strictly-smaller one; on a tie keep the inline form. ### C. Trace Callers @@ -186,6 +193,11 @@ visible call sites, group two or more visible entries from the same file: - `--expand` source windows remain attached to the correct child call site and retain exact source lines. - Single call sites keep the current line shape. +- As in Seam A, grouping is conditional: render the grouped and ungrouped + candidates and pick the strictly-smaller one; on a tie keep the inline form. + `--expand` windows are included in both candidates, interleaved at the correct + child call site, so the byte comparison (and the retained source windows) stay + correct. ### D. Definition Provenance Hoist @@ -207,8 +219,16 @@ section: the current invocation/page. It is deterministic per invocation and is never cached or carried between `--offset` pages. -This contract applies only to Definitions in this story. Do not refactor every -provenance surface speculatively. +The same hoist is applied to the compact `Matches — same package` (`usages_local`) +facet. Its default is chosen from the **existing rendered provenance carriers** +— one `group[0]` per path group, or a singleton row — never weighted by the +number of child hits; ties resolve to the first-seen carrier. The default is +printed once immediately below the heading, and identical per-group provenance +is suppressed. Definitions remains entry-level (each visible definition is its +own carrier). Deviations print locally. The cross-package (`usages_cross`) +section is intentionally **not** hoisted — it keeps per-group provenance. This +contract is bounded to Definitions and usages_local in this story; do not refactor +every provenance surface speculatively. ## Design Seams @@ -232,13 +252,19 @@ provenance surface speculatively. - Every pre-change visible entry maps one-to-one to a post-change entry with the same path, line/range, text, owner, metadata, and caller fields. -- Multi-hit file paths appear exactly once within their section group; child rows - use `:LINE` or `:START-END` anchors. +- When the grouped candidate wins, a multi-hit file path appears exactly once + within its section group and child rows use `:LINE` or `:START-END` anchors. + When grouping is unprofitable or a tie, the file's exact inline rows are + retained at their original positions in the visible slice; no row is moved or + reordered. - Single-hit files are byte-identical to current output. - Owner runs fold only for three or more contiguous hits with the exact same owner; K=2 stays inline, and mixed/unattributed rows stay honest. - Definitions with uniform provenance print it once. Mixed-provenance fixtures - print the default once and each deviation locally. + print the default once and each deviation locally. The same hoist applies to + the usages_local section; usages_cross keeps per-group provenance. +- Single-hit files, usages_cross groups, and non-compact paths stay byte-identical + to current output. - Trace collapse/pagination exposes exactly the same call-site identities before and after compaction; printed pointer commands return the same remainder. - Group paths and printed commands round-trip when pasted from repository root, @@ -246,11 +272,16 @@ provenance surface speculatively. ### Efficiency -- On the pinned Pebble audit command set, combined stdout bytes decrease by at - least 15% with identical evidence identities and omission counts. +- Target: on the pinned Pebble audit command set, combined stdout bytes decrease + by 15% with identical evidence identities and omission counts. 15% is a target, + not a hard gate. Record the actual combined `--no-budget` reduction; hard + escalation is required only below 10%. A result of 10–15% is accepted honestly + with no scope chasing. - The Text OR per-term detail section with 10 same-file hits prints the path once and is strictly smaller. -- No representative command grows in bytes solely because of grouping. +- No representative command grows in bytes solely because of grouping. Grouping + is conditional (applied only when strictly smaller); on a tie the inline form + is kept, so grouping never grows output. - Report bytes and o200k tokens separately; do not equate stdout bytes with API billed tokens. @@ -267,14 +298,23 @@ provenance surface speculatively. Run from `benchmark/fixtures/repos/pebble` (or reproduce equivalent committed fixtures in integration tests): +Two explicit measurement modes are run on the pinned set. + +**Mode A — `--no-budget` (compaction KPI)**: all four commands use `--no-budget`: + ```bash srcwalk discover 'strictWALTail,readWAL' --match any --as text --scope . --no-budget -srcwalk discover SyncWait --scope . -srcwalk discover Set --as symbol --scope . -srcwalk trace callers Set --scope . +srcwalk discover SyncWait --scope . --no-budget +srcwalk discover Set --as symbol --scope . --no-budget +srcwalk trace callers Set --scope . --no-budget ``` -Record before/after: +**Mode B — original/default budget**: same four commands WITHOUT `--no-budget` +(original flags). These runs prove (a) no previously visible evidence is lost and +(b) within the same budget the compact rendering retains at least as much +evidence, potentially more. Default-budget bytes are NOT the compaction KPI. + +For both modes, record before/after: - stdout bytes and o200k tokens; - ordered evidence identity list `(section, path, line/range, kind, owner)`; @@ -290,9 +330,9 @@ relax the acceptance rule. | Layer | Required proof | | --- | --- | -| Unit | stable first-appearance grouping; single/multi boundary; owner-run K=2 inline / K=3 folded; uniform/mixed/tied provenance defaults; page-local default | +| Unit | stable first-appearance grouping; single/multi boundary; profitable/unprofitable/tie grouping decisions; interleaved order preservation (ungrouped rows keep original slice positions; profitable group emits at first occurrence); owner-run K=2 inline / K=3 folded; uniform/mixed/tied provenance defaults; carrier-majority default for usages_local; page-local default | | Integration | exact packets for all four surfaces; single-hit byte identity; no lost evidence identities; collapse/offset/expand caller cases | -| Measurement | pinned Pebble before/after byte + o200k report; combined reduction ≥15% | +| Measurement | pinned Pebble before/after byte + o200k report in both modes (A `--no-budget` KPI, B default-budget evidence-retention); record actual reduction; hard escalation only below 10% | | Round-trip | grouped path copied into `show`; unchanged pointer commands execute and return expected remainder | | Platform | real Windows build/run for grouped relative, nested, and cross-directory paths | | Release | `cargo fmt`; targeted tests; `cargo test --locked`; `cargo clippy -- -D warnings`; docs/examples aligned | @@ -313,8 +353,9 @@ Parser/string round-trip tests alone do not satisfy this gate. ## Documentation And Release Notes -- Release notes: “group repeated same-file hits and hoist stable definition - provenance; evidence, ordering, paths, and reachability unchanged.” +- Release notes: “group repeated same-file hits (only when strictly smaller) and + hoist stable definition and same-package-usage provenance; evidence, ordering, + paths, and reachability unchanged.” - No GUIDE concept is added: agents already understand file headers and `:LINE` child rows. Update GUIDE only if an existing exact format statement/example is invalidated. @@ -336,7 +377,8 @@ Parser/string round-trip tests alone do not satisfy this gate. ## Done Bar -US-065 is done only when all acceptance criteria pass, the ≥15% pinned-corpus -reduction is recorded, exact-format docs/tests are updated, and real Windows -verification is attached. Internal merge may precede the Windows run only if the -PR is explicitly marked not release-ready. +US-065 is done only when all acceptance criteria pass, the actual pinned-corpus +reduction is recorded (15% target; hard escalation only below 10%; 10–15% +accepted honestly with no scope chasing), exact-format docs/tests are updated, +and real Windows verification is attached. Internal merge may precede the +Windows run only if the PR is explicitly marked not release-ready. diff --git a/src/commands/find.rs b/src/commands/find.rs index 9c43a8a..84e2dd9 100644 --- a/src/commands/find.rs +++ b/src/commands/find.rs @@ -319,26 +319,7 @@ fn render_text_or_term_details( "\n\n## {} — {shown}/{} matches", result.term, result.total_found ); - for m in &result.matches { - let owner = 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 - ) - }); - let _ = write!( - rendered, - "\n {}:{}{} — {}", - format::rel_nonempty(&m.path, scope), - m.line, - owner, - m.text.trim() - ); - } + render_text_or_term_matches(&mut rendered, &result.matches, scope, owner_links); if result.omitted > 0 { let _ = write!( rendered, @@ -350,6 +331,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, diff --git a/src/search/callers/single.rs b/src/search/callers/single.rs index e78dc99..0b0286d 100644 --- a/src/search/callers/single.rs +++ b/src/search/callers/single.rs @@ -1067,59 +1067,62 @@ pub fn search_callers_expanded_with_artifact( // (as the pointer command uses) lists the full remaining page. let list_collapse = effective_offset == 0 && precision::should_collapse_list(shown); let render_count = if list_collapse { precision::K } else { shown }; - for (i, caller) in sorted_callers.iter().take(render_count).enumerate() { - let caller_kind = detect_file_type(&caller.path) - .structural_lang() - .and_then(crate::capabilities::caller_context_kind) - .unwrap_or("fn"); - - let _ = write!( - output, - " [{caller_kind}] {} {}:{}", - caller.calling_function, - rel_nonempty(&caller.path, scope), - caller.line, + let visible: Vec<&CallerMatch> = sorted_callers.iter().take(render_count).collect(); + // Group visible call sites by file after all selection semantics. + let mut groups: Vec<(&Path, Vec<(usize, &CallerMatch)>)> = Vec::new(); + for (i, caller) in visible.iter().enumerate() { + match groups.iter_mut().find(|(p, _)| *p == caller.path.as_path()) { + Some((_, group)) => group.push((i, caller)), + None => groups.push((caller.path.as_path(), vec![(i, caller)])), + } + } + // Precompute the per-path decision: grouped when strictly smaller than + // the ungrouped inline rows, else inline (single site, tie, or loss). + // Expand windows stay attached to their call site in both shapes. + let mut grouped_by_path: std::collections::HashMap<&Path, String> = + std::collections::HashMap::new(); + for (path, group) in &groups { + if group.len() == 1 { + continue; + } + let mut grouped_candidate = String::new(); + let _ = writeln!( + grouped_candidate, + " {} [{} call sites]", + rel_nonempty(path, scope), + group.len() ); - if let Some(ref prefix) = caller.receiver { - if let Some(kind) = caller.prefix_kind { - let _ = write!(output, " prefix={prefix}({})", kind.suffix()); - } else { - let _ = write!(output, " prefix={prefix}"); - } + for (i, caller) in group { + render_caller_line(&mut grouped_candidate, caller, None, scope); + render_caller_expand(&mut grouped_candidate, caller, *i, expand); } - if let Some(argc) = caller.arg_count { - let _ = write!(output, " args={argc}"); + + let mut ungrouped_candidate = String::new(); + for (i, caller) in group { + render_caller_line(&mut ungrouped_candidate, caller, Some(path), scope); + render_caller_expand(&mut ungrouped_candidate, caller, *i, expand); } - let _ = writeln!(output); - - // Expand only when explicitly requested and we have the range. - if i < expand { - if let Some((start, end)) = caller.caller_range { - // Use cached content — no re-read needed. - // Show a compact window around the callsite (±2 lines) - // bounded by the enclosing function range. - let lines: Vec<&str> = caller.content.lines().collect(); - let window_start = caller.line.saturating_sub(2).max(start); - let window_end = (caller.line + 2).min(end); - let start_idx = (window_start as usize).saturating_sub(1); - let end_idx = (window_end as usize).min(lines.len()); - - output.push_str("\n```\n"); - - for (idx, line) in lines[start_idx..end_idx].iter().enumerate() { - let line_num = start_idx + idx + 1; - let prefix = if line_num == caller.line as usize { - "► " - } else { - " " - }; - let _ = writeln!(output, "{prefix}{line_num:4} │ {line}"); - } - output.push_str("```\n"); + if grouped_candidate.len() < ungrouped_candidate.len() { + grouped_by_path.insert(path, grouped_candidate); + } + } + // Iterate the original visible slice. Emit a profitable group once at + // its first call site; emit every other (single / unprofitable) call + // site inline at its original position with its expand window. + let mut emitted: std::collections::HashSet<&Path> = std::collections::HashSet::new(); + for (i, caller) in visible.iter().enumerate() { + let path = caller.path.as_path(); + if let Some(grouped) = grouped_by_path.get(path) { + if emitted.insert(path) { + output.push_str(grouped); } + continue; } + render_caller_line(&mut output, caller, Some(path), scope); + render_caller_expand(&mut output, caller, i, expand); } + // US-060: every collapsed item stays reachable via one pointer command. if list_collapse { let omitted = shown - precision::K; @@ -1287,6 +1290,84 @@ pub fn search_callers_expanded_with_artifact( Ok(output) } +/// Render one call-site line. When `path` is `Some`, the full `file:line` is +/// shown (single-call-site file); when `None`, a grouped child row using only +/// `:line` is rendered (the file header already carries the path). +fn render_caller_line( + output: &mut String, + caller: &CallerMatch, + path: Option<&Path>, + scope: &Path, +) { + let caller_kind = detect_file_type(&caller.path) + .structural_lang() + .and_then(crate::capabilities::caller_context_kind) + .unwrap_or("fn"); + + match path { + Some(p) => { + let _ = write!( + output, + " [{caller_kind}] {} {}:{}", + caller.calling_function, + rel_nonempty(p, scope), + caller.line, + ); + } + None => { + let _ = write!( + output, + " [{caller_kind}] {} :{}", + caller.calling_function, caller.line, + ); + } + } + + if let Some(ref prefix) = caller.receiver { + if let Some(kind) = caller.prefix_kind { + let _ = write!(output, " prefix={prefix}({})", kind.suffix()); + } else { + let _ = write!(output, " prefix={prefix}"); + } + } + if let Some(argc) = caller.arg_count { + let _ = write!(output, " args={argc}"); + } + let _ = writeln!(output); +} + +/// Render the expand window for one call site when it is within the requested +/// expand depth (`i` is the global visible index). +fn render_caller_expand(output: &mut String, caller: &CallerMatch, i: usize, expand: usize) { + if i >= expand { + return; + } + if let Some((start, end)) = caller.caller_range { + // Use cached content — no re-read needed. + // Show a compact window around the callsite (±2 lines) bounded by the + // enclosing function range. + let lines: Vec<&str> = caller.content.lines().collect(); + let window_start = caller.line.saturating_sub(2).max(start); + let window_end = (caller.line + 2).min(end); + let start_idx = (window_start as usize).saturating_sub(1); + let end_idx = (window_end as usize).min(lines.len()); + + output.push_str("\n```\n"); + + for (idx, line) in lines[start_idx..end_idx].iter().enumerate() { + let line_num = start_idx + idx + 1; + let prefix = if line_num == caller.line as usize { + "► " + } else { + " " + }; + let _ = writeln!(output, "{prefix}{line_num:4} │ {line}"); + } + + output.push_str("```\n"); + } +} + fn append_artifact_callers_grouped( output: &mut String, callers: &[CallerMatch], diff --git a/src/search/display/mod.rs b/src/search/display/mod.rs index 359c9ba..a208dd3 100644 --- a/src/search/display/mod.rs +++ b/src/search/display/mod.rs @@ -97,7 +97,7 @@ pub(super) fn is_artifact_anchor_match(m: &Match) -> bool { m.is_definition && m.text.starts_with("artifact anchor ") } -fn match_evidence_source(m: &Match) -> EvidenceSource { +pub(super) fn match_evidence_source(m: &Match) -> EvidenceSource { if is_artifact_anchor_match(m) { EvidenceSource::Artifact } else if matches!( @@ -119,7 +119,7 @@ pub(super) fn document_outline_kind_label(kind: OutlineKind) -> Option<&'static } } -fn displayed_evidence_kind_label(m: &Match) -> &'static str { +pub(super) fn displayed_evidence_kind_label(m: &Match) -> &'static str { if m.in_comment { "comment occurrence" } else if m.impl_target.is_some() { @@ -152,6 +152,98 @@ pub(super) fn append_match_provenance_with_kind( pub(super) fn append_match_provenance(m: &Match, out: &mut String, indent: &str) { append_match_provenance_with_kind(m, out, indent, None); } + +/// The exact provenance tuple string a non-definition match would print, used to +/// compare against a section default for suppression. Mirrors +/// `append_match_provenance` (no kind override). +fn non_definition_provenance_tuple(m: &Match) -> String { + let source = match_evidence_source(m); + format!( + "source: {} · kind: {} · confidence: {}", + evidence_source_label_for(source), + displayed_evidence_kind_label(m), + confidence_label_for(source) + ) +} + +/// Append facet rows (Tests, Comments) grouping two or more visible hits from +/// the same file under a file header. Grouping applies only when it is strictly +/// fewer UTF-8 bytes than the ungrouped inline rows; a tie keeps ungrouped. +/// Single-hit files keep their current one-line shape. Ordering is +/// first-appearance by file, then original order. +fn append_facet_grouped_rows(out: &mut String, matches: &[Match], scope: &Path) { + use std::collections::HashMap; + use std::fmt::Write as _; + + let mut files: Vec<(&Path, Vec<&Match>)> = Vec::new(); + for m in matches { + match files.iter_mut().find(|(p, _)| *p == m.path.as_path()) { + Some((_, group)) => group.push(m), + None => files.push((m.path.as_path(), vec![m])), + } + } + + // Precompute the per-path decision: grouped when strictly smaller, else + // inline (single-hit, tie, or loss). + let mut grouped_by_path: HashMap<&Path, String> = HashMap::new(); + for (path, group) in &files { + if group.len() < 2 { + continue; + } + let mut grouped_candidate = String::new(); + let _ = write!( + grouped_candidate, + "\n {} [{} matches]", + crate::format::rel_nonempty(path, scope), + group.len() + ); + for m in group { + let atom = (*m).to_evidence_atom(); + let _ = write!( + grouped_candidate, + "\n :{} — {}", + atom.anchor().start_line(), + atom.snippet().trim() + ); + } + + let mut ungrouped_candidate = String::new(); + append_facet_ungrouped_rows(&mut ungrouped_candidate, group, scope); + + if grouped_candidate.len() < ungrouped_candidate.len() { + grouped_by_path.insert(path, grouped_candidate); + } + } + + // Iterate the original visible slice. Emit a profitable group once at its + // first occurrence; emit every other (single-hit / unprofitable) row at its + // original position so rejected/tied file rows keep their relative order. + let mut emitted: std::collections::HashSet<&Path> = std::collections::HashSet::new(); + for m in matches { + let path = m.path.as_path(); + if let Some(grouped) = grouped_by_path.get(path) { + if emitted.insert(path) { + out.push_str(grouped); + } + continue; + } + append_facet_ungrouped_rows(out, &[m], scope); + } +} + +/// Render every hit in a file as a one-line inline row (the ungrouped shape). +fn append_facet_ungrouped_rows(out: &mut String, group: &[&Match], scope: &Path) { + use std::fmt::Write as _; + for m in group { + let atom = m.to_evidence_atom(); + let _ = write!( + out, + "\n {} — {}", + atom.anchor().display_relative_to(scope), + atom.snippet().trim() + ); + } +} pub fn format_raw_result( result: &SearchResult, cache: &OutlineCache, @@ -307,11 +399,15 @@ fn format_scope_miss(expanded: &glob::GlobResult, root: &Path, pattern: &str) -> out } -/// Format match entries with optional expansion. +/// Format compact facet matches. When `hoist_provenance` is true (used only for +/// the `Matches — same package` `usages_local` facet), the most frequent +/// non-definition provenance tuple is hoisted once as a section default and +/// identical per-group provenance is suppressed; deviations print locally. fn format_compact_facet_matches( matches: &[Match], scope: &Path, cache: &OutlineCache, + hoist_provenance: bool, out: &mut String, ) { let mut definitions: IndexMap<&Path, Vec<&Match>> = IndexMap::new(); @@ -324,49 +420,158 @@ fn format_compact_facet_matches( } } - for (path, group) in definitions { + render_compact_definitions(&definitions, scope, cache, out); + + // Hoist the most frequent non-definition provenance tuple as a section + // default when requested (usages_local only). Only suppress when the + // section has >= 2 provenance carriers. The default is chosen from the + // actual rendered provenance carriers (one per path group / single row, + // i.e. `group[0]`), NOT weighted by the number of child hits — a group + // renders one provenance line regardless of how many matches it contains. + // Ties resolve by first-appearance. + let carriers: Vec<&Match> = grouped.values().map(|g| g[0]).collect(); + let suppress = if hoist_provenance && carriers.len() >= 2 { + pick_non_definition_provenance_default(&carriers) + } else { + None + }; + if let Some(tuple) = &suppress { + let _ = write!(out, "\n {tuple}"); + } + + for (path, group) in grouped { if group.len() == 1 { - semantic::format_definition_semantic_match(group[0], scope, cache, out); + format_compact_non_definition_match_suppressed( + group[0], + scope, + out, + suppress.as_deref(), + ); continue; } + let noun = non_definition_group_noun(group[0]); let _ = write!( out, - "\n {} [{} matches]", + "\n {} [{} {noun}]", rel_nonempty(path, scope), group.len() ); + append_match_provenance_if_not_default(group[0], out, " ", suppress.as_deref()); for m in group { - semantic::format_definition_semantic_match_in_file(m, cache, out); + let atom = m.to_evidence_atom(); + let kind = non_definition_label(m); + let _ = write!( + out, + "\n [{kind}] :{} | {}", + atom.anchor().start_line(), + atom.snippet().trim() + ); } } +} - for (path, group) in grouped { +/// Render the compact Definitions facet, hoisting the most frequent provenance +/// tuple as a section default and suppressing identical per-entry provenance. +/// The default is page-local and deterministic: most frequent tuple, ties by +/// first occurrence; never cached or carried across `--offset` pages. +fn render_compact_definitions( + definitions: &IndexMap<&Path, Vec<&Match>>, + scope: &Path, + cache: &OutlineCache, + out: &mut String, +) { + use std::fmt::Write as _; + + // Flatten visible definitions in first-appearance order to pick the default. + let mut flat: Vec<&Match> = Vec::new(); + for group in definitions.values() { + flat.extend(group.iter().copied()); + } + let default = pick_definition_provenance_default(&flat, cache); + + // Hoist the default tuple once below the section header only when the + // section has >= 2 visible definitions; a single definition keeps its + // current per-entry provenance byte-identical. + let suppress = default.filter(|_| flat.len() >= 2); + if let Some(tuple) = &suppress { + let _ = write!(out, "\n {tuple}"); + } + + for (path, group) in definitions { if group.len() == 1 { - format_compact_non_definition_match(group[0], scope, out); + semantic::format_definition_semantic_match_suppressed( + group[0], + scope, + cache, + out, + suppress.as_deref(), + ); continue; } - let noun = non_definition_group_noun(group[0]); let _ = write!( out, - "\n {} [{} {noun}]", + "\n {} [{} matches]", rel_nonempty(path, scope), group.len() ); - append_match_provenance(group[0], out, " "); for m in group { - let atom = m.to_evidence_atom(); - let kind = non_definition_label(m); - let _ = write!( + semantic::format_definition_semantic_match_in_file_suppressed( + m, + cache, out, - "\n [{kind}] :{} | {}", - atom.anchor().start_line(), - atom.snippet().trim() + suppress.as_deref(), ); } } } -fn format_compact_non_definition_match(m: &Match, scope: &Path, out: &mut String) { +/// Select the most frequent visible definition provenance tuple as the section +/// default; ties resolve by first occurrence. Returns `None` when there is no +/// computable tuple (e.g. all relation/impl entries), so nothing is hoisted. +fn pick_definition_provenance_default(matches: &[&Match], cache: &OutlineCache) -> Option { + pick_most_frequent( + matches + .iter() + .filter_map(|m| semantic::definition_provenance_tuple(m, cache)), + ) +} + +/// Select the most frequent non-definition provenance tuple as the section +/// default; ties resolve by first occurrence. +fn pick_non_definition_provenance_default(matches: &[&Match]) -> Option { + pick_most_frequent(matches.iter().map(|m| non_definition_provenance_tuple(m))) +} + +/// Most frequent tuple; ties resolve by first occurrence (iteration order). +fn pick_most_frequent(tuples: impl Iterator) -> Option { + let mut counts: Vec<(String, usize)> = Vec::new(); + for tuple in tuples { + match counts.iter_mut().find(|(t, _)| *t == tuple) { + Some((_, count)) => *count += 1, + None => counts.push((tuple, 1)), + } + } + let mut best: Option<(String, usize)> = None; + for (tuple, count) in counts { + if best + .as_ref() + .is_none_or(|(_, best_count)| count > *best_count) + { + best = Some((tuple, count)); + } + } + best.map(|(tuple, _)| tuple) +} + +/// Compact single-row non-definition match. When `suppress` equals the entry's +/// exact provenance tuple, the per-entry provenance line is omitted (hoisted to +/// the section default computed by the caller); a deviation prints locally. +fn format_compact_non_definition_match_suppressed( + m: &Match, + scope: &Path, + out: &mut String, + suppress: Option<&str>, +) { let atom = m.to_evidence_atom(); let kind = non_definition_label(m); let _ = write!( @@ -375,7 +580,23 @@ fn format_compact_non_definition_match(m: &Match, scope: &Path, out: &mut String atom.anchor().display_relative_to(scope), atom.snippet().trim() ); - append_match_provenance(m, out, " "); + append_match_provenance_if_not_default(m, out, " ", suppress); +} + +/// Append provenance only when it deviates from the section default (or there is +/// no default). Exactly matches `append_match_provenance` otherwise. +fn append_match_provenance_if_not_default( + m: &Match, + out: &mut String, + indent: &str, + suppress: Option<&str>, +) { + if let Some(default) = suppress { + if non_definition_provenance_tuple(m) == default { + return; + } + } + append_match_provenance(m, out, indent); } /// Groups consecutive usage matches in the same enclosing function to reduce token noise. @@ -741,7 +962,13 @@ pub(super) fn format_search_result_with_header( if !faceted.definitions.is_empty() { let _ = write!(out, "\n\n### Definitions ({})", faceted.definitions.len()); if compact_facets { - format_compact_facet_matches(&faceted.definitions, &result.scope, cache, &mut out); + format_compact_facet_matches( + &faceted.definitions, + &result.scope, + cache, + false, + &mut out, + ); } else { format_matches( &faceted.definitions, @@ -772,6 +999,7 @@ pub(super) fn format_search_result_with_header( &faceted.implementations, &result.scope, cache, + false, &mut out, ); } else { @@ -796,7 +1024,7 @@ pub(super) fn format_search_result_with_header( if !faceted.bases.is_empty() { let _ = write!(out, "\n\n### Base relationships ({})", faceted.bases.len()); if compact_facets { - format_compact_facet_matches(&faceted.bases, &result.scope, cache, &mut out); + format_compact_facet_matches(&faceted.bases, &result.scope, cache, false, &mut out); } else { format_matches( &faceted.bases, @@ -820,36 +1048,26 @@ pub(super) fn format_search_result_with_header( let _ = write!(out, "\n\n### Tests ({})", faceted.tests.len()); append_match_provenance(&faceted.tests[0], &mut out, ""); // Compact test format — one line per match, no expand budget consumed - for m in &faceted.tests { - let atom = m.to_evidence_atom(); - let _ = write!( - out, - "\n {} — {}", - atom.anchor().display_relative_to(&result.scope), - atom.snippet().trim() - ); - } + append_facet_grouped_rows(&mut out, &faceted.tests, &result.scope); } if !faceted.comments.is_empty() { let _ = write!(out, "\n\n### Comments ({})", faceted.comments.len()); append_match_provenance(&faceted.comments[0], &mut out, ""); - for m in &faceted.comments { - let atom = m.to_evidence_atom(); - let _ = write!( - out, - "\n {} — {}", - atom.anchor().display_relative_to(&result.scope), - atom.snippet().trim() - ); - } + append_facet_grouped_rows(&mut out, &faceted.comments, &result.scope); } if !faceted.usages_local.is_empty() { let header = non_definition_facet_heading(&faceted.usages_local, true); let _ = write!(out, "\n\n### {header} ({})", faceted.usages_local.len()); if compact_facets { - format_compact_facet_matches(&faceted.usages_local, &result.scope, cache, &mut out); + format_compact_facet_matches( + &faceted.usages_local, + &result.scope, + cache, + true, + &mut out, + ); } else { format_matches( &faceted.usages_local, @@ -873,7 +1091,13 @@ pub(super) fn format_search_result_with_header( let header = non_definition_facet_heading(&faceted.usages_cross, false); let _ = write!(out, "\n\n### {header} ({})", faceted.usages_cross.len()); if compact_facets { - format_compact_facet_matches(&faceted.usages_cross, &result.scope, cache, &mut out); + format_compact_facet_matches( + &faceted.usages_cross, + &result.scope, + cache, + false, + &mut out, + ); } else { format_matches( &faceted.usages_cross, @@ -1303,3 +1527,400 @@ mod us062_paths_equivalent_tests { let _ = std::fs::remove_dir_all(&base); } } + +#[cfg(test)] +mod provenance_tuple_tests { + use super::*; + use crate::types::Match; + use std::path::PathBuf; + use std::time::SystemTime; + + fn def_match(name: &str, line: u32) -> Match { + Match { + path: PathBuf::from(format!("/repo/{name}.go")), + line, + text: format!("func {name}() {{}}"), + is_definition: true, + exact: true, + file_lines: 40, + mtime: SystemTime::now(), + def_range: Some((line, line + 1)), + def_name: Some(name.to_string()), + def_weight: 80, + impl_target: None, + base_target: None, + in_comment: false, + } + } + + fn tuple_of(m: &[&Match], cache: &OutlineCache) -> Option { + pick_definition_provenance_default(m, cache) + } + + #[test] + fn uniform_ast_definitions_produce_ast_tuple() { + let cache = OutlineCache::default(); + let a = def_match("A", 1); + let b = def_match("B", 5); + let c = def_match("C", 9); + let got = tuple_of(&[&a, &b, &c], &cache).unwrap(); + assert_eq!( + got, + "source: ast · kind: definition · confidence: structural syntax" + ); + } + + #[test] + fn most_frequent_tuple_wins_and_ties_by_first_occurrence() { + let cache = OutlineCache::default(); + let ast_a = def_match("A", 1); + let ast_b = def_match("B", 5); + // A deviation: a plain (non-definition) name occurrence in a code file + // yields a text tuple different from the AST definition tuple. + let dev = Match { + path: PathBuf::from("/repo/usage.go"), + line: 3, + text: "A()".to_string(), + is_definition: false, + exact: true, + file_lines: 40, + mtime: SystemTime::now(), + def_range: None, + def_name: None, + def_weight: 0, + impl_target: None, + base_target: None, + in_comment: false, + }; + // 3 AST defs vs 2 deviations -> AST wins (most frequent). + let ast_c = def_match("C", 9); + let got = tuple_of(&[&ast_a, &ast_b, &ast_c, &dev, &dev], &cache).unwrap(); + assert_eq!( + got, + "source: ast · kind: definition · confidence: structural syntax" + ); + // Single deviation only -> the deviation tuple is the default (honest). + let dev_only = tuple_of(&[&dev], &cache).unwrap(); + assert_eq!( + dev_only, + "source: text · kind: name occurrence · confidence: text evidence" + ); + } + + #[test] + fn impl_base_entries_are_excluded_from_default() { + let cache = OutlineCache::default(); + let a = def_match("A", 1); + let impl_match = Match { + impl_target: Some("Trait".to_string()), + ..def_match("B", 5) + }; + let got = tuple_of(&[&a, &impl_match], &cache).unwrap(); + assert_eq!( + got, + "source: ast · kind: definition · confidence: structural syntax" + ); + } + + fn name_occurrence_match(path: &str, line: u32) -> Match { + Match { + path: PathBuf::from(path), + line, + text: "a.A()".to_string(), + is_definition: false, + exact: true, + file_lines: 40, + mtime: SystemTime::now(), + def_range: None, + def_name: None, + def_weight: 0, + impl_target: None, + base_target: None, + in_comment: false, + } + } + + #[test] + fn non_definition_default_picks_most_frequent_usage_tuple() { + // usages_local provenance hoist: uniform name occurrences pick the + // text/name-occurrence tuple as the default. + let a = name_occurrence_match("/repo/x.go", 1); + let b = name_occurrence_match("/repo/y.go", 5); + let c = name_occurrence_match("/repo/z.go", 9); + let got = pick_non_definition_provenance_default(&[&a, &b, &c]).unwrap(); + assert_eq!( + got, + "source: text · kind: name occurrence · confidence: text evidence" + ); + } + + #[test] + fn non_definition_deviation_keeps_own_tuple() { + // A document/text deviation (different tuple) among usages_local is not + // folded into the default; the majority name-occurrence tuple wins. + let a = name_occurrence_match("/repo/x.go", 1); + let b = name_occurrence_match("/repo/y.go", 5); + // Deviation: a comment occurrence (kind differs). + let dev = Match { + in_comment: true, + ..name_occurrence_match("/repo/x.go", 3) + }; + let got = pick_non_definition_provenance_default(&[&a, &b, &dev]).unwrap(); + assert_eq!( + got, + "source: text · kind: name occurrence · confidence: text evidence" + ); + // Single deviation only -> the deviation tuple is the (honest) default. + let dev_only = pick_non_definition_provenance_default(&[&dev]).unwrap(); + assert_eq!( + dev_only, + "source: text · kind: comment occurrence · confidence: text evidence" + ); + } + + #[test] + fn conditional_grouping_tie_keeps_ungrouped() { + // A 2-hit short-path group is a tie/no-gain: the inline shape is chosen. + let out = ""; + let _ = out; + // Compare the two candidate byte lengths directly for a short path. + let path = std::path::Path::new("/repo/a.go"); + let scope = std::path::Path::new("/repo"); + let mut grouped = String::new(); + let mut ungrouped = String::new(); + let m1 = name_occurrence_match("/repo/a.go", 1); + let m2 = name_occurrence_match("/repo/a.go", 2); + let group: Vec<&Match> = vec![&m1, &m2]; + let _ = write!( + grouped, + "\n {} [{} matches]\n :1 — t\n :2 — t", + crate::format::rel_nonempty(path, scope), + 2 + ); + for m in &group { + let atom = m.to_evidence_atom(); + let _ = write!( + ungrouped, + "\n {} — {}", + atom.anchor().display_relative_to(scope), + atom.snippet().trim() + ); + } + // Short path: grouped is not strictly smaller, so ungrouped wins. + assert!( + grouped.len() >= ungrouped.len(), + "short-path 2-hit group should not be strictly smaller" + ); + } + + fn artifact_anchor_match(name: &str, line: u32) -> Match { + Match { + path: PathBuf::from(format!("/repo/bundle.min.js")), + line, + text: format!("artifact anchor export {name}"), + is_definition: true, + exact: true, + file_lines: 40, + mtime: SystemTime::now(), + def_range: Some((line, line + 1)), + def_name: Some(name.to_string()), + def_weight: 80, + impl_target: None, + base_target: None, + in_comment: false, + } + } + + #[test] + fn artifact_anchor_default_hoisted_once() { + // Blocker fix: an artifact anchor's definition provenance tuple is + // `source: artifact · kind: anchor ...`, so when it is the section + // default it must be suppressed per-entry (printed once as the default). + let cache = OutlineCache::default(); + let a1 = artifact_anchor_match("A1", 1); + let a2 = artifact_anchor_match("A2", 1); + let a3 = artifact_anchor_match("A3", 1); + let a4 = artifact_anchor_match("A4", 1); + let a5 = artifact_anchor_match("A5", 1); + let a6 = artifact_anchor_match("A6", 1); + // All artifact anchors share one provenance tuple -> it is the default. + let default = tuple_of(&[&a1, &a2, &a3, &a4, &a5, &a6], &cache).unwrap(); + assert_eq!( + default, + "source: artifact · kind: anchor · confidence: artifact-level" + ); + // Rendering the compact Definitions facet must not repeat the default + // after every anchor entry. + let mut map: IndexMap<&Path, Vec<&Match>> = IndexMap::new(); + map.insert(a1.path.as_path(), vec![&a1, &a2, &a3, &a4, &a5, &a6]); + let scope = Path::new("/repo"); + let mut out = String::new(); + render_compact_definitions(&map, scope, &cache, &mut out); + assert_eq!( + out.matches("kind: anchor · confidence: artifact-level") + .count(), + 1, + "artifact anchor default must be printed once (hoisted), got:\n{out}" + ); + } + + #[test] + fn artifact_anchor_mixed_keeps_deviation_tuple() { + // Blocker fix: when the section default is an artifact-anchor tuple, a + // non-anchor definition deviation must still print its own tuple. + let cache = OutlineCache::default(); + let a1 = artifact_anchor_match("A1", 1); + let a2 = artifact_anchor_match("A2", 1); + let a3 = artifact_anchor_match("A3", 1); + let a4 = artifact_anchor_match("A4", 1); + let a5 = artifact_anchor_match("A5", 1); + // Deviation: a Go AST definition (different provenance tuple). + let go = Match { + path: PathBuf::from("/repo/lib.go"), + line: 5, + text: "func Lib() {}".to_string(), + is_definition: true, + exact: true, + file_lines: 40, + mtime: SystemTime::now(), + def_range: Some((5, 6)), + def_name: Some("Lib".to_string()), + def_weight: 80, + impl_target: None, + base_target: None, + in_comment: false, + }; + // 5 anchors > 1 AST -> anchor tuple is the default. + let mut map: IndexMap<&Path, Vec<&Match>> = IndexMap::new(); + map.insert(a1.path.as_path(), vec![&a1, &a2, &a3, &a4, &a5]); + map.insert(go.path.as_path(), vec![&go]); + let scope = Path::new("/repo"); + let mut out = String::new(); + render_compact_definitions(&map, scope, &cache, &mut out); + // The hoisted default (anchor) appears once as the section default. + assert_eq!( + out.matches("kind: anchor · confidence: artifact-level") + .count(), + 1, + "anchor default should be printed once, got:\n{out}" + ); + // The Go definition deviation keeps its own tuple. + assert!( + out.contains("source: ast · kind: definition · confidence: structural syntax"), + "AST deviation must keep its own provenance tuple, got:\n{out}" + ); + } + + #[test] + fn usages_local_default_uses_carriers_not_child_count() { + // Blocker fix: the usages_local default is chosen from the actual + // rendered provenance carriers (one `group[0]` per path group), NOT + // weighted by the number of child hits. Here one path group has many + // name-occurrence children but there are two comment-only singleton + // carriers: the comment tuple wins as the default even though the + // child count favors name occurrences. + let cache = OutlineCache::default(); + // Carrier A: a path group with 6 name-occurrence children (only its + // `group[0]` is a carrier). + let mut group_a = Vec::new(); + for i in 0..6 { + group_a.push(name_occurrence_match("/repo/a.go", i + 1)); + } + // Carriers B and C: two comment-occurrence singletons (each a carrier). + let b = Match { + in_comment: true, + path: PathBuf::from("/repo/b.go"), + ..name_occurrence_match("/repo/b.go", 1) + }; + let c = Match { + in_comment: true, + path: PathBuf::from("/repo/c.go"), + ..name_occurrence_match("/repo/c.go", 1) + }; + // Carriers = [a.go -> name, b.go -> comment, c.go -> comment]. + // The comment tuple wins 2 vs 1 (carrier-based). + let mut map: IndexMap<&Path, Vec<&Match>> = IndexMap::new(); + map.insert( + group_a.first().unwrap().path.as_path(), + group_a.iter().collect(), + ); + map.insert(b.path.as_path(), vec![&b]); + map.insert(c.path.as_path(), vec![&c]); + let carriers: Vec<&Match> = map.values().map(|g| g[0]).collect(); + let default = pick_non_definition_provenance_default(&carriers).unwrap(); + assert_eq!( + default, "source: text · kind: comment occurrence · confidence: text evidence", + "carrier-majority default should be the comment tuple" + ); + // The name-occurrence group (deviation) keeps its own tuple. + let non_def_default = pick_non_definition_provenance_default(&[&group_a[0]]).unwrap(); + assert_eq!( + non_def_default, + "source: text · kind: name occurrence · confidence: text evidence" + ); + } + + #[test] + fn interleaved_ungrouped_rows_preserve_original_order() { + // Blocker fix: when a multi-hit file's group ISN'T profitable, its rows + // must stay at their original positions in the visible slice rather than + // being clustered together. Order A1, B1, A2 (A unprofitable short path) + // must render A1, B1, A2 — not A1, A2, B1. + let scope = Path::new("/repo"); + // A is a short-path 2-hit group (grouping ties -> stays inline). + let a1 = name_occurrence_match("/repo/a.go", 1); + let a2 = name_occurrence_match("/repo/a.go", 3); + // B is an unrelated single-hit file. + let b1 = name_occurrence_match("/repo/b.go", 2); + // Visible slice order: A1, B1, A2. + let matches = vec![a1, b1, a2]; + let mut out = String::new(); + append_facet_grouped_rows(&mut out, &matches, scope); + // a.go is short (2 chars) -> grouping is a tie/loss, so its rows stay + // inline at their original positions: a.go:1, b.go:2, a.go:3. + let a1_pos = out.find("a.go:1").unwrap(); + let b1_pos = out.find("b.go:2").unwrap(); + let a2_pos = out.find("a.go:3").unwrap(); + assert!( + a1_pos < b1_pos && b1_pos < a2_pos, + "ungrouped rows must keep original interleaved order A1,B1,A2, got:\n{out}" + ); + assert!( + !out.contains("a.go [2 matches]"), + "short-path 2-hit group must not be grouped, got:\n{out}" + ); + } + + #[test] + fn interleaved_profitable_group_emits_at_first_occurrence() { + // Blocker fix: a PROFITABLE group emits its whole group at the first + // occurrence of its path, consuming later matches. Order A1, B1, A2 where + // A is a long-path multi-hit profitable group renders A[2], B1 — the A + // group at A1's position, B1 after. + let scope = Path::new("/repo"); + // A uses a long path so grouping is strictly smaller. + let a1 = name_occurrence_match( + "/repo/very/long/path/that/makes/grouping/profitable/a.go", + 1, + ); + let a2 = name_occurrence_match( + "/repo/very/long/path/that/makes/grouping/profitable/a.go", + 3, + ); + let b1 = name_occurrence_match("/repo/b.go", 2); + let matches = vec![a1, b1, a2]; + let mut out = String::new(); + append_facet_grouped_rows(&mut out, &matches, scope); + // The A group is emitted at A1's position (before B1); A2 is consumed. + let group_pos = out.find("[2 matches]").unwrap(); + let b1_pos = out.find("b.go:2").unwrap(); + assert!( + group_pos < b1_pos, + "profitable group must emit at first occurrence before B1, got:\n{out}" + ); + assert!( + out.contains(":1") && out.contains(":3"), + "profitable group must contain both child rows, got:\n{out}" + ); + } +} diff --git a/src/search/display/semantic.rs b/src/search/display/semantic.rs index 440fe87..1228405 100644 --- a/src/search/display/semantic.rs +++ b/src/search/display/semantic.rs @@ -142,15 +142,58 @@ pub(super) fn format_definition_semantic_match( out: &mut String, ) { let path = rel_nonempty(&m.path, scope); - format_definition_semantic_match_with_path(m, Some(&path), cache, out, " "); + format_definition_semantic_match_with_path(m, Some(&path), cache, out, " ", None); } -pub(super) fn format_definition_semantic_match_in_file( +/// Compact-facet variant: when `suppress` is the exact provenance tuple of the +/// entry, the per-entry provenance line is omitted (hoisted to the section +/// default computed by the caller). +pub(super) fn format_definition_semantic_match_suppressed( m: &Match, + scope: &Path, cache: &OutlineCache, out: &mut String, + suppress: Option<&str>, ) { - format_definition_semantic_match_with_path(m, None, cache, out, " "); + let path = rel_nonempty(&m.path, scope); + format_definition_semantic_match_with_path(m, Some(&path), cache, out, " ", suppress); +} + +pub(super) fn format_definition_semantic_match_in_file_suppressed( + m: &Match, + cache: &OutlineCache, + out: &mut String, + suppress: Option<&str>, +) { + format_definition_semantic_match_with_path(m, None, cache, out, " ", suppress); +} + +/// Compute the exact provenance tuple string `source · kind · confidence` for a +/// definition match, mirroring `append_match_provenance_with_kind`. Returns +/// `None` for relation/impl/base artifacts that do not print a provenance line. +pub(super) fn definition_provenance_tuple(m: &Match, cache: &OutlineCache) -> Option { + if m.impl_target.is_some() || m.base_target.is_some() { + return None; + } + let source = super::match_evidence_source(m); + let kind_override = if super::is_artifact_anchor_match(m) { + Some("anchor") + } else if matches!( + crate::lang::detect_file_type(&m.path), + crate::types::FileType::Document(_) + ) && semantic_candidate_for_match(m, cache).is_some() + { + let candidate = semantic_candidate_for_match(m, cache).unwrap(); + super::document_outline_kind_label(candidate.kind) + } else { + None + }; + Some(format!( + "source: {} · kind: {} · confidence: {}", + super::evidence_source_label_for(source), + kind_override.unwrap_or_else(|| super::displayed_evidence_kind_label(m)), + super::confidence_label_for(source) + )) } fn format_definition_semantic_match_with_path( @@ -159,6 +202,7 @@ fn format_definition_semantic_match_with_path( cache: &OutlineCache, out: &mut String, indent: &str, + suppress: Option<&str>, ) { let atom = m.to_evidence_atom(); if super::is_artifact_anchor_match(m) { @@ -171,7 +215,7 @@ fn format_definition_semantic_match_with_path( "\n{indent}[anchor] {label} {}", format_loc(path, atom.anchor().start_line()) ); - super::append_match_provenance_with_kind(m, out, indent, Some("anchor")); + append_provenance_if_not_default(m, out, indent, Some("anchor"), cache, suppress); return; } if m.impl_target.is_some() { @@ -217,7 +261,7 @@ fn format_definition_semantic_match_with_path( } else { None }; - super::append_match_provenance_with_kind(m, out, indent, kind_override); + append_provenance_if_not_default(m, out, indent, kind_override, cache, suppress); for child in candidate.children.iter().take(2) { let _ = write!( out, @@ -246,7 +290,7 @@ fn format_definition_semantic_match_with_path( } else { let _ = write!(out, "\n{indent}[{kind}] {}", format_range(path, start, end)); } - super::append_match_provenance(m, out, indent); + append_provenance_if_not_default(m, out, indent, None, cache, suppress); } else { let kind = if m.impl_target.is_some() { "impl" @@ -266,11 +310,29 @@ fn format_definition_semantic_match_with_path( format_loc(path, atom.anchor().start_line()) ); } - super::append_match_provenance(m, out, indent); + append_provenance_if_not_default(m, out, indent, None, cache, suppress); } append_artifact_definition_snippet(m, out); } +/// Append a match provisioning line unless it equals the supplied section +/// default tuple (hoisted provenance). +fn append_provenance_if_not_default( + m: &Match, + out: &mut String, + indent: &str, + kind_override: Option<&'static str>, + cache: &OutlineCache, + suppress: Option<&str>, +) { + if let Some(default) = suppress { + if definition_provenance_tuple(m, cache).as_deref() == Some(default) { + return; + } + } + super::append_match_provenance_with_kind(m, out, indent, kind_override); +} + fn format_loc(path: Option<&str>, line: u32) -> String { match path { Some(path) => format!("{path}:{line}"), diff --git a/tests/js_ts_private_members.rs b/tests/js_ts_private_members.rs index 566990f..17f8d0e 100644 --- a/tests/js_ts_private_members.rs +++ b/tests/js_ts_private_members.rs @@ -160,6 +160,8 @@ fn callers_private_attributed_to_enclosing_class_method() { stdout.contains("— 3 call sites"), "exactly the three #evict sites:\n{stdout}" ); + // Short relative path `cache.js`: grouping is a tie/no-gain, so the three + // sites stay inline (conditional grouping keeps ungrouped on tie). for line in ["cache.js:6", "cache.js:7", "cache.js:8"] { assert!(stdout.contains(line), "call site {line} missing:\n{stdout}"); } @@ -184,6 +186,7 @@ fn public_name_distinct_from_private() { pub_out.contains("— 2 call sites"), "public evict must see only its two sites:\n{pub_out}" ); + // Short path `cache.js`: 2 sites stay inline (grouping would be a tie). assert!( pub_out.contains("cache.js:9") && pub_out.contains("cache.js:10"), "public evict must see the bare + member sites:\n{pub_out}" diff --git a/tests/semantic_compact.rs b/tests/semantic_compact.rs index 855349b..737c5e2 100644 --- a/tests/semantic_compact.rs +++ b/tests/semantic_compact.rs @@ -223,6 +223,146 @@ fn symbol_search_compact_groups_multiple_definitions_in_same_file() { ); } +#[test] +fn definitions_hoist_uniform_default_once() { + // US-065-D: a compact Definitions section with uniform provenance prints the + // default tuple once below the header and does not repeat it per entry. + let dir = tempfile::tempdir().unwrap(); + for idx in 0..6 { + std::fs::write( + dir.path().join(format!("K{idx}.go")), + format!("package db\nfunc K{idx}(v int) {{}} \n"), + ) + .unwrap(); + } + + let out = srcwalk() + .args(["discover", "K*", "--glob", "*.go", "--scope"]) + .arg(dir.path()) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + + assert!( + stdout.contains("### Definitions (6)"), + "expected a compact Definitions facet, got:\n{stdout}" + ); + assert!( + stdout.contains("source: ast · kind: definition · confidence: structural syntax"), + "expected the hoisted default provenance tuple, got:\n{stdout}" + ); + // The uniform default appears exactly once (as the section default line). + assert_eq!( + stdout + .matches("kind: definition · confidence: structural syntax") + .count(), + 1, + "uniform default provenance should be printed once, got:\n{stdout}" + ); +} + +#[test] +fn definitions_single_entry_keeps_inline_provenance() { + // US-065-D: a one-definition result keeps its per-entry provenance inline + // (no hoist), byte-identical to pre-compaction output. + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("solo.go"), + "package db\nfunc Ksolo(v int) {}\n", + ) + .unwrap(); + let solo = srcwalk() + .args(["discover", "Ksolo", "--glob", "*.go", "--scope"]) + .arg(dir.path()) + .output() + .unwrap(); + let solo_stdout = String::from_utf8_lossy(&solo.stdout); + assert!( + solo_stdout.contains("[fn] Ksolo") && solo_stdout.contains("kind: definition"), + "single definition should keep its inline provenance, got:\n{solo_stdout}" + ); +} + +#[test] +fn usages_local_hoists_default_provenance_keeps_deviations() { + // US-065: the compact `Matches — same package` (usages_local) facet hoists + // the most frequent provenance tuple once and suppresses identical per-group + // provenance, while a deviation group keeps its own tuple locally. + let dir = tempfile::tempdir().unwrap(); + // A go.mod is required so the definition's package root is known and the + // calls are classified as same-package (usages_local). + std::fs::write(dir.path().join("go.mod"), "module app\n\ngo 1.21\n").unwrap(); + // Multiple name occurrences of the target in one package (uniform tuple). + std::fs::write( + dir.path().join("use.go"), + "package app\nfunc helper() {}\nfunc f() { helper() }\nfunc h() { helper() }\nfunc k() { helper() }\nfunc m() { helper() }\nfunc n() { helper() }\n", + ) + .unwrap(); + let out = srcwalk() + .args(["discover", "helper", "--as", "symbol", "--scope"]) + .arg(dir.path()) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + + // The default provenance appears once below the section header. + assert!( + stdout.contains("### Name occurrences — same package"), + "expected usages_local facet, got:\n{stdout}" + ); + assert_eq!( + stdout + .matches("kind: name occurrence · confidence: text evidence") + .count(), + 1, + "usages_local default provenance should be hoisted once, got:\n{stdout}" + ); +} + +#[test] +fn usages_cross_section_byte_unchanged() { + // US-065: provenance hoist is bounded to usages_local; the cross-package + // section must not change. Build a mixed fixture with a cross-package hit. + let dir = tempfile::tempdir().unwrap(); + let pkg_a = dir.path().join("pkg_a"); + let pkg_b = dir.path().join("pkg_b"); + std::fs::create_dir_all(&pkg_a).unwrap(); + std::fs::create_dir_all(&pkg_b).unwrap(); + std::fs::write(pkg_a.join("go.mod"), "module pkg_a\n\ngo 1.21\n").unwrap(); + std::fs::write(pkg_b.join("go.mod"), "module pkg_b\n\ngo 1.21\n").unwrap(); + std::fs::write( + pkg_a.join("a.go"), + "package pkg_a\nfunc Target() {}\nfunc use() { Target() }\n", + ) + .unwrap(); + // Enough cross-package usages to exceed the compact threshold (>5 matches). + std::fs::write( + pkg_b.join("b.go"), + "package pkg_b\nimport \"pkg_a\"\nfunc u1() { pkg_a.Target() }\nfunc u2() { pkg_a.Target() }\nfunc u3() { pkg_a.Target() }\nfunc u4() { pkg_a.Target() }\nfunc u5() { pkg_a.Target() }\nfunc u6() { pkg_a.Target() }\n", + ) + .unwrap(); + let out = srcwalk() + .args(["discover", "Target", "--as", "symbol", "--scope"]) + .arg(dir.path()) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + // The cross section keeps its per-entry provenance (no hoist): each group + // still prints its own provenance tuple. + assert!( + stdout.contains("### Name occurrences — other"), + "expected a cross-package compact section, got:\n{stdout}" + ); + // No hoist: per-group provenance is still emitted (not suppressed). + assert_eq!( + stdout + .matches("kind: name occurrence · confidence: text evidence") + .count(), + 2, + "cross-package section must keep per-group provenance, got:\n{stdout}" + ); +} + #[test] fn symbol_search_semantic_rows_work_across_rust_typescript_and_python() { let dir = tempfile::tempdir().unwrap(); From f79f3b1fdb7b9755bab8d9151874c25ca830537e Mon Sep 17 00:00:00 2001 From: sting8k Date: Tue, 11 Aug 2026 22:57:04 +0700 Subject: [PATCH 09/26] docs: specify multilanguage owner attribution --- ...multilanguage-owner-attribution-phase-1.md | 417 ++++++++++++++++++ 1 file changed, 417 insertions(+) create mode 100644 docs/stories/US-067-multilanguage-owner-attribution-phase-1.md diff --git a/docs/stories/US-067-multilanguage-owner-attribution-phase-1.md b/docs/stories/US-067-multilanguage-owner-attribution-phase-1.md new file mode 100644 index 0000000..172e93e --- /dev/null +++ b/docs/stories/US-067-multilanguage-owner-attribution-phase-1.md @@ -0,0 +1,417 @@ +# US-067: Multilanguage Owner Attribution — Phase 1 + +## Status + +ready for implementation — audit conditions incorporated + +## Lane + +normal (accuracy-sensitive evidence feature) + +## Context And Release Boundary + +- Implementation owner: Toby after design audit approval. +- Review owner: Rocky; independent contract audit: Gizmo. +- Single working branch: `feat/owner-evidence-output-compaction`. Do not create a + second branch. +- This story is part of one future release bundle: existing Go owner evidence, + US-065 output compaction, and this phase-1 multilanguage owner attribution. +- The release version is intentionally undecided. Do not change Cargo/npm/lock + versions, tag, publish, push, or ship without an explicit user instruction. +- Run the real Windows gate once after this story lands, for the complete bundle. + +## Evidence-Based Scope Decision + +Owner ranges and rollups carried the measured navigation value: owner-only +rollups were consumed in 10/95 eligible historical shows, while call edges were +useful mainly in chain-shaped tasks and require language-specific binding rules. +Therefore phase 1 adds **owner attribution only** for: + +1. TypeScript/JavaScript: `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs`; +2. Python; +3. Rust. + +No call edges are inferred for these languages. A language may receive edges only +under a later evidence-backed story with its own binding and accuracy contract. + +## User Outcome + +For the existing Text OR flow, a hit inside a supported named callable shows the +same owner evidence shape already used by Go: + +```text + path/to/file.ts + owners (#N=Nth query term; *K=hits): Service.handle:20-48[#1,#3*2] +``` + +In non-compact per-term detail mode, the existing inline shape is also reused: + +```text + path/to/file.py:31 [owner Service.handle@20-48] — matched text +``` + +No new command, flag, configuration, section, trigger, or output encoding is +introduced. + +## Existing Design Seam + +Current ownership is built in `src/evidence/owner_links.rs`: + +1. `build_owner_link_evidence` groups visible Text OR hits by path. +2. Go files are parsed; `collect_file_owners` creates `OwnerAnchor`s. +3. `narrowest_owner` attributes a line to one unique narrowest callable range. +4. Go-only lexical analysis builds mechanically filtered call edges. +5. `src/commands/find.rs` renders inline tags, compact `owners (#N=...)` + rollups, and the Go call appendix. + +Phase 1 belongs at the owner-extraction boundary. It must not add language rules +inside `find.rs` or weaken the Go edge engine. + +## Core Data Contract + +### Owner regions, not only owner anchors + +Each parsed supported file produces nested callable regions of two kinds: + +```text +Named(owner anchor) +AnonymousBarrier(start_line, end_line) +``` + +For every visible hit: + +1. Find all callable regions whose inclusive line range contains the hit. +2. Select the unique narrowest range by `(end_line - start_line)`. +3. If the narrowest region is `Named`, attach that owner. +4. If it is `AnonymousBarrier`, abstain. +5. If equally narrow regions tie, abstain. + +An anonymous callable is a barrier, not merely an omitted owner node. Otherwise a +hit inside `items.map(x => ...)`, a Python lambda, or a Rust closure could fall +through and be falsely attributed to an enclosing named function. + +A named callable nested inside an anonymous barrier remains eligible within its +own narrower range. + +Region extraction must be exhaustive over **all callable node kinds** in each +version-pinned grammar. Every callable node is classified as either a supported +`Named` owner or an `AnonymousBarrier`; silently omitting a callable node is a +contract violation. Thus unsupported but callable constructs—object-literal +methods, getters/setters outside supported forms, IIFEs, prototype-assigned +functions, Python lambdas, Rust closures, and future callable kinds exposed by +the pinned grammar—cannot leak hits to an outer owner. + +Each adapter maintains a version-pinned callable-kind manifest audited against +the grammar's bundled node-type metadata. Tests must prove every manifest kind +produces exactly one region classification, and fixtures must exercise every +kind. A grammar upgrade that adds or changes a callable kind must fail this +coverage check until the adapter classifies it deliberately. + +### Anchor identity + +Every named anchor contains: + +- exact repository path; +- unqualified callable name; +- explicit display-qualified name; +- inclusive 1-indexed start/end lines from the callable AST node; +- source language. + +Qualified display identity must be separate from Go receiver/binding identity. +Do not overload `receiver_type` to encode Python, JS, or Rust containers. Existing +Go edge fields may remain Go-specific. + +Ordering and equality are deterministic over path, qualified name, and range. +No owner may render placeholder names such as `` or ``. + +### Parse failure and local error regions + +If a supported file cannot be read, produces no tree, or its root node itself is +an `ERROR`, preserve all raw text hits and emit no owner evidence for that file. +For a partial tree with local `ERROR` or missing-node descendants: + +1. Record every error/missing byte range and inclusive line range. +2. A callable whose byte range overlaps any error range is replaced by an + `AnonymousBarrier` covering the full callable; it is never a `Named` owner. +3. An error range outside a callable is itself an abstention barrier, so a hit on + an error-overlapping line cannot fall through to an enclosing owner. +4. Named regions with no error overlap remain eligible. + +Because Text OR hit inputs are line-based, any hit line intersecting an error +range abstains even when the parser provides narrower columns. Never recover +owner names from signatures, indentation, regexes, or raw-line guessing. + +## Language Contracts + +### A. TypeScript And JavaScript Family + +Use the grammar selected by the existing `Lang`/extension routing, including the +TSX grammar for `.tsx` and JavaScript grammar for JS/JSX/MJS/CJS. + +#### Supported named owners + +1. Named function and generator declarations: `load`. +2. Class methods with a static/simple/private identifier name: + `Service.handle`, `Service.#reset`. +3. A direct variable declarator with a simple identifier whose initializer is an + arrow or function expression: `load`. +4. A class field with a simple/private property name whose direct value is an + arrow or function expression: `Service.handle`. +5. A function expression with an explicit name may use that explicit name when + no supported binding/property owner exists. +6. Nested supported named callables append lexical containers with `.`: + `outer.inner`, `Service.handle.inner`. +7. TypeScript namespace/internal-module and ECMAScript module-block lexical + containers append with `.` (for example `Api.load`) but are not callable + owners themselves. This prevents equal unqualified names in separate + namespaces from conflating. + +Transparent syntax wrappers such as `export`, `default`, TypeScript annotations, +and decorators do not become containers and do not change the callable node +range. + +#### Required abstentions/barriers + +- Inline anonymous arrows/functions used as call arguments, returns, array/object + elements, JSX expressions, or assignment targets without a supported simple + binding/property name. +- Computed method/property names whose stable source name is not a simple or + private identifier. +- Overload signatures or declarations without a body. +- Any construct whose class/binding container cannot be read structurally. +- Object-literal methods/accessors, IIFEs, and prototype/member-assigned function + expressions are barriers unless they independently satisfy a supported named + binding form above. + +Do not invent labels such as `callback@42`, ``, property text, or a callee +name from the surrounding call. + +### B. Python + +#### Supported named owners + +1. Synchronous and asynchronous `function_definition` nodes. +2. Class methods: `Service.handle`. +3. Nested classes and functions use their complete lexical hierarchy with `.`: + `Outer.Inner.handle`, `outer.inner`, `Outer.method.inner`. + +The anchor range starts at the underlying `def`/`async def` node and ends at its +body. A `decorated_definition` wrapper is transparent: decorator lines are not +inside the callable owner range, and a hit in a decorator expression is not +attributed to the decorated function. + +#### Required abstentions/barriers + +- Every `lambda` is an anonymous barrier. +- A malformed decorated definition or a callable with no structural name + abstains. +- Do not infer class/function hierarchy from indentation or rendered signatures. + +### C. Rust + +#### Supported named owners + +1. Top-level body-bearing `function_item`: `run`. +2. Lexically nested functions/modules use Rust `::`: `outer::inner`, + `server::run`. +3. Inherent impl method: `Type::method`. +4. Trait default/body method: `Trait::method`. +5. Trait implementation method: `::method`. + +For impl names, read the AST `type` and optional `trait` fields. Preserve their +trimmed source spelling. Collapse every non-empty run recognized by Rust +`str::split_whitespace` to exactly one ASCII space; preserve all other source +tokens and punctuation. Do not semantically resolve aliases or modules. Examples: + +```text +impl Store => Store::get +impl Cache for Store => as Cache>::get +``` + +The trait-qualified form is binding: it prevents a trait method from being +presented as the same owner as an inherent method with the same name. + +#### Required abstentions/barriers + +- Every closure expression is an anonymous barrier. +- Trait signatures and extern declarations without bodies are not owners. +- If an impl target or trait name cannot be extracted structurally, its methods + abstain rather than fall back to an unqualified name. +- Macro-generated owners are not inferred from expanded or guessed source. + +## Rendering And Trigger Parity + +- Run attribution in the same existing Text OR flow and at the same point after + filtering/pagination as Go. +- Existing compact selection remains unchanged: compact file rollup is selected + by the current term/match thresholds (including three-or-more terms); otherwise + existing per-term detail rows are used. +- Reuse `OwnerAnchor`, inline `[owner ...@START-END]`, and + `owners (#N=Nth query term; *K=hits)` rendering. +- Preserve US-065 conditional file grouping and K=3 repeated-owner folding. +- Preserve path rendering, term indices, count multipliers, ordering, caps, + budgets, and omission accounting. +- Artifact mode continues to abstain exactly as today. + +### Capability-honest call appendix + +Owner attribution support and edge-analysis support are separate capabilities. + +- New-language owners never populate `OwnerCallEvidence`. +- `## Mechanical Go calls`, its zero-edge sentence, and its call-specific caveat + are driven only by Go owner/edge analysis. +- A non-Go-only result must not say “No direct name-level call evidence...”; + absence means unsupported analysis, not measured zero. +- A mixed-language query may render non-Go owner rollups plus a Go-only mechanical + appendix, but that appendix must remain explicitly labeled Go. +- Existing Go-only output stays byte-identical. +- Non-Go owner output includes one concise honesty caveat stating that ranges are + structural lexical ownership candidates, not runtime ownership or binding + proof. It must not imply call analysis ran. + +The evidence model should carry the capability/attempt distinction explicitly; +do not infer it from `edges.is_empty()`. + +## Implementation Shape + +Keep orchestration and Go edges in `owner_links.rs`, but do not add three large +parser implementations to that already-large file. Add focused owner extractors, +for example: + +```text +src/evidence/owners/mod.rs +src/evidence/owners/js_ts.rs +src/evidence/owners/python.rs +src/evidence/owners/rust.rs +``` + +A small shared walker for `Named`/`AnonymousBarrier`, lexical container stacks, +and unique-narrowest selection is appropriate. Language-specific node kinds, +field extraction, and qualified naming stay in their adapter. + +Do not refactor unrelated outline, caller, callee, qualified-symbol, or semantic +search logic. Existing outline entries may be reused only where they preserve the +contracts above; direct AST extraction is required for barriers, decorators, and +Rust impl identity. + +## Correctness Invariants + +1. Raw matches, ranking, pagination, and omission counts are identical with + attribution enabled or abstaining. +2. Every attributed hit has exactly one structurally containing callable range. +3. The displayed qualified name and inclusive range match source exactly. +4. The narrowest callable region wins; ties and anonymous barriers abstain. +5. Parse errors and unsupported name forms produce no owner evidence, never a + fallback guess. +6. No new-language edge or zero-edge claim is rendered. +7. Existing Go attribution, Go edges, output, and tests remain byte-identical. +8. Same source and visible hit slice produce deterministic byte-stable output. +9. TS/JS family extensions route through the correct existing grammar. +10. Scope-relative and Windows path behavior remains unchanged. + +## Accuracy Suite + +Create curated table-driven fixtures per language adapter. “0 wrong” cannot be +satisfied by abstaining everywhere. + +### Per-language minimum + +For each of JS/TS family, Python, and Rust: + +- at least 60 positive hit assertions across supported owner forms; +- at least 20 explicit abstention assertions across anonymous barriers, + unsupported names, body-less declarations, malformed source, and equal-range + ambiguity where applicable; +- 100% of required supported-form positives attributed; +- 100% exact qualified names and inclusive ranges; +- 0 false attributions; +- deterministic output under repeated runs; +- 100% callable-kind manifest coverage against the pinned grammar node metadata; + every callable kind classified as `Named` or `AnonymousBarrier`. + +The JS/TS curated matrix must contain `.ts`, `.tsx`, `.js`, and `.jsx` fixtures, +not only one grammar. Include nested named callables inside and outside anonymous +barriers. Python must include decorated async methods and nested class/def +hierarchies. Rust must include inherent impl, trait default method, trait impl, +generics, modules, nested functions, and closures. + +Add cross-language orchestration tests proving one Text OR query can attribute +supported files while preserving raw hits from malformed/unsupported files. + +## Real-Repository Replay + +Use the already-pinned benchmark repositories and SHAs: + +| Language | Repository | SHA | +| --- | --- | --- | +| TypeScript | Effect | `9245bc59ebfa688e8c92dd691296ee69d0815e59` | +| JavaScript | Express | `1140301f6a0ed5a05bc1ef38d48294f75a49580c` | +| Python | FastAPI | `6fa573ce0bc16fe445f93db413d20146dd9ff35d` | +| Rust | ripgrep | `0a88cccd5188074de96f54a4b6b44a63971ac157` | + +Predeclare at least one three-term Text OR query per repository before examining +candidate results. If the first query yields fewer than 50 attributed hit-owner +pairs, add another query and record why; do not cherry-pick only easy owners. + +For each repository, audit attributed pairs in deterministic +`(path,line,qualified_name,start,end)` order. Start with the first 50, which must +span at least 10 distinct files. If they do not, continue in the same order until +10 files are represented and audit every additional pair traversed; never skip +pairs to manufacture spread. + +- required result: every audited pair has exact range containment and + qualified-name correctness (at least 50 pairs across at least 10 files); +- required false-attribution count: 0; +- record total raw hits, attributed hits, barrier abstentions observed, parse-error + abstentions, and distinct owner forms; +- report attribution rate descriptively, not as a quality score. + +Also replay the same commands twice and require byte-identical owner rollups. +No new model A/B is required: this gate proves attribution accuracy, while prior +experiments already established owner-value demand. + +## Regression And Verification Matrix + +| Layer | Required proof | +| --- | --- | +| Unit | Per-language 60 positive + 20 abstention assertions; callable-kind manifest 100%; exact names/ranges; barriers; local errors; deterministic ties | +| Integration | Existing trigger parity; compact and detail shapes; mixed languages; artifact abstention; no non-Go edge/zero-edge claim | +| Go regression | Existing Go exact outputs and complete Go owner/edge suite byte-identical | +| Real repos | Effect/Express/FastAPI/ripgrep deterministic audit; ≥50 pairs and ≥10 files each; 0 false attribution | +| Build | `cargo fmt`; `cargo fmt --check`; targeted tests; `cargo test --locked`; `cargo clippy -- -D warnings` | +| npm | `node npm/install.test.js`; `(cd npm && npm pack --dry-run)` if package metadata or release surface changes | +| Platform | One real Windows build/run after phase 1, covering Go plus TS/Python/Rust owner paths and pasted `show` anchors | + +## Documentation + +After behavior is verified: + +- Update GUIDE language scope and state explicitly that call edges remain Go-only. +- Update README only if an existing language-support/output statement becomes + incomplete; do not add speculative examples. +- Keep CHANGELOG under `Unreleased` and draft one bundled release note covering + Go owners/edges, US-065 compaction, and phase-1 owner-only languages. +- Do not choose or write a release version until the user decides it. + +## Out Of Scope + +- Call edges for TypeScript/JavaScript, Python, or Rust. +- Dynamic dispatch, callback target, dependency-injection, protocol, trait-object, + import, or binding resolution. +- New flags, config, intent classifier, trigger thresholds, caps, or ranking. +- C, C++, Java, C#, or any phase-2 language. +- Anonymous-owner synthetic names. +- Semantic module/package inference from paths. +- New model A/B runs. +- Version bump, tag, publish, push, or release. + +## Done Bar + +Implementation is complete only when the curated matrices and callable-kind +manifests pass with 0 false attributions, all four deterministic real-repo audits +cover at least 50 pairs across at least 10 files with every audited pair exact, +Go output is unchanged, docs describe owner-only language scope honestly, and +full local verification passes. The complete release bundle is only +release-eligible after the real Windows gate; actual versioning and shipping +still require an explicit +user command. From 7c812c618ed48efc926f29737b4d8e305e39340f Mon Sep 17 00:00:00 2001 From: sting8k Date: Tue, 11 Aug 2026 23:45:11 +0700 Subject: [PATCH 10/26] feat: Python owner attribution with honest Go appendix gating Add multilanguage owner region extraction (US-067 phase 1). Python files are parsed into Named owner regions and AnonymousBarriers; a hit line is attributed to the unique narrowest named owner, abstaining on equal-width ties, anonymous callables (lambda, unnamed class), decorator lines, and local parser ERROR/missing-node points. A version-pinned manifest gate pins the tree-sitter-python NODE_TYPES fingerprint and verifies callable/container inventories are disjoint, so grammar drift fails the test suite. The Go mechanical-call appendix is now gated on an explicit successful Go parse (go_call_analysis_attempted) plus actual Go owner evidence; the zero-edge sentence additionally requires a Go-only result with >=2 distinct Go owners. A non-Go honesty caveat is emitted only when non-Go owner evidence actually rendered. Malformed Go no longer suppresses nothing nor spuriously renders Go-only claims. quality matrix: independent-fixture Case table (each parsed separately, 1-based local line numbers, exact qualified_name/start/end per positive row). 69 positive + 23 intentional abstention assertions, programmatic >=60 / >=20 floors. Counted abstentions are intentional cases (decorator lines, class/module outside-callable lines, lambda placement/nesting, malformed/ERROR/missing hierarchies); blank/separator lines are asserted incidentally and never count toward the floor. --- src/commands/find.rs | 189 ++++++++-- src/evidence/mod.rs | 1 + src/evidence/owner_links.rs | 106 +++++- src/evidence/owners/mod.rs | 320 ++++++++++++++++ src/evidence/owners/python.rs | 688 ++++++++++++++++++++++++++++++++++ src/types.rs | 10 +- tests/intent_first_cli.rs | 76 +++- 7 files changed, 1335 insertions(+), 55 deletions(-) create mode 100644 src/evidence/owners/mod.rs create mode 100644 src/evidence/owners/python.rs diff --git a/src/commands/find.rs b/src/commands/find.rs index 84e2dd9..04a21e3 100644 --- a/src/commands/find.rs +++ b/src/commands/find.rs @@ -10,6 +10,7 @@ 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, @@ -710,41 +711,59 @@ fn render_owner_link_appendix(owner_links: &OwnerLinkEvidence, scope: &Path) -> return String::new(); } let mut rendered = String::new(); - if owner_links.edges.is_empty() { - if owner_links.attributed_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() - ); + + // 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}"); } - let _ = write!(rendered, "\n\n{OWNER_LINK_CAVEAT}"); rendered } @@ -2036,6 +2055,11 @@ mod tests { } 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(), @@ -2044,6 +2068,8 @@ mod tests { package_dir: PathBuf::from("."), start_line: s, end_line: e, + language: crate::types::Lang::Go, + display_name, } } @@ -2059,6 +2085,7 @@ mod tests { let ev = OwnerLinkEvidence { hits, edges: edges.to_vec(), + go_call_analysis_attempted: true, }; render_owner_link_appendix(&ev, Path::new("")) } @@ -2241,6 +2268,7 @@ mod tests { 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); @@ -2318,6 +2346,7 @@ mod tests { 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); @@ -2325,4 +2354,98 @@ mod tests { // 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}" + ); + } } diff --git a/src/evidence/mod.rs b/src/evidence/mod.rs index b09b17a..6676792 100644 --- a/src/evidence/mod.rs +++ b/src/evidence/mod.rs @@ -5,6 +5,7 @@ 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/owner_links.rs b/src/evidence/owner_links.rs index 834ffe4..10d6cf9 100644 --- a/src/evidence/owner_links.rs +++ b/src/evidence/owner_links.rs @@ -10,24 +10,39 @@ 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.receiver_type.as_ref().map_or_else( - || self.name.clone(), - |receiver| format!("{receiver}.{}", self.name), - ) + self.display_name.clone() } fn receiver_identity(&self) -> Option<(&Path, &str)> { @@ -63,6 +78,11 @@ pub(crate) struct OwnerCallEvidence { 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 { @@ -73,17 +93,33 @@ impl OwnerLinkEvidence { .map(|hit| &hit.owner) } - pub(crate) fn attributed_owner_count(&self) -> usize { + 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) fn has_owners(&self) -> bool { - !self.hits.is_empty() - } } pub(crate) struct OwnerLinkHitInput<'a> { @@ -130,9 +166,15 @@ enum Initializer { } 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 { - if crate::lang::detect_file_type(input.path) == crate::types::FileType::Code(Lang::Go) { + 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); + if is_go || is_python { by_path .entry(input.path.to_path_buf()) .or_default() @@ -146,6 +188,27 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own 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; + } 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. @@ -224,7 +287,17 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own .then(a.candidate.start_line.cmp(&b.candidate.start_line)) }); - OwnerLinkEvidence { hits, edges } + // `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( @@ -502,6 +575,9 @@ fn collect_file_owners( 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(), @@ -511,6 +587,8 @@ fn collect_file_owners( package_dir: package_dir.to_path_buf(), start_line: entry.start_line, end_line: entry.end_line, + language: Lang::Go, + display_name, }, }); } @@ -524,6 +602,8 @@ fn collect_file_owners( 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(), }, }); } @@ -1624,6 +1704,8 @@ mod tests { package_dir: dir.clone(), start_line: 4, end_line: 4, + language: Lang::Go, + display_name: "A.Set".into(), }, }, FileOwner { @@ -1635,6 +1717,8 @@ mod tests { package_dir: dir.clone(), start_line: 4, end_line: 4, + language: Lang::Go, + display_name: "B.Set".into(), }, }, ]; diff --git a/src/evidence/owners/mod.rs b/src/evidence/owners/mod.rs new file mode 100644 index 0000000..3f82cf4 --- /dev/null +++ b/src/evidence/owners/mod.rs @@ -0,0 +1,320 @@ +//! 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 python; + +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/python.rs b/src/evidence/owners/python.rs new file mode 100644 index 0000000..27fd9fe --- /dev/null +++ b/src/evidence/owners/python.rs @@ -0,0 +1,688 @@ +//! 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 = 0x1dd4c1a2e4a91aeb; + +/// Stable FNV-1a 64-bit hash, dependency-free and reproducible across builds. +#[cfg(test)] +fn fnv1a(bytes: &[u8]) -> u64 { + let mut hash: u64 = 0xcbf29ce484222325; + for &b in bytes { + hash ^= b as u64; + hash = hash.wrapping_mul(0x100000001b3); + } + 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. + match node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + Some(name) => { + containers.push(name.to_string()); + recurse(node, bytes, path, containers, errors, regions); + containers.pop(); + } + None => { + // 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(|o| o.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/types.rs b/src/types.rs index a326998..39ff22b 100644 --- a/src/types.rs +++ b/src/types.rs @@ -94,7 +94,7 @@ pub struct RegexCoOccurrenceQuery { /// Provider-owned language identity for removable capability modules. #[allow(dead_code)] -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct ProviderLang { id: LangId, label: &'static str, @@ -121,7 +121,7 @@ impl ProviderLang { /// Programming language, carried through the type system so downstream /// code never re-detects. Built-in IDs stay closed; provider extensions use /// `Lang::Provider` while the compiler still checks built-in coverage. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Lang { Rust, TypeScript, @@ -176,7 +176,7 @@ impl FileType { /// What the output contains — shown in the header bracket. #[allow(dead_code)] -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct ProviderViewMode { id: ViewModeId, label: &'static str, @@ -377,7 +377,7 @@ pub struct OutlineEntry { } #[allow(dead_code)] -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct ProviderOutlineKind { id: OutlineKindId, outline_label: &'static str, @@ -426,7 +426,7 @@ impl ProviderOutlineKind { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum OutlineKind { Import, Function, diff --git a/tests/intent_first_cli.rs b/tests/intent_first_cli.rs index 3960ebc..663237b 100644 --- a/tests/intent_first_cli.rs +++ b/tests/intent_first_cli.rs @@ -1265,11 +1265,11 @@ fn discover_text_or_owner_caveat_survives_budget_truncation() { } #[test] -fn discover_text_or_non_go_abstains_from_owner_evidence() { - // Owner evidence is Go-only. A non-Go Text OR must not emit owner rollup - // or mechanical-call markers, even though its output uses `- [` bullet - // shapes elsewhere. Assert absence of the exact owner markers, not `- [`. - let dir = temp_repo("discover_text_or_non_go_owner"); +fn discover_text_or_python_attributes_owners_without_go_call_appendix() { + // US-067 phase 1: Python files now carry owner attribution. The owner + // rollup is emitted, the Go-only mechanical-call appendix is NOT (no Go + // call-analysis attempt), and the non-Go honesty caveat applies. + let dir = temp_repo("discover_text_or_python_owner"); fs::write( dir.join("app.py"), "def apply():\n pass\ndef set():\n apply()\ndef flush():\n set()\n", @@ -1295,7 +1295,11 @@ fn discover_text_or_non_go_abstains_from_owner_evidence() { String::from_utf8_lossy(&output.stderr) ); let stdout = String::from_utf8_lossy(&output.stdout); - assert!(!stdout.contains("owners (#N=Nth query term"), "{stdout}"); + // Python owner rollup is rendered. + assert!(stdout.contains("owners (#N=Nth query term"), "{stdout}"); + assert!(stdout.contains("apply:1-2[#1]"), "{stdout}"); + assert!(stdout.contains("set:3-4[#1,#2]"), "{stdout}"); + // No Go call appendix is emitted for a non-Go-only query. assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); assert!( !stdout.contains("[recv=same package-qualified receiver type"), @@ -1305,6 +1309,66 @@ fn discover_text_or_non_go_abstains_from_owner_evidence() { !stdout.contains("structural owner and mechanically filtered"), "{stdout}" ); + // Non-Go honesty caveat present, and it must not imply call analysis ran. + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_malformed_go_with_python_owners_suppresses_go_call_appendix() { + // Regression for the gate bug: a malformed Go input must not leave + // `go_call_analysis_attempted` true, because `build_owner_link_evidence` + // only inserts successfully-parsed Go files into its analysis set. Python + // owner attribution is retained, but the Go-only mechanical-call appendix + // (zero-edge sentence + call caveat) must NOT render. + let dir = temp_repo("discover_malformed_go_suppresses_go_appendix"); + fs::write(dir.join("app.py"), "def apply():\n pass\n").unwrap(); + // Deterministically malformed Go: unclosed parameter list. + fs::write(dir.join("broken.go"), "package p\nfunc main( {\n").unwrap(); + + let output = srcwalk() + .args([ + "discover", + "apply,main", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + // Python owner evidence is retained. + assert!(stdout.contains("[owner apply@1-2]"), "{stdout}"); + // The malformed Go hit is present but carries NO owner attribution. + assert!(stdout.contains("broken.go:2"), "{stdout}"); + assert!(!stdout.contains("broken.go:2 [owner"), "{stdout}"); + // No Go zero-edge sentence, no Go call caveat, no Mechanical Go header. + assert!( + !stdout.contains("No direct name-level call evidence"), + "{stdout}" + ); + assert!( + !stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + // Non-Go honesty caveat is retained. + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); let _ = fs::remove_dir_all(&dir); } From f7b6a5587af1c01869dca9fbd5594b20b992b87f Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 00:17:14 +0700 Subject: [PATCH 11/26] fix(python): clippy -D warnings mechanical lints in owner adapter Corrects the false slice-1 'clippy clean' verification claim: the earlier grep pattern missed clippy's indented error lines, so python.rs baseline lints went unreported. Mechanical-only fixes, no behavior change: - digit separators in FNV-1a fingerprint/hash constants - u64::from(b) instead of a u8-as-u64 cast - if-let instead of single-binding match (class_definition) - method pointer OwnerAnchor::qualified_name - inline {e:?} format args - doc_markdown backticks cargo clippy --lib -- -D warnings exits 0; python owner suite 13 pass. --- src/evidence/owners/python.rs | 52 ++++++++++++++++------------------- 1 file changed, 24 insertions(+), 28 deletions(-) diff --git a/src/evidence/owners/python.rs b/src/evidence/owners/python.rs index 27fd9fe..7b305c1 100644 --- a/src/evidence/owners/python.rs +++ b/src/evidence/owners/python.rs @@ -49,15 +49,15 @@ const PYTHON_BODILESS_DECLARATIONS: &[&str] = &[]; /// (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 = 0x1dd4c1a2e4a91aeb; +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 = 0xcbf29ce484222325; + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; for &b in bytes { - hash ^= b as u64; - hash = hash.wrapping_mul(0x100000001b3); + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x100_0000_01b3); } hash } @@ -146,25 +146,22 @@ fn walk( } "class_definition" => { // Class is a lexical container for naming, not itself a callable. - match node + if let Some(name) = node .child_by_field_name("name") .and_then(|n| n.utf8_text(bytes).ok()) { - Some(name) => { - containers.push(name.to_string()); - recurse(node, bytes, path, containers, errors, regions); - containers.pop(); - } - None => { - // 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); - } + 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" => { @@ -237,7 +234,7 @@ mod tests { fn assert_owner(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32, name: &str) { let owner = python_owner_for(regions, errors, line); assert_eq!( - owner.map(|o| o.qualified_name()), + owner.map(OwnerAnchor::qualified_name), Some(name.to_string()), "line {line} should attribute to {name}" ); @@ -335,10 +332,9 @@ mod tests { assert!( e.iter() .any(|er| er.is_point && er.start_byte == er.end_byte), - "{:?}", - e + "{e:?}" ); - assert!(e.iter().any(|er| er.contains_line(1)), "{:?}", 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(), @@ -381,10 +377,10 @@ mod tests { /// 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). + /// (`>=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] = &[ From 8c7967715671662500d4b22941c7fe3cd42e5ac6 Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 00:17:49 +0700 Subject: [PATCH 12/26] feat: Rust owner attribution with exact qualified identity (US-067 phase 2) Implement the Rust owner adapter pairing exact named forms with honest barriers/abstentions, satisfying the Rust owner quality matrix and manifest gate. Named forms (exact, no guessing): - Top-level & body-bearing function_item -> name - Nested module/function -> a::b::f - Inherent impl -> Type::method (Stack::push) - Trait default -> Trait::method (Greet::bye) - Trait impl -> exactly ::method (::fmt) Malformed-container recovery (structural, not grammar-string patch): - A collapsed mod/impl/trait with no valid identity is detected via its ERROR-recovery context: an expression_statement wrapping a block with an immediately-preceding ERROR sibling. Under this `recovery` context every contained callable is classified as an AnonymousBarrier (never a guessed partial name) while traversal continues, so EVERY callable node is classified (omission is a contract violation). - Valid lexically nested function items inside clean if/loop/match/standalone blocks have no ERROR sibling and stay eligible (outer::inner). - Unreadable/missing impl identity, nameless mod/trait, and nameless function all barrier and keep recursing so nested callables are individually classified. Barriers/abstentions: every closure barriers; body-less function_signature_item abstains; macro_definition barriers; macro_invocation not guessed. Tests: clean nested-block positives; exhaustive-barrier classification for malformed mod/impl/trait; manifest gate pinned (0x50a2_cce6_3015_8590); matrix floor 71/32; cross-language Go edge filter regression preserved. --- src/evidence/owner_links.rs | 76 ++- src/evidence/owners/mod.rs | 1 + src/evidence/owners/rust.rs | 1142 +++++++++++++++++++++++++++++++++++ tests/intent_first_cli.rs | 106 ++++ 4 files changed, 1324 insertions(+), 1 deletion(-) create mode 100644 src/evidence/owners/rust.rs diff --git a/src/evidence/owner_links.rs b/src/evidence/owner_links.rs index 10d6cf9..527cdb9 100644 --- a/src/evidence/owner_links.rs +++ b/src/evidence/owner_links.rs @@ -174,7 +174,8 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own 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); - if is_go || is_python { + let is_rust = detected == crate::types::FileType::Code(Lang::Rust); + if is_go || is_python || is_rust { by_path .entry(input.path.to_path_buf()) .or_default() @@ -209,6 +210,26 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own } 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; + } 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. @@ -234,9 +255,15 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own ); } + // 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(); @@ -1316,6 +1343,53 @@ mod tests { 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"); diff --git a/src/evidence/owners/mod.rs b/src/evidence/owners/mod.rs index 3f82cf4..45d2f19 100644 --- a/src/evidence/owners/mod.rs +++ b/src/evidence/owners/mod.rs @@ -14,6 +14,7 @@ //! model, the unique-narrowest selection, and local-`ERROR` primitives. pub(crate) mod python; +pub(crate) mod rust; use crate::evidence::owner_links::OwnerAnchor; diff --git a/src/evidence/owners/rust.rs b/src/evidence/owners/rust.rs new file mode 100644 index 0000000..5263373 --- /dev/null +++ b/src/evidence/owners/rust.rs @@ -0,0 +1,1142 @@ +//! Rust owner-region extraction (US-067 phase 2). +//! +//! Supported named owners: top-level and body-bearing `function_item` nodes, +//! nested module/function `::` paths, inherent `Type::method`, trait default +//! `Trait::method`, and trait impl exactly `::method`. +//! +//! Abstractions/barriers: every `closure_expression` is an `AnonymousBarrier`; +//! body-less `function_signature_item` (trait/extern declarations) abstain so +//! they cannot fall through; an `impl_item` whose identity is missing/unreadable +//! is a full-callable `AnonymousBarrier` (never an unqualified fallback); a +//! `mod_item` with no structural name, and any callable reached through an +//! anonymous collapsed-module block, barrier so guessed child names never leak; +//! `macro_definition` regions barrier so macro-generated owners are not guessed. + +use std::path::Path; + +use tree_sitter::Node; + +use crate::evidence::owner_links::OwnerAnchor; +use crate::evidence::owners::{ + any_error_overlaps_bytes, attribute_line, collect_error_ranges, degrade_named_on_error, + ErrorRange, OwnerRegion, +}; +use crate::lang::outline::outline_language; +use crate::types::Lang; + +/// Version-pinned Rust callable manifest (anti-drift contract). +/// +/// Inventories are kept distinct so a grammar change to one category cannot +/// silently reclassify a node into another: +/// +/// * (a) executable callable kinds that MUST be classified `Named`/`Barrier`; +/// * (b) binding/container/wrapper kinds used only for naming/context; +/// * (c) body-less declaration kinds that abstain/barrier (no owner region). +#[cfg(test)] +const RUST_EXECUTABLE_CALLABLES: &[&str] = &["function_item", "closure_expression"]; +#[cfg(test)] +const RUST_CONTAINER_KINDS: &[&str] = &["mod_item", "impl_item", "trait_item", "foreign_mod_item"]; +#[cfg(test)] +const RUST_BODILESS_DECLARATIONS: &[&str] = &["function_signature_item"]; + +/// FNV-1a-64 fingerprint of the bundled `tree-sitter-rust` `NODE_TYPES` JSON +/// (tree-sitter-rust 0.24.2). Pinned so any grammar metadata change fails the +/// manifest gate and forces a re-audit of the inventories above. +#[cfg(test)] +const RUST_NODE_TYPES_FINGERPRINT: u64 = 0x50a2_cce6_3015_8590; + +/// Stable FNV-1a 64-bit hash, dependency-free and reproducible across builds. +#[cfg(test)] +fn fnv1a(bytes: &[u8]) -> u64 { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for &b in bytes { + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x100_0000_01b3); + } + hash +} + +/// Parse a Rust file and produce its owner regions and local error ranges. +/// Returns `None` when the file cannot be read, has no tree, or its root node +/// itself is an `ERROR` (preserve raw hits, emit no owner evidence). +pub(crate) fn rust_regions( + path: &Path, + content: &str, +) -> Option<(Vec, Vec)> { + let language = outline_language(Lang::Rust)?; + let mut parser = tree_sitter::Parser::new(); + if parser.set_language(&language).is_err() { + return None; + } + let tree = parser.parse(content, None)?; + if tree.root_node().kind() == "ERROR" { + return None; + } + let bytes = content.as_bytes(); + let errors = collect_error_ranges(&tree, bytes); + let mut regions = Vec::new(); + let mut prefixes: Vec = Vec::new(); + walk( + tree.root_node(), + bytes, + path, + &mut prefixes, + &errors, + &mut regions, + false, + ); + Some((regions, errors)) +} + +/// Walk a Rust tree, emitting `Named` regions for body-bearing `function_item` +/// nodes and `AnonymousBarrier` regions for every other callable (closures, +/// body-less signatures, and callables whose enclosing container identity is +/// unknown). A `prefixes` stack carries `::`-suffixed path segments (modules, +/// functions, inherent/trait impls, traits) so nested callables get their full +/// qualified name. `impl` identity text is preserved from source tokens with +/// whitespace collapsed; an unreadable impl becomes a full-callable barrier. +/// +/// `recovery` is true when walking inside a collapsed malformed container +/// (`mod {`, `impl {`, pointer-less `trait {`), +/// which tree-sitter recovers as an `expression_statement`-wrapped block with +/// an immediately-preceding ERROR sibling. Under `recovery` every contained +/// callable is classified as an `AnonymousBarrier` (never a guessed name), but +/// traversal still continues so EVERY callable node is classified — omission +/// is a contract violation. A structurally named callable inside an ordinary +/// anonymous closure barrier remains eligible when its naming context is valid. +fn walk( + node: Node<'_>, + bytes: &[u8], + path: &Path, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + recovery: bool, +) { + match node.kind() { + "function_item" => walk_function(node, bytes, path, prefixes, errors, regions, recovery), + "closure_expression" => { + // Anonymous barrier: a hit inside a closure must not fall through + // to an enclosing named owner. Recurse so a named item nested + // inside a closure still gets classified; under a valid naming + // context it remains eligible within its narrower range. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, recovery); + } + "function_signature_item" => { + // Body-less trait/extern signature: abstain so it cannot fall + // through to an enclosing owner. No body to recurse into. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + } + "impl_item" => walk_impl(node, bytes, path, prefixes, errors, regions, recovery), + "trait_item" => { + if recovery { + // Invalid-identity context: barrier the whole trait and keep + // traversing so every contained callable is classified. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + } else if let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + prefixes.push(format!("{}::", name.trim())); + recurse(node, bytes, path, prefixes, errors, regions, false); + prefixes.pop(); + } else { + // Nameless trait: unknown lexical container identity. + // Barrier and continue so contained callables (usually + // signatures) are classified, never guessed. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + } + } + "mod_item" => { + if recovery { + // Invalid-identity context: barrier the whole module and keep + // traversing so every contained callable is classified. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + } else if let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + prefixes.push(format!("{}::", name.trim())); + recurse(node, bytes, path, prefixes, errors, regions, false); + prefixes.pop(); + } else { + // Nameless module: unknown lexical container identity. + // Barrier and continue so every contained callable is + // classified, never exposed with a guessed name. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + } + } + "foreign_mod_item" => { + // Extern block: body-less signatures inside are barriers; the + // block itself is a transparent container (no name to qualify). + recurse(node, bytes, path, prefixes, errors, regions, recovery); + } + "macro_definition" => { + // macro_rules! is not a callable; its rule bodies are not code to + // recurse into. Barrier so generated-owner lines never leak. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + } + "expression_statement" => { + if is_recovery_wrapper(node) { + // A collapsed malformed container (mod/impl/trait with no valid + // identity) recovers here: an expression_statement wrapping a + // block of declarations with an immediately-preceding ERROR. Its + // contained callables have unknown identity, so the whole block + // is a barrier and traversal continues under `recovery`. + if let Some(block) = node.named_child(0) { + regions.push(OwnerRegion::AnonymousBarrier { + start_line: block.start_position().row as u32 + 1, + end_line: block.end_position().row as u32 + 1, + }); + } + recurse(node, bytes, path, prefixes, errors, regions, true); + } else { + recurse(node, bytes, path, prefixes, errors, regions, recovery); + } + } + // `macro_invocation` is a statement/expression, not a callable; do not + // guess owners from its generated token tree. Skip (enclosing owner + // still owns the line). + _ => recurse(node, bytes, path, prefixes, errors, regions, recovery), + } +} + +/// Whether `node` is the recovery wrapper of a collapsed malformed container: +/// an `expression_statement` whose first named child is a `block` and which has +/// an immediately-preceding ERROR sibling. This is the structural fingerprint +/// of `mod {`, an unreadable `impl {`, or name-less `trait +/// {` (tree-sitter parses the stray `{ ... }` as a statement block). It is NOT +/// a valid nested block: those (standalone block, if/loop/match bodies) have no +/// ERROR sibling, so a lexically nested `function_item` inside them stays +/// eligible. The preceding ERROR must itself announce a collapsed mod/impl/trait +/// container (its subtree contains the relevant item-introducer keyword token), +/// so an unrelated local ERROR before a valid standalone block is rejected. +/// +/// NOTE: the keyword may be an unnamed token, so all ERROR children are walked. +fn is_recovery_wrapper(node: Node<'_>) -> bool { + if node.kind() != "expression_statement" { + return false; + } + if node + .named_child(0) + .is_none_or(|first| first.kind() != "block") + { + return false; + } + let Some(parent) = node.parent() else { + return false; + }; + let mut cursor = parent.walk(); + let siblings: Vec> = parent.named_children(&mut cursor).collect(); + let Some(idx) = siblings.iter().position(|s| s.id() == node.id()) else { + return false; + }; + idx > 0 + && siblings[idx - 1].kind() == "ERROR" + && error_is_collapsed_container(siblings[idx - 1]) +} + +/// Whether an ERROR node announces a collapsed `mod`/`impl`/`trait` container: +/// its subtree contains an anonymous grammar token of kind `mod`, `impl`, or +/// `trait`. Traversal is purely structural (`Node::kind()`, no source text/bytes, +/// no whole-ERROR fallback) and recurses through ALL children because the token +/// may sit below the immediate child. This rejects unrelated local ERRORs (e.g. +/// a stray `struct`/`enum`/`foo(`) that happen to be immediately followed by a +/// valid standalone block, so a clean nested `function_item` with no ERROR +/// overlap stays eligible. +fn error_is_collapsed_container(error: Node<'_>) -> bool { + fn contains_item_keyword(node: Node<'_>) -> bool { + let mut cursor = node.walk(); + for child in node.children(&mut cursor) { + if !child.is_named() && matches!(child.kind(), "mod" | "impl" | "trait") { + return true; + } + if contains_item_keyword(child) { + return true; + } + } + false + } + contains_item_keyword(error) +} + +/// Emit a `Named` region for a body-bearing callable, or a full-callable +/// `AnonymousBarrier` when the callable is under an invalid-identity/recovery +/// context or has no structural name. Traversal always continues so every +/// nested callable is classified (never omitted). +fn walk_function( + node: Node<'_>, + bytes: &[u8], + path: &Path, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + recovery: bool, +) { + let start_line = node.start_position().row as u32 + 1; + let end_line = node.end_position().row as u32 + 1; + if recovery { + // Under a collapsed malformed container the enclosing identity is + // unknown; classify this callable as a barrier and keep traversing so + // deeper callables are also classified (never a guessed partial name). + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + return; + } + if let Some(name) = node + .child_by_field_name("name") + .and_then(|n| n.utf8_text(bytes).ok()) + { + let name = name.to_string(); + let qualified = join_prefixes(prefixes, &name); + let anchor = OwnerAnchor { + path: path.to_path_buf(), + name: name.clone(), + receiver_var: None, + receiver_type: None, + package_dir: std::path::PathBuf::from("."), + start_line, + end_line, + language: Lang::Rust, + display_name: qualified, + }; + let region = OwnerRegion::Named(anchor); + let region = degrade_named_on_error(region, errors, node.start_byte(), node.end_byte()); + regions.push(region); + prefixes.push(format!("{name}::")); + recurse(node, bytes, path, prefixes, errors, regions, false); + prefixes.pop(); + } else { + // Nameless function: unknown identity; barrier and keep traversing so + // deeper callables are classified (never guessed). + regions.push(OwnerRegion::AnonymousBarrier { + start_line, + end_line, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + } +} + +/// Walk an `impl_item`: inherent (`impl Type`) or trait (`impl Trait for +/// Type`). Pushes the correctly-qualified prefix so methods become +/// `Type::method` or `::method`. An unreadable/missing impl +/// identity becomes a full-callable barrier over the whole impl (never an +/// unqualified fallback) while traversal continues under an invalid-identity +/// context so every contained callable is classified. +fn walk_impl( + node: Node<'_>, + bytes: &[u8], + path: &Path, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + recovery: bool, +) { + let body_byte = node + .child_by_field_name("body") + .map_or(node.end_byte(), |b| b.start_byte()); + // The signature region is from the `impl` keyword to the body. An ERROR + // there means the identity text is unreadable -> full barrier. + let identity_unreadable = any_error_overlaps_bytes(errors, node.start_byte(), body_byte); + let type_text = node + .child_by_field_name("type") + .and_then(|n| n.utf8_text(bytes).ok()) + .map(normalize_impl_text); + let trait_text = node + .child_by_field_name("trait") + .and_then(|n| n.utf8_text(bytes).ok()) + .map(normalize_impl_text); + let prefix = match (&type_text, &trait_text) { + (Some(ty), None) => Some(format!("{ty}::")), + (Some(ty), Some(tr)) => Some(format!("<{ty} as {tr}>::")), + _ => None, + }; + if recovery { + // Under a collapsed malformed container: barrier the whole impl and + // keep traversing so every contained callable is classified. + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + return; + } + if let (Some(prefix), false) = (prefix, identity_unreadable) { + prefixes.push(prefix); + recurse(node, bytes, path, prefixes, errors, regions, false); + prefixes.pop(); + } else { + // Unreadable/missing impl identity: full-callable barrier; do not + // emit unqualified method names, but keep traversing so every + // contained callable is classified (never omitted). + regions.push(OwnerRegion::AnonymousBarrier { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + 1, + }); + recurse(node, bytes, path, prefixes, errors, regions, true); + } +} + +#[allow(clippy::too_many_arguments)] +fn recurse( + node: Node<'_>, + bytes: &[u8], + path: &Path, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + recovery: bool, +) { + let mut cursor = node.walk(); + for child in node.named_children(&mut cursor) { + walk(child, bytes, path, prefixes, errors, regions, recovery); + } +} +fn join_prefixes(prefixes: &[String], name: &str) -> String { + if prefixes.is_empty() { + name.to_string() + } else { + let mut joined = prefixes.concat(); + joined.push_str(name); + joined + } +} + +/// Preserve an impl type/trait node's source tokens and punctuation, trimming +/// and collapsing each `split_whitespace` run to one ASCII space. No semantic +/// resolution (e.g. `Foo` stays `Foo`, `Vec < T >` collapses to +/// `Vec < T >`). +fn normalize_impl_text(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +/// Attribute a Rust hit line to a named owner, honoring local errors. +pub(crate) fn rust_owner_for<'a>( + regions: &'a [OwnerRegion], + errors: &[ErrorRange], + line: u32, +) -> Option<&'a OwnerAnchor> { + attribute_line(regions, errors, line) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + use std::path::PathBuf; + + fn path() -> PathBuf { + PathBuf::from("tests/fixtures/x.rs") + } + + fn parse(src: &str) -> (Vec, Vec) { + rust_regions(&path(), src).expect("should parse") + } + + fn assert_owner(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32, name: &str) { + let owner = rust_owner_for(regions, errors, line); + assert_eq!( + owner.map(OwnerAnchor::qualified_name), + Some(name.to_string()), + "line {line} should attribute to {name}" + ); + } + + fn assert_abstain(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32) { + assert!( + rust_owner_for(regions, errors, line).is_none(), + "line {line} should abstain" + ); + } + + #[test] + fn top_level_function_and_inherent_method() { + let (r, e) = parse("struct Foo {}\nimpl Foo {\n fn a() {}\n fn b(&self) {}\n}\n"); + assert_owner(&r, &e, 3, "Foo::a"); + assert_owner(&r, &e, 4, "Foo::b"); + assert_abstain(&r, &e, 2); // impl header line + } + + #[test] + fn trait_impl_uses_type_as_trait_identity() { + let (r, e) = parse("impl Display for Foo {\n fn fmt(&self) {}\n}\n"); + assert_owner(&r, &e, 2, "::fmt"); + assert_abstain(&r, &e, 1); // impl header line + } + + #[test] + fn trait_default_body_some_and_body_less_signature_barriers() { + let (r, e) = + parse("trait Greet {\n fn hi();\n fn bye() {\n let x = 1;\n }\n}\n"); + assert_owner(&r, &e, 3, "Greet::bye"); + assert_abstain(&r, &e, 2); // body-less signature + assert_abstain(&r, &e, 1); // trait header line + } + + #[test] + fn nested_module_and_function_scopes_qualify_with_double_colon() { + let (r, e) = parse( + "mod a {\n mod b {\n fn f() {\n let x = 1;\n }\n }\n}\n", + ); + assert_owner(&r, &e, 3, "a::b::f"); + assert_abstain(&r, &e, 1); // mod a header + assert_abstain(&r, &e, 2); // mod b header + } + + #[test] + fn nested_function_inside_function_qualifies() { + let (r, e) = + parse("fn outer() {\n fn inner() {\n let x = 1;\n }\n inner();\n}\n"); + assert_owner(&r, &e, 1, "outer"); + assert_owner(&r, &e, 2, "outer::inner"); + assert_owner(&r, &e, 5, "outer"); + } + + #[test] + fn closure_expression_is_barrier_preventing_outer_fallthrough() { + let (r, e) = parse("fn outer() {\n let f = |x| {\n x + 1\n };\n}\n"); + assert_owner(&r, &e, 1, "outer"); + assert_abstain(&r, &e, 2); // closure line + assert_abstain(&r, &e, 3); // closure body + } + + #[test] + fn nested_closure_abstains_without_named_item() { + let (r, e) = parse("fn factory() {\n || {\n |x| x + 1\n }\n}\n"); + assert_owner(&r, &e, 1, "factory"); + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + } + + #[test] + fn generic_inherent_impl_whitespace_normalized() { + // `Stack` keeps its tokens; the identity is `Stack::push`. + let (r, e) = parse( + "impl Stack {\n fn push(self) {\n let x = 1;\n }\n}\n", + ); + assert_owner(&r, &e, 2, "Stack::push"); + assert_abstain(&r, &e, 1); + } + + #[test] + fn impl_identity_whitespace_runs_collapsed_to_single_space() { + let (r, e) = parse( + "impl Foo < T > for Bar {\n fn m() {\n let x = 1;\n }\n}\n", + ); + // Source tokens preserved with whitespace collapsed: `>::m`. + assert_owner(&r, &e, 2, ">::m"); + assert_abstain(&r, &e, 1); + } + + #[test] + fn missing_impl_identity_is_full_barrier_never_unqualified() { + // `impl Foo for {` has an ERROR in its signature region: the whole + // impl becomes a barrier; `m` must NOT fall back to an unqualified name. + let (r, e) = parse("impl Foo for {\n fn m() {\n let x = 1;\n }\n}\n"); + assert_abstain(&r, &e, 1); + assert_abstain(&r, &e, 2); // method inside unreadable impl + } + + #[test] + fn collapsed_impl_no_type_is_barrier_not_unqualified() { + // Bare `impl {` collapses to ERROR + statement block; the re-parsed + // `fn m` must not leak as an unqualified owner. + let (r, e) = parse("impl {\n fn m() {\n let x = 1;\n }\n}\n"); + assert_abstain(&r, &e, 1); + assert_abstain(&r, &e, 2); + } + + #[test] + fn malformed_module_no_name_is_barrier_not_leaking_to_outer() { + // `mod {` has no structural module name; tree-sitter collapses it to an + // ERROR plus an `expression_statement`-wrapped anonymous block. Nested + // inside a named function, the contained fn must NOT leak as an + // outer-qualified owner (`outer::inner`); the collapsed module's ERROR + // also degrades the enclosing function, so nothing inside may attribute. + let (r, e) = parse( + "fn outer() {\n mod {\n fn inner() {\n let x = 1;\n }\n }\n}\n", + ); + assert_abstain(&r, &e, 1); // outer def: degraded by the collapsed-mod ERROR + assert_abstain(&r, &e, 2); // collapsed mod header (ERROR) + assert_abstain(&r, &e, 3); // inner def: no `outer::inner` leak + assert_abstain(&r, &e, 4); // inner body + } + + #[test] + fn malformed_module_top_level_is_barrier() { + let (r, e) = parse("mod {\n fn inner() {\n let x = 1;\n }\n}\n"); + assert_abstain(&r, &e, 1); // collapsed mod header (ERROR) + assert_abstain(&r, &e, 2); // inner def line + assert_abstain(&r, &e, 3); // inner body + } + + #[test] + fn malformed_module_nested_function_does_not_leak_at_depth() { + // A function nested deeper inside the collapsed module must also not + // leak: no guessed child owner is emitted at any depth. + let (r, e) = parse( + "fn outer() {\n mod {\n fn a() {\n fn b() {\n let x = 1;\n }\n }\n }\n}\n", + ); + assert_abstain(&r, &e, 1); // outer degraded by the collapsed-mod ERROR + assert_abstain(&r, &e, 3); // a (collapsed) def line + assert_abstain(&r, &e, 4); // b def line: no deeper leak + assert_abstain(&r, &e, 5); // b body + } + + #[test] + fn nested_function_in_clean_blocks_stays_eligible() { + // Valid lexically nested function items inside clean control-flow/standalone + // blocks remain eligible: the enclosing named function is a valid naming + // context, so they are `outer::inner` (NOT mistaken for collapsed-mod artifacts). + let (r, e) = parse( + "fn outer() {\n { fn in_block() { let x = 1; } }\n if cond { fn in_if() { } }\n loop { fn in_loop() { } }\n match x { _ => { fn in_match() { } } }\n}\n", + ); + assert_owner(&r, &e, 2, "outer::in_block"); + assert_owner(&r, &e, 3, "outer::in_if"); + assert_owner(&r, &e, 4, "outer::in_loop"); + assert_owner(&r, &e, 5, "outer::in_match"); + } + + #[test] + fn malformed_container_nested_callables_classified_as_barriers() { + // Exhaustive extraction: every callable nested under a collapsed malformed + // mod/impl/trait must be individually classified as an AnonymousBarrier + // (never omitted, never given a guessed name). Prove classification by + // asserting a barrier region exists covering each nested function. + let (r, _) = parse( + "fn outer() {\n mod {\n fn a() {\n let x = 1;\n }\n fn b() {\n let y = 2;\n }\n }\n}\n", + ); + let barriers = r + .iter() + .filter_map(|region| match region { + OwnerRegion::AnonymousBarrier { + start_line, + end_line, + } => Some((*start_line, *end_line)), + OwnerRegion::Named(_) => None, + }) + .collect::>(); + assert!( + barriers.contains(&(3, 5)), + "fn a must be individually barriered, got {barriers:?}" + ); + assert!( + barriers.contains(&(6, 8)), + "fn b must be individually barriered, got {barriers:?}" + ); + // No named owner may leak from the malformed module. + assert!(r + .iter() + .all(|region| !matches!(region, OwnerRegion::Named(_)))); + } + + #[test] + fn malformed_impl_and_trait_nested_callables_classified_as_barriers() { + // `impl {` and `trait {` (no valid identity) recover to the same kind of + // statement-level block; their contained methods must barrier, not leak. + let (r1, _) = parse("impl {\n fn m() {\n let x = 1;\n }\n}\n"); + let b1 = r1 + .iter() + .filter_map(|region| match region { + OwnerRegion::AnonymousBarrier { + start_line, + end_line, + } => Some((*start_line, *end_line)), + OwnerRegion::Named(_) => None, + }) + .collect::>(); + assert!( + b1.contains(&(2, 4)), + "impl fn m must be barriered, got {b1:?}" + ); + assert!(r1 + .iter() + .all(|region| !matches!(region, OwnerRegion::Named(_)))); + + let (r2, _) = parse("trait {\n fn t() {\n let x = 1;\n }\n}\n"); + let b2 = r2 + .iter() + .filter_map(|region| match region { + OwnerRegion::AnonymousBarrier { + start_line, + end_line, + } => Some((*start_line, *end_line)), + OwnerRegion::Named(_) => None, + }) + .collect::>(); + assert!( + b2.contains(&(2, 4)), + "trait fn t must be barriered, got {b2:?}" + ); + assert!(r2 + .iter() + .all(|region| !matches!(region, OwnerRegion::Named(_)))); + } + + #[test] + fn unrelated_local_error_followed_by_clean_block_keeps_inner_eligible() { + // `foo(;` is an unrelated local ERROR (its ERROR is nested inside its own + // expression_statement, not a sibling of the block). The following valid + // standalone block is preserved, so `fn inner` (no ERROR overlap) stays + // eligible as `outer::inner` even though `outer` degrades from the local + // ERROR — the pinned local-error rule must not be contradicted. + let (r, e) = + parse("fn outer() {\n foo(;\n { fn inner() {\n let x = 1;\n } }\n}\n"); + assert_abstain(&r, &e, 1); // outer def degrades (local ERROR overlaps) + assert_owner(&r, &e, 3, "outer::inner"); + assert_owner(&r, &e, 4, "outer::inner"); + } + + #[test] + fn struct_error_is_not_recovery_leaves_nested_fn_eligible() { + // `struct {` has the SAME ERROR-sibling shape as a collapsed mod/impl/trait + // but its keyword is not a mod/impl/trait item-introducer. The keyword gate + // must reject it, so the clean nested `fn a` stays eligible as `outer::a` + // (rather than incorrectly abstaining as recovery-invalid). + let (r, e) = parse( + "fn outer() {\n struct {\n fn a() {\n let x = 1;\n }\n }\n}\n", + ); + assert_abstain(&r, &e, 1); // outer degrades from the struct ERROR + assert_owner(&r, &e, 3, "outer::a"); + assert_owner(&r, &e, 4, "outer::a"); + } + + #[test] + fn error_is_collapsed_container_accepts_only_item_introducers() { + // Direct proof of the keyword gate: a collapsed mod/impl/trait ERROR is + // accepted, but a stray struct/enum ERROR (same shape, different keyword) + // is rejected. + fn check(src: &str) -> bool { + fn find(n: tree_sitter::Node, found: &mut bool) { + if n.is_error() { + *found = error_is_collapsed_container(n); + return; + } + let mut c = n.walk(); + for ch in n.named_children(&mut c) { + find(ch, found); + } + } + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&outline_language(Lang::Rust).unwrap()) + .unwrap(); + let tree = parser.parse(src, None).unwrap(); + let mut found = false; + find(tree.root_node(), &mut found); + found + } + assert!(check( + "fn outer() {\n mod {\n fn a() {}\n }\n}\n" + )); + assert!(check( + "fn outer() {\n impl {\n fn m() {}\n }\n}\n" + )); + assert!(check( + "fn outer() {\n trait {\n fn t() {}\n }\n}\n" + )); + assert!(!check( + "fn outer() {\n struct {\n fn a() {}\n }\n}\n" + )); + assert!(!check( + "fn outer() {\n enum {\n fn a() {}\n }\n}\n" + )); + } + + #[test] + fn extern_body_less_signatures_barrier() { + let (r, e) = parse("extern \"C\" {\n fn c_func(x: i32);\n fn d_func() -> i32;\n}\n"); + assert_abstain(&r, &e, 1); + assert_abstain(&r, &e, 2); + assert_abstain(&r, &e, 3); + } + + #[test] + fn macro_definition_barriers_and_macro_invocation_not_guessed() { + let (r, e) = parse("macro_rules! make {\n () => { fn generated() {} };\n}\nfn real() {\n make!();\n}\n"); + // The macro-rules body must not produce a named `generated` owner. + assert_abstain(&r, &e, 1); + assert_abstain(&r, &e, 2); + assert_owner(&r, &e, 4, "real"); + assert_owner(&r, &e, 5, "real"); // macro invocation line still owned by `real` + } + + #[test] + fn local_error_degrades_overlapping_callable_and_clean_elsewhere_eligible() { + let (r, e) = parse("fn good() {\n}\nfn bad() {\n x = (\n ;\n}\n"); + assert_owner(&r, &e, 1, "good"); + assert_abstain(&r, &e, 3); // bad def line degrades + assert_abstain(&r, &e, 4); + } + + #[test] + fn distinct_top_level_functions_each_unique_narrowest() { + let (r, e) = parse("fn a() {\n let x = 1;\n}\nfn b() {\n}\n"); + assert_owner(&r, &e, 1, "a"); + assert_owner(&r, &e, 4, "b"); + } + + #[test] + fn empty_content_yields_no_regions() { + let (r, e) = parse("let x = 1;\n"); + assert!(r.is_empty()); + assert!(e.is_empty()); + } + + #[test] + fn module_level_statement_and_comment_abstain() { + let (r, e) = parse("fn one() {\n}\nlet x = 1;\n// c\nfn two() {\n}\n"); + assert_owner(&r, &e, 1, "one"); + assert_abstain(&r, &e, 3); // module-level let + assert_abstain(&r, &e, 4); // comment + assert_owner(&r, &e, 5, "two"); + } + + /// A single independent fixture, parsed on its own with 1-based local line + /// numbers. `owners` lists `(hit_line, name, start_line, end_line)` that + /// must attribute to the exact owner; `abstain` lists lines that must + /// abstain and count toward the intentional-abstention floor; `incidental` + /// lists lines that must abstain but do NOT count (module-level blanks). + struct Case { + label: &'static str, + source: &'static str, + owners: &'static [(u32, &'static str, u32, u32)], + abstain: &'static [u32], + incidental: &'static [u32], + } + + /// Slice-2 binding quality gate: a table of independent, varied fixtures. + /// Each case is parsed separately with local line numbers (no shared buffer, + /// no offset math). Counts assertions programmatically and asserts the floor + /// (`>=60` positive hits, `>=20` intentional abstentions); mechanically repeated + /// `blank`/`separator` lines never count toward the abstention floor. Every + /// positive row asserts the exact owner (`qualified_name`, `start_line`, + /// `end_line`); every abstention row asserts no attribution (0 mismatches). + + #[test] + fn rust_owner_matrix_meets_quality_gates() { + let cases: &[Case] = &[ + Case { + label: "top-level simple", + source: "fn alpha() {\n let x = 1;\n x\n}\n", + owners: &[ + (1, "alpha", 1, 4), + (2, "alpha", 1, 4), + (3, "alpha", 1, 4), + (4, "alpha", 1, 4), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level params + return", + source: "fn beta(a: i32, b: i32) -> i32 {\n a + b\n}\n", + owners: &[(1, "beta", 1, 3), (2, "beta", 1, 3), (3, "beta", 1, 3)], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level multiline body", + source: "fn gamma() {\n let s = String::new();\n for c in s.chars() {\n s.push(c);\n }\n s\n}\n", + owners: &[ + (1, "gamma", 1, 7), + (2, "gamma", 1, 7), + (3, "gamma", 1, 7), + (4, "gamma", 1, 7), + (5, "gamma", 1, 7), + (6, "gamma", 1, 7), + (7, "gamma", 1, 7), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "nested function", + source: "fn outer() {\n fn inner() {\n let x = 1;\n }\n inner()\n}\n", + owners: &[ + (1, "outer", 1, 6), + (2, "outer::inner", 2, 4), + (3, "outer::inner", 2, 4), + (4, "outer::inner", 2, 4), + (5, "outer", 1, 6), + (6, "outer", 1, 6), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level async", + source: "async fn fetch() {\n let data = load().await;\n data\n}\n", + owners: &[ + (1, "fetch", 1, 4), + (2, "fetch", 1, 4), + (3, "fetch", 1, 4), + (4, "fetch", 1, 4), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level unsafe", + source: "unsafe fn raw() {\n let x = 1;\n}\n", + owners: &[(1, "raw", 1, 3), (2, "raw", 1, 3), (3, "raw", 1, 3)], + abstain: &[], + incidental: &[], + }, + Case { + label: "inherent impl methods", + source: "struct Foo {}\nimpl Foo {\n fn a() {\n let x = 1;\n }\n fn b(&self) {\n let y = 2;\n }\n}\n\n", + owners: &[ + (3, "Foo::a", 3, 5), + (4, "Foo::a", 3, 5), + (5, "Foo::a", 3, 5), + (6, "Foo::b", 6, 8), + (7, "Foo::b", 6, 8), + (8, "Foo::b", 6, 8), + ], + abstain: &[1, 2], + incidental: &[10], + }, + Case { + label: "trait impl", + source: "impl Display for Foo {\n fn fmt(&self) {\n let x = 1;\n }\n}\n", + owners: &[(2, "::fmt", 2, 4), (3, "::fmt", 2, 4), (4, "::fmt", 2, 4)], + abstain: &[1], + incidental: &[], + }, + Case { + label: "trait default + body-less signature", + source: "trait Greet {\n fn hi();\n fn bye() {\n let x = 1;\n }\n}\n", + owners: &[(3, "Greet::bye", 3, 5), (4, "Greet::bye", 3, 5), (5, "Greet::bye", 3, 5)], + abstain: &[1, 2], + incidental: &[], + }, + Case { + label: "nested modules", + source: "mod a {\n mod b {\n fn f() {\n let x = 1;\n }\n }\n}\n", + owners: &[(3, "a::b::f", 3, 5), (4, "a::b::f", 3, 5), (5, "a::b::f", 3, 5)], + abstain: &[1, 2], + incidental: &[], + }, + Case { + label: "closure barrier", + source: "fn outer() {\n let f = |x| {\n x + 1\n };\n}\n", + owners: &[(1, "outer", 1, 5), (5, "outer", 1, 5)], + abstain: &[2, 3, 4], + incidental: &[], + }, + Case { + label: "nested closure abstains", + source: "fn factory() {\n || {\n |x| x + 1\n }\n}\n", + owners: &[(1, "factory", 1, 5), (5, "factory", 1, 5)], + abstain: &[2, 3, 4], + incidental: &[], + }, + Case { + label: "generic inherent impl", + source: "impl Stack {\n fn push(self) {\n let x = 1;\n }\n}\n", + owners: &[(2, "Stack::push", 2, 4), (3, "Stack::push", 2, 4), (4, "Stack::push", 2, 4)], + abstain: &[1], + incidental: &[], + }, + Case { + label: "extern body-less signatures", + source: "extern \"C\" {\n fn c_func(x: i32);\n fn d_func() -> i32;\n}\n", + owners: &[], + abstain: &[1, 2, 3], + incidental: &[], + }, + Case { + label: "macro_definition barrier + macro_invocation owned", + source: "macro_rules! make {\n () => { fn generated() {} };\n}\nfn real() {\n make!();\n}\n", + owners: &[(4, "real", 4, 6), (5, "real", 4, 6), (6, "real", 4, 6)], + abstain: &[1, 2], + incidental: &[], + }, + Case { + label: "module-level statement + comment", + source: "fn one() {\n}\nlet x = 1;\n// c\nfn two() {\n}\n", + owners: &[(1, "one", 1, 2), (2, "one", 1, 2), (5, "two", 5, 6), (6, "two", 5, 6)], + abstain: &[3, 4], + incidental: &[], + }, + Case { + label: "module-level blank separation", + source: "fn one() {\n}\n\nfn two() {\n}\n", + owners: &[(1, "one", 1, 2), (2, "one", 1, 2), (4, "two", 4, 5), (5, "two", 4, 5)], + abstain: &[], + incidental: &[3], + }, + Case { + label: "top-level match body", + source: "fn classify(n: i32) -> &'static str {\n match n {\n 0 => \"zero\",\n _ => \"other\",\n }\n}\n", + owners: &[ + (1, "classify", 1, 6), + (2, "classify", 1, 6), + (3, "classify", 1, 6), + (4, "classify", 1, 6), + (5, "classify", 1, 6), + (6, "classify", 1, 6), + ], + abstain: &[], + incidental: &[], + }, + Case { + label: "top-level generic fn", + source: "fn identity(v: T) -> T {\n v\n}\n", + owners: &[(1, "identity", 1, 3), (2, "identity", 1, 3), (3, "identity", 1, 3)], + abstain: &[], + incidental: &[], + }, + Case { + label: "local error degrades callable", + source: "fn broken() {\n x = (\n return x;\n}\n", + owners: &[], + abstain: &[1, 2, 3], + incidental: &[], + }, + Case { + label: "clean callable elsewhere in partial tree", + source: "fn good() {\n}\nfn bad() {\n x = (\n ;\n}\n", + owners: &[(1, "good", 1, 2), (2, "good", 1, 2)], + abstain: &[3, 4], + incidental: &[], + }, + Case { + label: "missing impl identity is full barrier", + source: "impl Foo for {\n fn m() {\n let x = 1;\n }\n}\n", + owners: &[], + abstain: &[1, 2, 3], + incidental: &[], + }, + Case { + label: "collapsed impl no type is barrier", + source: "impl {\n fn m() {\n let x = 1;\n }\n}\n", + owners: &[], + abstain: &[1, 2, 3], + incidental: &[], + }, + Case { + label: "malformed module no name is barrier", + source: "fn outer() {\n mod {\n fn inner() {\n let x = 1;\n }\n }\n}\n", + owners: &[], + abstain: &[1, 2, 3, 4, 5, 6], + incidental: &[], + }, + ]; + + let mut positives = 0u32; + let mut abstentions = 0u32; + for case in cases { + let (regions, errors) = parse(case.source); + for &(hit_line, name, start, end) in case.owners { + positives += 1; + let owner = rust_owner_for(®ions, &errors, hit_line); + assert!( + owner.is_some(), + "[{}] line {hit_line}: expected {name}@{start}-{end}, got abstain", + case.label + ); + let owner = owner.unwrap(); + assert_eq!( + owner.qualified_name(), + name, + "[{}] line {hit_line} name", + case.label + ); + assert_eq!( + owner.start_line, start, + "[{}] line {hit_line} start", + case.label + ); + assert_eq!(owner.end_line, end, "[{}] line {hit_line} end", case.label); + } + for &line in case.abstain { + abstentions += 1; + assert_abstain(®ions, &errors, line); + } + for &line in case.incidental { + assert_abstain(®ions, &errors, line); + } + } + // Binding quality floor; cannot silently regress. Separation/blank lines + // live in `incidental` and never count toward the abstention floor. + assert!( + positives >= 60, + "positive floor: only {positives} assertions" + ); + assert!( + abstentions >= 20, + "intentional-abstention floor: only {abstentions} assertions" + ); + } + + #[test] + fn manifest_gate_verifies_kinds_exist_and_fingerprint_is_pinned() { + let v: serde_json::Value = serde_json::from_str(tree_sitter_rust::NODE_TYPES).unwrap(); + let kinds: HashSet = v + .as_array() + .unwrap() + .iter() + .filter_map(|e| e.get("type").and_then(|t| t.as_str()).map(String::from)) + .collect(); + assert!(!kinds.is_empty(), "NODE_TYPES must declare node kinds"); + // Every executable/config/bodyless kind must exist in the grammar. + for k in RUST_EXECUTABLE_CALLABLES + .iter() + .chain(RUST_CONTAINER_KINDS) + .chain(RUST_BODILESS_DECLARATIONS) + { + assert!( + kinds.contains(*k), + "manifest kind {k} missing from NODE_TYPES" + ); + } + // Inventories must be disjoint (a node cannot be two categories). + let mut all: Vec<&str> = Vec::new(); + all.extend(RUST_EXECUTABLE_CALLABLES); + all.extend(RUST_CONTAINER_KINDS); + all.extend(RUST_BODILESS_DECLARATIONS); + let uniq: HashSet<&str> = all.iter().copied().collect(); + assert_eq!( + uniq.len(), + all.len(), + "manifest inventories must be disjoint" + ); + // Fingerprint is pinned so grammar metadata changes fail here. + assert_eq!( + fnv1a(tree_sitter_rust::NODE_TYPES.as_bytes()), + RUST_NODE_TYPES_FINGERPRINT, + "tree-sitter-rust NODE_TYPES changed; re-audit the manifest" + ); + } +} diff --git a/tests/intent_first_cli.rs b/tests/intent_first_cli.rs index 663237b..b7f24f6 100644 --- a/tests/intent_first_cli.rs +++ b/tests/intent_first_cli.rs @@ -1369,6 +1369,112 @@ fn discover_malformed_go_with_python_owners_suppresses_go_call_appendix() { stdout.contains("structural lexical ownership candidates"), "{stdout}" ); +} + +#[test] +fn discover_text_or_rust_attributes_owners_without_go_call_appendix() { + // US-067 phase 2: Rust files now carry owner attribution. The owner rollup + // is emitted, the Go-only mechanical-call appendix is NOT (no Go call- + // analysis attempt), and the non-Go honesty caveat applies. + let dir = temp_repo("discover_text_or_rust_owner"); + fs::write( + dir.join("app.rs"), + "fn apply() {\n}\nfn set() {\n apply();\n}\nfn flush() {\n set();\n}\n", + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", + "apply,set,flush", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + // Rust owner rollup is rendered with exact owner ranges. + assert!(stdout.contains("owners (#N=Nth query term"), "{stdout}"); + assert!(stdout.contains("apply:1-2[#1]"), "{stdout}"); + assert!(stdout.contains("set:3-5[#1,#2]"), "{stdout}"); + assert!(stdout.contains("flush:6-8[#2,#3]"), "{stdout}"); + // No Go call appendix is emitted for a non-Go-only query. + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + !stdout.contains("[recv=same package-qualified receiver type"), + "{stdout}" + ); + assert!( + !stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + // Non-Go honesty caveat present, and it must not imply call analysis ran. + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_mixed_go_and_rust_attributes_both_and_go_appendix() { + // Phase 2 capability honesty: a mixed Go + Rust query retains Rust owner + // attribution AND the Go-only mechanical-call appendix (Go call analysis + // ran), plus the non-Go honesty caveat for the Rust evidence. + let dir = temp_repo("discover_mixed_go_rust_owner"); + fs::write( + dir.join("app.rs"), + "fn apply() {\n}\nfn set() {\n apply();\n}\n", + ) + .unwrap(); + fs::write( + dir.join("db.go"), + "package db\ntype DB struct{}\nfunc (d *DB) Apply() { /* apply body */ }\nfunc (d *DB) Set() { /* set body */ d.Apply() }\n", + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", + "apply,set", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + // Rust owner evidence is retained. + assert!(stdout.contains("[owner apply@1-2]"), "{stdout}"); + // Go mechanical-call appendix is present (Go call analysis ran). + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + // Non-Go honesty caveat present for the Rust owner evidence. + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); let _ = fs::remove_dir_all(&dir); } From 612bf60b10764177ffac10aeba369940546a5b01 Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 01:18:33 +0700 Subject: [PATCH 13/26] feat(js): JavaScript owner attribution (US-067 phase 3) JS/JSX/MJS/CJS files now carry structural owner attribution via a tree-sitter-javascript adapter, owner-only (no call edges in phase 3B). - Dot-joined qualified names (outer.inner, A.foo, A.#priv). - Direct simple-variable binding wins over an explicit internal name. - Class fields/methods/get-set/static/private map to Class.name. - Safety barriers (never omission, never guessed): object-literal callables, anonymous classes/IIFEs, member/prototype assignments, computed names, class_static_block. - Named IIFEs use their own name; anonymous -> barrier. - Manifest gate pins NODE_TYPES fingerprint; quality matrix requires >=30 positive + >=10 intentional abstentions. - Non-Go honesty caveat; no Go mechanical-call appendix. --- src/evidence/owner_links.rs | 23 +- src/evidence/owners/js_ts.rs | 997 +++++++++++++++++++++++++++++++++++ src/evidence/owners/mod.rs | 1 + tests/intent_first_cli.rs | 97 ++++ 4 files changed, 1117 insertions(+), 1 deletion(-) create mode 100644 src/evidence/owners/js_ts.rs diff --git a/src/evidence/owner_links.rs b/src/evidence/owner_links.rs index 527cdb9..639f81b 100644 --- a/src/evidence/owner_links.rs +++ b/src/evidence/owner_links.rs @@ -175,7 +175,8 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own 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); - if is_go || is_python || is_rust { + let is_javascript = detected == crate::types::FileType::Code(Lang::JavaScript); + if is_go || is_python || is_rust || is_javascript { by_path .entry(input.path.to_path_buf()) .or_default() @@ -230,6 +231,26 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own } continue; } + if detected == crate::types::FileType::Code(Lang::JavaScript) { + // JavaScript is owner-only: no call edges are inferred in phase 3B. + let Some((regions, errors)) = + crate::evidence::owners::js_ts::js_regions(path, &content) + else { + continue; + }; + for input in path_inputs { + if let Some(owner) = + crate::evidence::owners::js_ts::js_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. diff --git a/src/evidence/owners/js_ts.rs b/src/evidence/owners/js_ts.rs new file mode 100644 index 0000000..bdd89d5 --- /dev/null +++ b/src/evidence/owners/js_ts.rs @@ -0,0 +1,997 @@ +//! JavaScript owner-region extraction (US-067 slice 3B). +//! +//! 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). +//! * 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) 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. + +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). +/// +/// TypeScript-only categories (type-only non-callables and body-less callable +/// declarations) are added by the slice-3C manifest. +#[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"]; + +/// FNV-1a-64 fingerprint of the bundled `tree-sitter-javascript` `NODE_TYPES` +/// JSON (tree-sitter-javascript 0.23.1). Pinned so any grammar metadata change +/// fails the manifest gate and forces a re-audit of the inventories above. +#[cfg(test)] +const JS_NODE_TYPES_FINGERPRINT: u64 = 0x372f_ecd5_b5f8_67c2; + +/// 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 JavaScript 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 js_regions( + path: &Path, + content: &str, +) -> Option<(Vec, Vec)> { + let language = outline_language(Lang::JavaScript)?; + 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)) +} + +/// Attribute a JavaScript hit line to a named owner, honoring local errors. +pub(crate) fn js_owner_for<'a>( + regions: &'a [OwnerRegion], + errors: &[ErrorRange], + line: u32, +) -> Option<&'a OwnerAnchor> { + attribute_line(regions, errors, line) +} + +/// Walk a JavaScript tree, emitting `Named` regions for supported callables and +/// `AnonymousBarrier` regions for every other callable. `prefixes` carries +/// `.`-suffixed path segments (classes, binding-backed callables, nested +/// functions) so nested callables get their full qualified name. +/// +/// `sticky` is true inside an invalid naming container (an anonymous class or an +/// unsupported object method/property callable) 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, + prefixes: &mut Vec, + errors: &[ErrorRange], + regions: &mut Vec, + sticky: bool, +) { + match node.kind() { + "function_declaration" | "generator_function_declaration" => { + walk_declaration(node, bytes, path, prefixes, errors, regions, sticky); + } + "function_expression" | "generator_function" => { + walk_expression(node, bytes, path, prefixes, errors, regions, sticky); + } + "arrow_function" => walk_arrow(node, bytes, path, prefixes, errors, regions, sticky), + "method_definition" => walk_method(node, bytes, path, prefixes, errors, regions, sticky), + "class_declaration" => { + // A named class is a valid `.`-prefix container; it is not itself a + // callable region (a hit on the class header line abstains). + 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 { + recurse(node, bytes, path, 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, 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, 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, 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, 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, + 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, 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, prefixes, errors, regions, false); + return; + }; + let name = name.trim().to_string(); + let qualified = join_prefixes(prefixes, &name); + emit_named(node, path, &name, &qualified, errors, regions); + prefixes.push(format!("{name}.")); + recurse(node, bytes, path, 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, + 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, 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, 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, &binding, &qualified, errors, regions); + prefixes.push(format!("{binding}.")); + recurse(node, bytes, path, 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, &field, &qualified, errors, regions); + prefixes.push(format!("{field}.")); + recurse(node, bytes, path, 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, &own, &qualified, errors, regions); + prefixes.push(format!("{own}.")); + recurse(node, bytes, path, 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, + 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, + 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, 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, prefixes, errors, regions, true); + return; + } + if let Some(binding) = variable_binding_name(node, bytes) { + let qualified = join_prefixes(prefixes, &binding); + emit_named(node, path, &binding, &qualified, errors, regions); + prefixes.push(format!("{binding}.")); + recurse(node, bytes, path, 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, &field, &qualified, errors, regions); + prefixes.push(format!("{field}.")); + recurse(node, bytes, path, 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, + 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, + 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, 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, 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, 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, prefixes, errors, regions, true); + return; + }; + let qualified = join_prefixes(prefixes, &name); + emit_named(node, path, &name, &qualified, errors, regions); + prefixes.push(format!("{name}.")); + recurse(node, bytes, path, prefixes, errors, regions, false); + prefixes.pop(); +} + +/// Whether a class-body member's enclosing class has a structural name. +/// `node` is a `method_definition` or `field_definition` whose parent is a +/// `class_body`; walk up to the `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() +} + +/// 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 `field_definition` 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 parent.kind() != "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 = parent.child_by_field_name("property")?; + 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 `field_definition` 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 parent.kind() != "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) = parent.child_by_field_name("property") 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. +fn emit_named( + node: Node<'_>, + path: &Path, + 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::JavaScript, + 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, + 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, 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.js") + } + + fn parse(src: &str) -> (Vec, Vec) { + js_regions(&path(), src).expect("should parse") + } + + fn assert_owner_exact( + regions: &[OwnerRegion], + errors: &[ErrorRange], + hit_line: u32, + name: &str, + start: u32, + end: u32, + ) { + let owner = js_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!( + js_owner_for(regions, errors, line).is_none(), + "line {line} should abstain" + ); + } + + #[test] + fn manifest_gate_verifies_kinds_exist_and_fingerprint_is_pinned() { + let v: serde_json::Value = + serde_json::from_str(tree_sitter_javascript::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()); + + 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); + for k in &all { + assert!( + kinds.contains(*k), + "manifest kind {k} missing from NODE_TYPES" + ); + } + let uniq: HashSet<&str> = all.iter().copied().collect(); + assert_eq!( + uniq.len(), + all.len(), + "manifest inventories must be disjoint" + ); + + 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 all_six_executable_callable_kinds_are_disposed() { + // Every kind in JS_EXECUTABLE_CALLABLES must be exercised as Named (or + // Barrier) so a grammar reclassification cannot silently drop coverage. + let (r, e) = parse( + "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 quality_matrix() { + struct Case { + src: &'static str, + owners: &'static [(u32, &'static str, u32, u32)], + abstain: &'static [u32], + } + let cases: &[Case] = &[ + Case { + src: "function alpha() {\n return 1;\n}\n", + owners: &[(1, "alpha", 1, 3), (2, "alpha", 1, 3)], + abstain: &[], + }, + Case { + src: "function* gen() {\n yield 1;\n}\n", + owners: &[(1, "gen", 1, 3), (2, "gen", 1, 3)], + abstain: &[], + }, + Case { + 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 { + 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 { + 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 { + 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 { + src: "const f = () => {\n return 1;\n};\n", + owners: &[(1, "f", 1, 3), (2, "f", 1, 3)], + abstain: &[], + }, + Case { + src: "const g = function() {\n return 2;\n};\n", + owners: &[(1, "g", 1, 3), (2, "g", 1, 3)], + abstain: &[], + }, + Case { + src: "const h = function* () {\n yield 1;\n};\n", + owners: &[(1, "h", 1, 3), (2, "h", 1, 3)], + abstain: &[], + }, + Case { + src: "const f = function named() {\n return 1;\n};\n", + owners: &[(1, "f", 1, 3), (2, "f", 1, 3)], + abstain: &[], + }, + Case { + 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 { + 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 { + src: "(function named() {\n return 1;\n})();\n", + owners: &[(1, "named", 1, 3), (2, "named", 1, 3)], + abstain: &[], + }, + Case { + src: "(function* gen() {\n yield 1;\n})();\n", + owners: &[(1, "gen", 1, 3), (2, "gen", 1, 3)], + abstain: &[], + }, + Case { + 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 { + 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 { + 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: &[], + }, + // Intentional abstentions (safety barriers / unsupported phase-1 contexts). + Case { + src: "const o = {\n foo() {\n return 1;\n },\n};\n", + owners: &[], + abstain: &[2, 3], + }, + Case { + src: "const o = {\n bar: function() {\n return 1;\n },\n};\n", + owners: &[], + abstain: &[2, 3], + }, + Case { + src: "const o = {\n bar: function named() {\n return 1;\n },\n};\n", + owners: &[(2, "named", 2, 4), (3, "named", 2, 4)], + abstain: &[], + }, + Case { + src: "const A = class {\n foo() {\n return 1;\n }\n};\n", + owners: &[], + abstain: &[2, 3], + }, + Case { + src: "(function() {\n let x = 1;\n})();\n", + owners: &[], + abstain: &[1, 2], + }, + Case { + src: "Foo.prototype.bar = function() {\n return 1;\n};\n", + owners: &[], + abstain: &[1, 2], + }, + Case { + src: "button.onClick = () => {\n handle();\n};\n", + owners: &[], + abstain: &[1, 2], + }, + Case { + src: "class A {\n ['foo']() {\n return 1;\n }\n}\n", + owners: &[], + abstain: &[2, 3], + }, + Case { + src: "class A {\n static {\n let x = 1;\n }\n}\n", + owners: &[], + abstain: &[2, 3], + }, + ]; + + let mut positives = 0usize; + let mut abstentions = 0usize; + for c in cases { + let (r, e) = parse(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; + } + } + assert!( + positives >= 30, + "need >=30 positive attributions, got {positives}" + ); + assert!( + abstentions >= 10, + "need >=10 intentional abstentions, got {abstentions}" + ); + } + + #[test] + fn 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("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); + + // Direct class-field callable with a computed/unreadable field name: + // unsupported direct field context recurses sticky. + let (r, e) = parse( + "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); + + // Direct declarator with a destructuring/patter name: unsupported + // direct binding context recurses sticky. + let (r, e) = parse("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() { + // A non-sticky anonymous callback (IIFE / member-value arrow) preserves + // the outer prefix, so an independently named nested declaration stays + // eligible. + let (r, e) = parse( + "const xs = [1].map(() => {\n function inner() { return 1; }\n return inner();\n});\n", + ); + assert_owner_exact(&r, &e, 2, "inner", 2, 2); + // Line 3 is inside the anonymous arrow (outside `inner`'s span): abstain. + assert_abstain(&r, &e, 3); + } + + #[test] + fn object_get_set_are_barriers_but_named_container_allows_binding() { + let (r, e) = parse("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() { + // A malformed statement inside a callable overlaps its span, degrading + // the WHOLE named region to a barrier (every line abstains). A clean + // adjacent function (no error overlap) remains eligible. + let (r, e) = parse( + "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::JavaScript, + display_name: "outer.inner".into(), + }; + assert_eq!(a.qualified_name(), "outer.inner"); + } +} diff --git a/src/evidence/owners/mod.rs b/src/evidence/owners/mod.rs index 45d2f19..c6c54df 100644 --- a/src/evidence/owners/mod.rs +++ b/src/evidence/owners/mod.rs @@ -13,6 +13,7 @@ //! (`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 js_ts; pub(crate) mod python; pub(crate) mod rust; diff --git a/tests/intent_first_cli.rs b/tests/intent_first_cli.rs index b7f24f6..996cbaa 100644 --- a/tests/intent_first_cli.rs +++ b/tests/intent_first_cli.rs @@ -1318,6 +1318,103 @@ fn discover_text_or_python_attributes_owners_without_go_call_appendix() { let _ = fs::remove_dir_all(&dir); } +#[test] +fn discover_text_or_javascript_attributes_owners_without_go_call_appendix() { + // US-067 phase 3: JavaScript files now carry owner attribution. The owner + // rollup is emitted, the Go-only mechanical-call appendix is NOT (no Go + // call-analysis attempt), and the non-Go honesty caveat applies. + let dir = temp_repo("discover_text_or_javascript_owner"); + fs::write( + dir.join("app.js"), + "function apply() {\n return 1;\n}\nfunction set() {\n apply();\n}\nfunction flush() {\n set();\n}\n", + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", + "apply,set,flush", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + // JavaScript owner rollup is rendered with dot-less top-level names. + assert!(stdout.contains("owners (#N=Nth query term"), "{stdout}"); + assert!(stdout.contains("apply:1-3[#1]"), "{stdout}"); + assert!(stdout.contains("set:4-6[#1,#2]"), "{stdout}"); + assert!(stdout.contains("flush:7-9[#2,#3]"), "{stdout}"); + // No Go call appendix is emitted for a non-Go-only query. + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + !stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + // Non-Go honesty caveat present, and it must not imply call analysis ran. + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_jsx_routes_through_javascript_grammar_with_callback_barrier() { + // A real `.jsx` file must route through the JavaScript grammar (JSX + // elements parse), the named component gets an exact owner, and the inline + // JSX callback (an anonymous arrow) must NOT fall through as a bogus owner. + // The non-Go honesty caveat holds and no Go call appendix is emitted. + let dir = temp_repo("discover_jsx_owner_barrier"); + fs::write( + dir.join("app.jsx"), + "function App() {\n return ;\n}\nfunction util() {\n return 1;\n}\n", + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", "App,util", "--match", "any", "--as", "text", "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + // Named component routes through JS grammar with an exact owner. + assert!(stdout.contains("app.jsx:1 [owner App@1-3]"), "{stdout}"); + assert!(stdout.contains("app.jsx:4 [owner util@4-6]"), "{stdout}"); + // The inline JSX callback line is an anonymous barrier: it does NOT carry + // its own `[owner ...]` and does not fall through to a bogus name. + assert!(!stdout.contains("app.jsx:2 [owner"), "{stdout}"); + // Non-Go honesty caveat present; no Go mechanical-call appendix. + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + !stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + #[test] fn discover_malformed_go_with_python_owners_suppresses_go_call_appendix() { // Regression for the gate bug: a malformed Go input must not leave From 7032310d2697ef307c1987608e09931672d8fb3a Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 01:39:55 +0700 Subject: [PATCH 14/26] feat(ts): TypeScript/TSX owner attribution (US-067 phase 3C) Generalize the shared JS adapter at the language seam: grammar selected by detected Lang::{JavaScript,TypeScript,Tsx}, OwnerAnchor.language set to the actual language. Preserves all JS/JSX behavior and tests. TS/TSX wired into the same owner-only pipeline (no call edges). - Body-less callable declarations barrier over exact spans: abstract_method_ signature, method_signature, function_signature, call_signature, construct_signature. Concrete overload impl stays Named on its body node. - Type-only non-callables transparent (no barrier/no name): property_signature, index_signature, function_type, constructor_type. - Valid .-prefix containers: named/abstract class and TypeScript namespace/ internal_module/module (readable identifier/nested-identifier segments only; string/computed module names sticky barrier). - public_field_definition is the TS class-field binding node (simple/private direct value => A.x; computed/unreadable/anonymous-class sticky barrier). - ambient_declaration, decorators, export/default, interfaces, type-alias, enums are transparent wrappers/traversal containers, never name prefixes. - Invalid naming context sticky + local ERROR policy identical to JS. Anti-drift: separate TypeScript and TSX NODE_TYPES inventories + pinned fingerprints (JS kept separate); every TS executable/body-less callable kind has exactly one deliberate disposition with fixture coverage. Tests: combined family matrix >=60 exact positive (name,start,end) checks and >=20 intentional abstentions; TS fixtures for namespace nesting, abstract+ concrete methods, overload signatures + impl, ambient function, call/ construct/method signatures, transparent function/constructor types inside an owner, public fields, computed/destructured stickiness, local ERROR, and all TS callable kinds. CLI integration for real .ts and .tsx; .mts/.cts routing smoke via existing Lang mapping. --- src/evidence/owner_links.rs | 18 +- src/evidence/owners/js_ts.rs | 874 +++++++++++++++++++++++++++++------ tests/intent_first_cli.rs | 125 +++++ 3 files changed, 863 insertions(+), 154 deletions(-) diff --git a/src/evidence/owner_links.rs b/src/evidence/owner_links.rs index 639f81b..af860d6 100644 --- a/src/evidence/owner_links.rs +++ b/src/evidence/owner_links.rs @@ -175,8 +175,11 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own 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_javascript = detected == crate::types::FileType::Code(Lang::JavaScript); - if is_go || is_python || is_rust || is_javascript { + let is_js_ts_family = matches!( + detected, + crate::types::FileType::Code(Lang::JavaScript | Lang::TypeScript | Lang::Tsx) + ); + if is_go || is_python || is_rust || is_js_ts_family { by_path .entry(input.path.to_path_buf()) .or_default() @@ -231,16 +234,19 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own } continue; } - if detected == crate::types::FileType::Code(Lang::JavaScript) { - // JavaScript is owner-only: no call edges are inferred in phase 3B. + 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::js_regions(path, &content) + 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::js_owner_for(®ions, &errors, input.line) + crate::evidence::owners::js_ts::owner_for(®ions, &errors, input.line) { hits.push(OwnedTextHit { path: path.clone(), diff --git a/src/evidence/owners/js_ts.rs b/src/evidence/owners/js_ts.rs index bdd89d5..3932f2c 100644 --- a/src/evidence/owners/js_ts.rs +++ b/src/evidence/owners/js_ts.rs @@ -1,4 +1,4 @@ -//! JavaScript owner-region extraction (US-067 slice 3B). +//! JavaScript/TypeScript/TSX owner-region extraction (US-067 slices 3B/3C). //! //! Supported named owners (`.`-qualified, per spec): //! * `function_declaration` / `generator_function_declaration` -> `name` @@ -10,7 +10,8 @@ //! - `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). +//! `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. //! @@ -21,12 +22,27 @@ //! and `class_static_block` (a non-callable safety fallthrough guard). //! //! Invalid naming containers (anonymous class; unsupported object method/ -//! property callable) 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. +//! 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; @@ -47,9 +63,6 @@ use crate::types::Lang; /// * (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). -/// -/// TypeScript-only categories (type-only non-callables and body-less callable -/// declarations) are added by the slice-3C manifest. #[cfg(test)] const JS_EXECUTABLE_CALLABLES: &[&str] = &[ "function_declaration", @@ -75,11 +88,80 @@ const JS_BINDING_CONTAINER_KINDS: &[&str] = &[ #[cfg(test)] const JS_NON_CALLABLE_SAFETY_BARRIERS: &[&str] = &["class_static_block"]; -/// FNV-1a-64 fingerprint of the bundled `tree-sitter-javascript` `NODE_TYPES` -/// JSON (tree-sitter-javascript 0.23.1). Pinned so any grammar metadata change -/// fails the manifest gate and forces a re-audit of the inventories above. +/// 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)] @@ -92,14 +174,16 @@ fn fnv1a(bytes: &[u8]) -> u64 { hash } -/// Parse a JavaScript 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 js_regions( +/// 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::JavaScript)?; + let language = outline_language(lang)?; let mut parser = tree_sitter::Parser::new(); if parser.set_language(&language).is_err() { return None; @@ -116,6 +200,7 @@ pub(crate) fn js_regions( tree.root_node(), bytes, path, + lang, &mut prefixes, &errors, &mut regions, @@ -124,8 +209,8 @@ pub(crate) fn js_regions( Some((regions, errors)) } -/// Attribute a JavaScript hit line to a named owner, honoring local errors. -pub(crate) fn js_owner_for<'a>( +/// 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, @@ -133,19 +218,22 @@ pub(crate) fn js_owner_for<'a>( attribute_line(regions, errors, line) } -/// Walk a JavaScript tree, emitting `Named` regions for supported callables and +/// 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, binding-backed callables, nested -/// functions) so nested callables get their full qualified name. +/// `.`-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 or an -/// unsupported object method/property callable) 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. +/// `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, @@ -153,26 +241,41 @@ fn walk( ) { match node.kind() { "function_declaration" | "generator_function_declaration" => { - walk_declaration(node, bytes, path, prefixes, errors, regions, sticky); + walk_declaration(node, bytes, path, lang, prefixes, errors, regions, sticky); } "function_expression" | "generator_function" => { - walk_expression(node, bytes, path, prefixes, errors, regions, sticky); + walk_expression(node, bytes, path, lang, prefixes, errors, regions, sticky); } - "arrow_function" => walk_arrow(node, bytes, path, prefixes, errors, regions, sticky), - "method_definition" => walk_method(node, bytes, path, prefixes, errors, regions, sticky), - "class_declaration" => { - // A named class is a valid `.`-prefix container; it is not itself a - // callable region (a hit on the class header line abstains). - 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 { - recurse(node, bytes, path, 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 @@ -182,14 +285,14 @@ fn walk( .and_then(|n| n.utf8_text(bytes).ok()) { prefixes.push(format!("{}.", name.trim())); - recurse(node, bytes, path, prefixes, errors, regions, false); + 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, prefixes, errors, regions, true); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); } } "class_static_block" => { @@ -200,12 +303,19 @@ fn walk( 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, sticky); + 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, prefixes, errors, regions, sticky), + _ => recurse(node, bytes, path, lang, prefixes, errors, regions, sticky), } } @@ -216,6 +326,7 @@ fn walk_declaration( node: Node<'_>, bytes: &[u8], path: &Path, + lang: Lang, prefixes: &mut Vec, errors: &[ErrorRange], regions: &mut Vec, @@ -229,7 +340,7 @@ fn walk_declaration( start_line, end_line, }); - recurse(node, bytes, path, prefixes, errors, regions, true); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); return; } let Some(name) = node @@ -240,14 +351,14 @@ fn walk_declaration( start_line, end_line, }); - recurse(node, bytes, path, prefixes, errors, regions, false); + 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, &name, &qualified, errors, regions); + emit_named(node, path, lang, &name, &qualified, errors, regions); prefixes.push(format!("{name}.")); - recurse(node, bytes, path, prefixes, errors, regions, false); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); prefixes.pop(); } @@ -259,6 +370,7 @@ fn walk_expression( node: Node<'_>, bytes: &[u8], path: &Path, + lang: Lang, prefixes: &mut Vec, errors: &[ErrorRange], regions: &mut Vec, @@ -271,7 +383,7 @@ fn walk_expression( start_line, end_line, }); - recurse(node, bytes, path, prefixes, errors, regions, true); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); return; } // Unsupported direct binding context (computed field, destructuring/ @@ -282,24 +394,24 @@ fn walk_expression( start_line, end_line, }); - recurse(node, bytes, path, prefixes, errors, regions, true); + 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, &binding, &qualified, errors, regions); + emit_named(node, path, lang, &binding, &qualified, errors, regions); prefixes.push(format!("{binding}.")); - recurse(node, bytes, path, prefixes, errors, regions, false); + 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, &field, &qualified, errors, regions); + emit_named(node, path, lang, &field, &qualified, errors, regions); prefixes.push(format!("{field}.")); - recurse(node, bytes, path, prefixes, errors, regions, false); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); prefixes.pop(); return; } @@ -310,9 +422,9 @@ fn walk_expression( { let own = own.trim().to_string(); let qualified = join_prefixes(prefixes, &own); - emit_named(node, path, &own, &qualified, errors, regions); + emit_named(node, path, lang, &own, &qualified, errors, regions); prefixes.push(format!("{own}.")); - recurse(node, bytes, path, prefixes, errors, regions, false); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); prefixes.pop(); return; } @@ -328,6 +440,7 @@ fn walk_expression( node, bytes, path, + lang, prefixes, errors, regions, @@ -342,6 +455,7 @@ fn walk_arrow( node: Node<'_>, bytes: &[u8], path: &Path, + lang: Lang, prefixes: &mut Vec, errors: &[ErrorRange], regions: &mut Vec, @@ -354,7 +468,7 @@ fn walk_arrow( start_line, end_line, }); - recurse(node, bytes, path, prefixes, errors, regions, true); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); return; } // Unsupported direct binding context (computed field, destructuring/ @@ -364,22 +478,22 @@ fn walk_arrow( start_line, end_line, }); - recurse(node, bytes, path, prefixes, errors, regions, true); + 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, &binding, &qualified, errors, regions); + emit_named(node, path, lang, &binding, &qualified, errors, regions); prefixes.push(format!("{binding}.")); - recurse(node, bytes, path, prefixes, errors, regions, false); + 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, &field, &qualified, errors, regions); + emit_named(node, path, lang, &field, &qualified, errors, regions); prefixes.push(format!("{field}.")); - recurse(node, bytes, path, prefixes, errors, regions, false); + recurse(node, bytes, path, lang, prefixes, errors, regions, false); prefixes.pop(); return; } @@ -392,6 +506,7 @@ fn walk_arrow( node, bytes, path, + lang, prefixes, errors, regions, @@ -406,6 +521,7 @@ fn walk_method( node: Node<'_>, bytes: &[u8], path: &Path, + lang: Lang, prefixes: &mut Vec, errors: &[ErrorRange], regions: &mut Vec, @@ -418,7 +534,7 @@ fn walk_method( start_line, end_line, }); - recurse(node, bytes, path, prefixes, errors, regions, true); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); return; } let parent_kind = node.parent().map(|p| p.kind().to_string()); @@ -429,7 +545,7 @@ fn walk_method( start_line, end_line, }); - recurse(node, bytes, path, prefixes, errors, regions, true); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); return; } if !in_named_class(node) { @@ -438,7 +554,7 @@ fn walk_method( start_line, end_line, }); - recurse(node, bytes, path, prefixes, errors, regions, true); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); return; } let Some(name) = simple_member_name(node, bytes) else { @@ -449,19 +565,116 @@ fn walk_method( start_line, end_line, }); - recurse(node, bytes, path, prefixes, errors, regions, true); + recurse(node, bytes, path, lang, prefixes, errors, regions, true); return; }; let qualified = join_prefixes(prefixes, &name); - emit_named(node, path, &name, &qualified, errors, regions); + emit_named(node, path, lang, &name, &qualified, errors, regions); prefixes.push(format!("{name}.")); - recurse(node, bytes, path, prefixes, errors, regions, false); + 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` or `field_definition` whose parent is a -/// `class_body`; walk up to the `class_declaration`/`class` and check its 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; @@ -475,6 +688,17 @@ fn in_named_class(node: Node<'_>) -> bool { 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. @@ -493,12 +717,16 @@ fn variable_binding_name(node: Node<'_>, bytes: &[u8]) -> Option { name.utf8_text(bytes).ok().map(|s| s.trim().to_string()) } -/// Whether `node` is the direct `value` of a `field_definition` 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). +/// 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 parent.kind() != "field_definition" { + if !matches!( + parent.kind(), + "field_definition" | "public_field_definition" + ) { return None; } if parent.child_by_field_name("value")?.id() != node.id() { @@ -507,7 +735,7 @@ fn field_binding_name(node: Node<'_>, bytes: &[u8]) -> Option { if !in_named_class(parent) { return None; } - let field = parent.child_by_field_name("property")?; + let field = field_name_node(parent)?; if !matches!( field.kind(), "property_identifier" | "private_property_identifier" @@ -517,15 +745,19 @@ fn field_binding_name(node: Node<'_>, bytes: &[u8]) -> Option { field.utf8_text(bytes).ok().map(|s| s.trim().to_string()) } -/// Whether `node` is the direct `value` of a `field_definition` 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. +/// 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 parent.kind() != "field_definition" { + if !matches!( + parent.kind(), + "field_definition" | "public_field_definition" + ) { return false; } let Some(value) = parent.child_by_field_name("value") else { @@ -534,7 +766,7 @@ fn unsupported_field_direct_context(node: Node<'_>) -> bool { if value.id() != node.id() { return false; } - let Some(field) = parent.child_by_field_name("property") else { + let Some(field) = field_name_node(parent) else { return false; }; !matches!( @@ -593,10 +825,11 @@ fn join_prefixes(prefixes: &[String], name: &str) -> String { /// 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. +/// 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], @@ -610,7 +843,7 @@ fn emit_named( 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::JavaScript, + language: lang, display_name: qualified.to_string(), }; let region = OwnerRegion::Named(anchor); @@ -623,6 +856,7 @@ fn recurse( node: Node<'_>, bytes: &[u8], path: &Path, + lang: Lang, prefixes: &mut Vec, errors: &[ErrorRange], regions: &mut Vec, @@ -630,7 +864,7 @@ fn recurse( ) { let mut cursor = node.walk(); for child in node.named_children(&mut cursor) { - walk(child, bytes, path, prefixes, errors, regions, sticky); + walk(child, bytes, path, lang, prefixes, errors, regions, sticky); } } @@ -641,11 +875,11 @@ mod tests { use std::path::PathBuf; fn path() -> PathBuf { - PathBuf::from("tests/fixtures/x.js") + PathBuf::from("tests/fixtures/x.ts") } - fn parse(src: &str) -> (Vec, Vec) { - js_regions(&path(), src).expect("should parse") + fn parse(lang: Lang, src: &str) -> (Vec, Vec) { + regions_for(lang, &path(), src).expect("should parse") } fn assert_owner_exact( @@ -656,7 +890,7 @@ mod tests { start: u32, end: u32, ) { - let owner = js_owner_for(regions, errors, hit_line) + 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"); @@ -665,52 +899,156 @@ mod tests { fn assert_abstain(regions: &[OwnerRegion], errors: &[ErrorRange], line: u32) { assert!( - js_owner_for(regions, errors, line).is_none(), + owner_for(regions, errors, line).is_none(), "line {line} should abstain" ); } - #[test] - fn manifest_gate_verifies_kinds_exist_and_fingerprint_is_pinned() { - let v: serde_json::Value = - serde_json::from_str(tree_sitter_javascript::NODE_TYPES).unwrap(); - let kinds: HashSet = v - .as_array() - .unwrap() + /// Number of `AnonymousBarrier` regions whose span covers `line`. + fn barrier_regions_at(regions: &[OwnerRegion], line: u32) -> usize { + regions .iter() - .filter_map(|e| e.get("type").and_then(|t| t.as_str()).map(String::from)) - .collect(); - assert!(!kinds.is_empty()); + .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); - for k in &all { + 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" ); - - 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 all_six_executable_callable_kinds_are_disposed() { - // Every kind in JS_EXECUTABLE_CALLABLES must be exercised as Named (or - // Barrier) so a grammar reclassification cannot silently drop coverage. + 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\ @@ -727,24 +1065,118 @@ mod tests { } #[test] - fn quality_matrix() { + 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), @@ -755,6 +1187,7 @@ mod tests { 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), @@ -765,11 +1198,13 @@ mod tests { 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), @@ -779,46 +1214,55 @@ mod tests { 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), @@ -829,15 +1273,13 @@ mod tests { 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), - ], + 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), @@ -847,58 +1289,129 @@ mod tests { ], abstain: &[], }, - // Intentional abstentions (safety barriers / unsupported phase-1 contexts). 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 { - src: "const o = {\n bar: function named() {\n return 1;\n },\n};\n", - owners: &[(2, "named", 2, 4), (3, "named", 2, 4)], - abstain: &[], - }, - 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.src); + 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; @@ -908,38 +1421,105 @@ mod tests { abstentions += 1; } } + // Combined JS+TS family gate (substantial, not padded). assert!( - positives >= 30, - "need >=30 positive attributions, got {positives}" + positives >= 60, + "need >=60 combined positive owner checks, got {positives}" ); assert!( - abstentions >= 10, - "need >=10 intentional abstentions, got {abstentions}" + abstentions >= 20, + "need >=20 combined intentional abstention lines, got {abstentions}" ); } #[test] - fn invalid_naming_contexts_are_sticky_for_nested_declarations() { + 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("class A {\n ['foo']() {\n function inner() { return 1; }\n }\n}\n"); + 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); - // Direct class-field callable with a computed/unreadable field name: - // unsupported direct field context recurses sticky. 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); - // Direct declarator with a destructuring/patter name: unsupported - // direct binding context recurses sticky. - let (r, e) = parse("const { a } = function() {\n function inner() { return 1; }\n};\n"); + 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); @@ -947,29 +1527,27 @@ mod tests { #[test] fn ordinary_anonymous_callback_keeps_nested_declarations_eligible() { - // A non-sticky anonymous callback (IIFE / member-value arrow) preserves - // the outer prefix, so an independently named nested declaration stays - // 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); - // Line 3 is inside the anonymous arrow (outside `inner`'s span): abstain. assert_abstain(&r, &e, 3); } #[test] fn object_get_set_are_barriers_but_named_container_allows_binding() { - let (r, e) = parse("const o = {\n get x() { return 1; }\n};\n"); + 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() { - // A malformed statement inside a callable overlaps its span, degrading - // the WHOLE named region to a barrier (every line abstains). A clean - // adjacent function (no error overlap) remains 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); @@ -989,7 +1567,7 @@ mod tests { package_dir: PathBuf::from("pkg"), start_line: 1, end_line: 1, - language: crate::types::Lang::JavaScript, + language: crate::types::Lang::TypeScript, display_name: "outer.inner".into(), }; assert_eq!(a.qualified_name(), "outer.inner"); diff --git a/tests/intent_first_cli.rs b/tests/intent_first_cli.rs index 996cbaa..ae0747d 100644 --- a/tests/intent_first_cli.rs +++ b/tests/intent_first_cli.rs @@ -1415,6 +1415,131 @@ fn discover_jsx_routes_through_javascript_grammar_with_callback_barrier() { let _ = fs::remove_dir_all(&dir); } +#[test] +fn discover_typescript_attributes_owners_without_go_call_appendix() { + // A real `.ts` file routes through the TypeScript grammar: namespace + // nesting yields dot-joined owners, exact ranges render, and the non-Go + // honesty caveat holds with no Go call appendix. + let dir = temp_repo("discover_typescript_owner"); + fs::write( + dir.join("app.ts"), + "namespace A.B {\n export function foo() {}\n export class C {\n bar() {}\n }\n}\n", + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", "foo,bar", "--match", "any", "--as", "text", "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("app.ts:2 [owner A.B.foo@2-2]"), "{stdout}"); + assert!( + stdout.contains("app.ts:4 [owner A.B.C.bar@4-4]"), + "{stdout}" + ); + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + !stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_tsx_routes_through_tsx_grammar_with_callback_barrier() { + // A real `.tsx` file routes through the TSX grammar: the named component is + // an exact owner, the inline JSX callback is an anonymous barrier (no bogus + // owner), and the non-Go caveat/no-Go-appendix holds. + let dir = temp_repo("discover_tsx_owner_barrier"); + fs::write( + dir.join("app.tsx"), + "function App() {\n return ;\n}\nfunction util() {\n return 1;\n}\n", + ) + .unwrap(); + + let output = srcwalk() + .args([ + "discover", "App,util", "--match", "any", "--as", "text", "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("app.tsx:1 [owner App@1-3]"), "{stdout}"); + assert!(stdout.contains("app.tsx:4 [owner util@4-6]"), "{stdout}"); + assert!(!stdout.contains("app.tsx:2 [owner"), "{stdout}"); + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_mts_cts_route_owners_through_existing_lang_mapping() { + // `.mts`/`.cts` share the TypeScript Lang tier via the existing extension + // mapping (no extension hacks): both carry owner attribution. + let dir = temp_repo("discover_mts_cts_owner_routing"); + fs::write( + dir.join("mod.mts"), + "namespace N {\n export function foo() {}\n}\n", + ) + .unwrap(); + fs::write(dir.join("main.cts"), "class Svc {\n handle() {}\n}\n").unwrap(); + + let output = srcwalk() + .args([ + "discover", + "foo,handle", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("mod.mts:2 [owner N.foo@2-2]"), "{stdout}"); + assert!( + stdout.contains("main.cts:2 [owner Svc.handle@2-2]"), + "{stdout}" + ); + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + assert!(!stdout.contains("## Mechanical Go calls"), "{stdout}"); + + let _ = fs::remove_dir_all(&dir); +} + #[test] fn discover_malformed_go_with_python_owners_suppresses_go_call_appendix() { // Regression for the gate bug: a malformed Go input must not leave From 8f706f9627cdbe8535ae5a6861ca4dd98d2e29c7 Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 02:12:10 +0700 Subject: [PATCH 15/26] test: add deterministic owner replay harness --- src/commands/find.rs | 359 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 359 insertions(+) diff --git a/src/commands/find.rs b/src/commands/find.rs index 04a21e3..06a5391 100644 --- a/src/commands/find.rs +++ b/src/commands/find.rs @@ -2448,4 +2448,363 @@ mod tests { "{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)); + } } From 4fdb1a77086584c1cec73929bcbc2221269be13b Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 13:49:40 +0700 Subject: [PATCH 16/26] test: cover mixed owner orchestration --- src/evidence/owner_links.rs | 70 ++++++++++++ tests/intent_first_cli.rs | 210 +++++++++++++++++++++++++++++++++++- 2 files changed, 279 insertions(+), 1 deletion(-) diff --git a/src/evidence/owner_links.rs b/src/evidence/owner_links.rs index af860d6..4cbad39 100644 --- a/src/evidence/owner_links.rs +++ b/src/evidence/owner_links.rs @@ -1891,4 +1891,74 @@ mod tests { 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/tests/intent_first_cli.rs b/tests/intent_first_cli.rs index ae0747d..9e73566 100644 --- a/tests/intent_first_cli.rs +++ b/tests/intent_first_cli.rs @@ -1,5 +1,5 @@ use std::fs; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::Command; const OWNER_LINK_ZERO_EDGE: &str = "No direct name-level call evidence among hit owners. Dynamic dispatch, DI, callbacks, and protocol wiring are not ruled out."; @@ -2960,3 +2960,211 @@ fn trace_callers_path_symbol_success_path_remains_without_new_hint() { let _ = fs::remove_dir_all(&dir); } + +/// US-067 cross-language orchestration fixture: one temp scope with a Go +/// owner pair + valid Go->Go edge, named owners in Python/Rust/JS/TS/TSX, one +/// malformed supported file, and one unsupported `.txt`. +fn write_mixed_owner_scope(dir: &Path) { + fs::write( + dir.join("feature.go"), + "package feature\nfunc First() { /* alpha */ }\nfunc Second() { /* beta */ First() }\n", + ) + .unwrap(); + fs::write(dir.join("app.py"), "def load():\n return \"alpha\"\n").unwrap(); + fs::write( + dir.join("lib.rs"), + "fn load() {\n let _ = \"alpha\";\n}\n", + ) + .unwrap(); + fs::write( + dir.join("app.js"), + "function greet() {\n return \"alpha\";\n}\n", + ) + .unwrap(); + fs::write( + dir.join("app.ts"), + "function greet(): string {\n return \"alpha\";\n}\n", + ) + .unwrap(); + fs::write( + dir.join("App.tsx"), + "function App() {\n return
alpha
;\n}\n", + ) + .unwrap(); + // Malformed supported-language file: has a raw alpha hit but must abstain. + fs::write(dir.join("broken.py"), "def broken(\n return \"alpha\"\n").unwrap(); + // Unsupported raw file: preserved by search, absent from owner evidence. + fs::write(dir.join("notes.txt"), "line with alpha here\n").unwrap(); +} + +/// US-067 orchestration + determinism (tasks 1+2): one mixed Go/Python/Rust/JS/ +/// TS/TSX scope with a malformed supported file and an unsupported `.txt`. The +/// Go mechanical-call appendix renders Go-only, every clean file carries exact +/// per-file owner evidence, the malformed + unsupported raw hits stay visible +/// WITHOUT an owner, the non-Go honesty caveat holds, and no non-Go zero-edge/ +/// call claim is made. The exact command runs twice with byte-identical stdout +/// AND stderr. +#[test] +fn discover_text_or_mixed_owner_orchestration_and_determinism() { + let dir = temp_repo("discover_mixed_owner_orchestration"); + write_mixed_owner_scope(&dir); + + let run = || { + srcwalk() + .args([ + "discover", + "alpha,beta", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap() + }; + + let first = run(); + assert!( + first.status.success(), + "{}", + String::from_utf8_lossy(&first.stderr) + ); + + // Determinism: run twice, byte-compare stdout AND stderr. + let second = run(); + assert_eq!( + first.stdout, second.stdout, + "stdout bytes changed between runs" + ); + assert_eq!( + first.stderr, second.stderr, + "stderr bytes changed between runs" + ); + + let stdout = String::from_utf8_lossy(&first.stdout); + + // Header: 2-term Text OR, 9 matches across 8 files (detail path, <=30 hits). + assert!(stdout.contains("— 2 terms, 9 matches, 8 files"), "{stdout}"); + + // Every supported clean file carries exact per-file owner evidence. + for tag in [ + "feature.go:2 [owner First@2-2]", + "feature.go:3 [owner Second@3-3]", + "app.py:2 [owner load@1-2]", + "lib.rs:2 [owner load@1-3]", + "app.js:2 [owner greet@1-3]", + "app.ts:2 [owner greet@1-3]", + "App.tsx:2 [owner App@1-3]", + ] { + assert!(stdout.contains(tag), "missing {tag}:\n{stdout}"); + } + + // Malformed supported file + unsupported .txt: raw hit rows remain visible + // but carry NO owner tag. + assert!( + stdout.contains("broken.py:2 — return \"alpha\""), + "{stdout}" + ); + assert!( + stdout.contains("notes.txt:1 — line with alpha here"), + "{stdout}" + ); + assert!(!stdout.contains("broken.py:2 [owner"), "{stdout}"); + assert!(!stdout.contains("notes.txt:1 [owner"), "{stdout}"); + + // Go mechanical-call appendix exists and the single rendered edge is Go-only. + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + stdout.contains("- [bare] Second calls First@feature.go:3; candidate First@:2-2",), + "{stdout}" + ); + let go_edge_rows = stdout + .lines() + .filter(|l| l.starts_with("- [") && l.contains(" calls ")) + .count(); + assert_eq!(go_edge_rows, 1, "{stdout}"); + + // No non-Go zero-edge/call claim: not the zero-edge sentence, and no non-Go + // edge candidate appears. + assert!(!stdout.contains(OWNER_LINK_ZERO_EDGE), "{stdout}"); + assert!(!stdout.contains("candidate app."), "{stdout}"); + assert!(!stdout.contains("candidate lib."), "{stdout}"); + + // Go mechanical caveat + non-Go honesty caveat both present. + assert!( + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +/// US-067 Go isolation (task 5): adding non-matching non-Go files to a Go-only +/// scope leaves the Go query's stdout AND stderr byte-identical. +#[test] +fn discover_text_or_go_only_bytes_unchanged_by_non_matching_non_go_files() { + let dir = temp_repo("discover_go_isolation"); + fs::write( + dir.join("feature.go"), + "package feature\nfunc First() { /* alpha */ }\nfunc Second() { /* beta */ First() }\n", + ) + .unwrap(); + + let run = || { + srcwalk() + .args([ + "discover", + "alpha,beta", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap() + }; + + let before = run(); + assert!( + before.status.success(), + "{}", + String::from_utf8_lossy(&before.stderr) + ); + + // Add non-matching non-Go files (no alpha/beta anywhere) to the SAME dir so + // the scope path is unchanged. + fs::write(dir.join("app.py"), "def load():\n return 1\n").unwrap(); + fs::write(dir.join("lib.rs"), "fn load() {\n let _ = 1;\n}\n").unwrap(); + fs::write(dir.join("app.js"), "function greet() {\n return 1;\n}\n").unwrap(); + fs::write( + dir.join("App.tsx"), + "function App() {\n return
plain
;\n}\n", + ) + .unwrap(); + fs::write(dir.join("notes.txt"), "just a plain text note\n").unwrap(); + + let after = run(); + assert!( + after.status.success(), + "{}", + String::from_utf8_lossy(&after.stderr) + ); + assert_eq!( + before.stdout, after.stdout, + "Go stdout changed when non-Go files added" + ); + assert_eq!( + before.stderr, after.stderr, + "Go stderr changed when non-Go files added" + ); + + let _ = fs::remove_dir_all(&dir); +} From ac73aa09638eedcd37ecde2b05465dfe47fc448b Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 15:37:20 +0700 Subject: [PATCH 17/26] feat(java): Java owner attribution (US-068 wave 2A) --- src/evidence/owner_links.rs | 23 +- src/evidence/owners/java.rs | 721 ++++++++++++++++++++++++++++++++++++ src/evidence/owners/mod.rs | 1 + 3 files changed, 744 insertions(+), 1 deletion(-) create mode 100644 src/evidence/owners/java.rs diff --git a/src/evidence/owner_links.rs b/src/evidence/owner_links.rs index 4cbad39..7bb0216 100644 --- a/src/evidence/owner_links.rs +++ b/src/evidence/owner_links.rs @@ -179,7 +179,8 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own detected, crate::types::FileType::Code(Lang::JavaScript | Lang::TypeScript | Lang::Tsx) ); - if is_go || is_python || is_rust || is_js_ts_family { + let is_java = detected == crate::types::FileType::Code(Lang::Java); + if is_go || is_python || is_rust || is_js_ts_family || is_java { by_path .entry(input.path.to_path_buf()) .or_default() @@ -257,6 +258,26 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own } 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; + } 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. diff --git a/src/evidence/owners/java.rs b/src/evidence/owners/java.rs new file mode 100644 index 0000000..a095c8e --- /dev/null +++ b/src/evidence/owners/java.rs @@ -0,0 +1,721 @@ +//! 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 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/mod.rs b/src/evidence/owners/mod.rs index c6c54df..82fa6aa 100644 --- a/src/evidence/owners/mod.rs +++ b/src/evidence/owners/mod.rs @@ -13,6 +13,7 @@ //! (`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 java; pub(crate) mod js_ts; pub(crate) mod python; pub(crate) mod rust; From 33c0d5f88a6e218dd28b5d59b9ce51787770cca5 Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 16:10:48 +0700 Subject: [PATCH 18/26] feat(kotlin): Kotlin owner attribution (US-068 Wave 2A) Kotlin owner-only adapter on pinned tree-sitter-kotlin-ng 1.1.0: - named owners: top-level/class/nested/local functions, named object, companion (default 'Companion' or declared name), extension receiver prefix, secondary constructor, property accessors, local function path. - identity barriers for lambda_literal/annotated_lambda/anonymous_function, anonymous_initializer, object_literal; abstain bodyless fn/ctor and primary_constructor. - receiver must be a type kind (fixes generic fun receiver bug). - manifest gate + node-types fingerprint; 60+/20+ quality gate. - fold Java crossing-context initializer follow-up tests. - wire Kotlin owner-only seam in owner_links. --- src/evidence/owner_links.rs | 23 +- src/evidence/owners/java.rs | 22 + src/evidence/owners/kotlin.rs | 886 ++++++++++++++++++++++++++++++++++ src/evidence/owners/mod.rs | 1 + 4 files changed, 931 insertions(+), 1 deletion(-) create mode 100644 src/evidence/owners/kotlin.rs diff --git a/src/evidence/owner_links.rs b/src/evidence/owner_links.rs index 7bb0216..5b977c2 100644 --- a/src/evidence/owner_links.rs +++ b/src/evidence/owner_links.rs @@ -180,7 +180,8 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own crate::types::FileType::Code(Lang::JavaScript | Lang::TypeScript | Lang::Tsx) ); let is_java = detected == crate::types::FileType::Code(Lang::Java); - if is_go || is_python || is_rust || is_js_ts_family || is_java { + let is_kotlin = detected == crate::types::FileType::Code(Lang::Kotlin); + if is_go || is_python || is_rust || is_js_ts_family || is_java || is_kotlin { by_path .entry(input.path.to_path_buf()) .or_default() @@ -278,6 +279,26 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own } 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; + } 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. diff --git a/src/evidence/owners/java.rs b/src/evidence/owners/java.rs index a095c8e..a623add 100644 --- a/src/evidence/owners/java.rs +++ b/src/evidence/owners/java.rs @@ -388,6 +388,28 @@ mod tests { 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"); 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 index 82fa6aa..dcd207d 100644 --- a/src/evidence/owners/mod.rs +++ b/src/evidence/owners/mod.rs @@ -15,6 +15,7 @@ pub(crate) mod java; pub(crate) mod js_ts; +pub(crate) mod kotlin; pub(crate) mod python; pub(crate) mod rust; From c63557b624f019578f1fc57e99d8d62e2047c067 Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 17:07:12 +0700 Subject: [PATCH 19/26] feat(owners): add PHP owner attribution adapter (US-068 Wave 2A) Body-bearing function_definition (declared name), method_declaration under class/interface/trait/enum containers (Service::load), namespace as a `\` lexical container (Acme\Api\load, Acme\Api\Service::load; braced and unbraced forms produce the same identity), and body-bearing single-property hooks (Container::$prop::get/set). Anonymous barriers for anonymous_function, arrow_function, and anonymous_class; a named function nested inside a callable body is an identity barrier (PHP registers it globally; neither outer::inner nor outer.inner); body-less methods/hooks abstain; fail-closed field_nonempty rejects empty structural names; a namespace name field present-but-empty is a malformed barrier while a missing field is a valid global namespace. Curated matrix: 62 positives >=60, 41 abstentions >=20, exact names/ranges. Version-pinned callable manifest (tree-sitter-php 0.24.2 php grammar) with PHP_NODE_TYPES fingerprint 0x1297dd3f8fd2f5d3. Path-isolated: only src/evidence/owners/php.rs. --- src/evidence/owners/php.rs | 1051 ++++++++++++++++++++++++++++++++++++ 1 file changed, 1051 insertions(+) create mode 100644 src/evidence/owners/php.rs 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" + ); + } +} From 389ea3a7b78e103f58fc4758844ef5f66de8eb47 Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 17:08:31 +0700 Subject: [PATCH 20/26] feat(csharp): C# owner attribution (US-068 Wave 2A) Add C# owner adapter with fail-closed identity handling: - Named owners under type+namespace containers, property/event/indexer accessors, expression-bodied members, local functions, operators, constructors/destructors, conversion operators. - AnonymousBarrier for lambdas/anonymous methods. - Trim + non-empty normalization for every required identity component (method, local fn, ctor/dtor, operator symbol, conversion target, property/event base, namespace/type, accessor kind) so no dangling segments like `Service.` / `.get` / `operator `. - Missing-name namespace/type/accessor and malformed file-scoped namespace fail closed (full-range barrier + anonymous descend). 28 tests incl. crossing-context, malformed-identity, and required_identity normalization regression cases. --- src/evidence/owner_links.rs | 23 +- src/evidence/owners/csharp.rs | 1491 +++++++++++++++++++++++++++++++++ src/evidence/owners/mod.rs | 1 + 3 files changed, 1514 insertions(+), 1 deletion(-) create mode 100644 src/evidence/owners/csharp.rs diff --git a/src/evidence/owner_links.rs b/src/evidence/owner_links.rs index 5b977c2..32bbe74 100644 --- a/src/evidence/owner_links.rs +++ b/src/evidence/owner_links.rs @@ -181,7 +181,8 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own ); let is_java = detected == crate::types::FileType::Code(Lang::Java); let is_kotlin = detected == crate::types::FileType::Code(Lang::Kotlin); - if is_go || is_python || is_rust || is_js_ts_family || is_java || is_kotlin { + let is_csharp = detected == crate::types::FileType::Code(Lang::CSharp); + if is_go || is_python || is_rust || is_js_ts_family || is_java || is_kotlin || is_csharp { by_path .entry(input.path.to_path_buf()) .or_default() @@ -299,6 +300,26 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own } 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; + } 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. 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/mod.rs b/src/evidence/owners/mod.rs index dcd207d..13b01b7 100644 --- a/src/evidence/owners/mod.rs +++ b/src/evidence/owners/mod.rs @@ -13,6 +13,7 @@ //! (`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; From 9d5b8ae98b00025667d0ecaa2b50c7cbb481f8f8 Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 17:10:50 +0700 Subject: [PATCH 21/26] feat(owners): wire PHP owner attribution --- src/evidence/owner_links.rs | 30 +++++++++++++++++++++++++++++- src/evidence/owners/mod.rs | 1 + 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/evidence/owner_links.rs b/src/evidence/owner_links.rs index 32bbe74..516a2da 100644 --- a/src/evidence/owner_links.rs +++ b/src/evidence/owner_links.rs @@ -182,7 +182,16 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own 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); - if is_go || is_python || is_rust || is_js_ts_family || is_java || is_kotlin || is_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() @@ -320,6 +329,25 @@ pub(crate) fn build_owner_link_evidence(inputs: &[OwnerLinkHitInput<'_>]) -> Own } 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. diff --git a/src/evidence/owners/mod.rs b/src/evidence/owners/mod.rs index 13b01b7..5c634a3 100644 --- a/src/evidence/owners/mod.rs +++ b/src/evidence/owners/mod.rs @@ -17,6 +17,7 @@ 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; From ef8bcade428ef822e2039d1d222ecb4e409211cd Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 17:26:13 +0700 Subject: [PATCH 22/26] test: add US-068 owner integration regressions --- tests/intent_first_cli.rs | 453 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 453 insertions(+) diff --git a/tests/intent_first_cli.rs b/tests/intent_first_cli.rs index 9e73566..1f9394c 100644 --- a/tests/intent_first_cli.rs +++ b/tests/intent_first_cli.rs @@ -3168,3 +3168,456 @@ fn discover_text_or_go_only_bytes_unchanged_by_non_matching_non_go_files() { let _ = fs::remove_dir_all(&dir); } + +/// Wave 2A full mixed-language scope: Go + TSX/TS/JS + Python + Rust + Java + +/// Kotlin + C# + PHP, each with a named owner over a matching hit. Only Go has +/// a name-level call edge (`Second -> First`). +fn write_wave2a_full_mixed_scope(dir: &Path) { + fs::write( + dir.join("feature.go"), + "package feature\nfunc First() { /* alpha */ }\nfunc Second() { /* beta */ First() }\n", + ) + .unwrap(); + fs::write(dir.join("app.py"), "def load():\n return \"alpha\"\n").unwrap(); + fs::write( + dir.join("lib.rs"), + "fn load() {\n let _ = \"alpha\";\n}\n", + ) + .unwrap(); + fs::write( + dir.join("app.js"), + "function greet() {\n return \"alpha\";\n}\n", + ) + .unwrap(); + fs::write( + dir.join("app.ts"), + "function greet(): string {\n return \"alpha\";\n}\n", + ) + .unwrap(); + fs::write( + dir.join("App.tsx"), + "function App() {\n return
alpha
;\n}\n", + ) + .unwrap(); + fs::write( + dir.join("Service.java"), + "class Service {\n void handle() {\n int x = 1; // alpha\n }\n}\n", + ) + .unwrap(); + fs::write( + dir.join("App.kt"), + "class App {\n fun load() {\n val s = \"alpha\"\n }\n}\n", + ) + .unwrap(); + fs::write( + dir.join("Program.cs"), + "class Service {\n void Load() {\n // alpha\n }\n}\n", + ) + .unwrap(); + fs::write( + dir.join("page.php"), + " First`; +/// no non-Go edge or zero-edge sentence appears. +#[test] +fn discover_text_or_wave2a_full_mixed_owner_orchestration() { + let dir = temp_repo("discover_wave2a_full_mixed_owner"); + write_wave2a_full_mixed_scope(&dir); + + let output = srcwalk() + .args([ + "discover", + "alpha,beta", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + + // Header: 2 terms, 11 matches across 10 files (detail path, <=30 hits). + assert!( + stdout.contains("— 2 terms, 11 matches, 10 files"), + "{stdout}" + ); + + // Every supported language carries exact per-file owner evidence. + for tag in [ + "feature.go:2 [owner First@2-2]", + "feature.go:3 [owner Second@3-3]", + "app.py:2 [owner load@1-2]", + "lib.rs:2 [owner load@1-3]", + "app.js:2 [owner greet@1-3]", + "app.ts:2 [owner greet@1-3]", + "App.tsx:2 [owner App@1-3]", + "Service.java:3 [owner Service.handle@2-4]", + "App.kt:3 [owner App.load@2-4]", + "Program.cs:3 [owner Service.Load@2-4]", + "page.php:3 [owner load@2-4]", + ] { + assert!(stdout.contains(tag), "missing {tag}:\n{stdout}"); + } + + // Go mechanical-call appendix exists and the single rendered edge is Go-only. + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + stdout.contains("- [bare] Second calls First@feature.go:3; candidate First@:2-2"), + "{stdout}" + ); + let go_edge_rows = stdout + .lines() + .filter(|l| l.starts_with("- [") && l.contains(" calls ")) + .count(); + assert_eq!(go_edge_rows, 1, "{stdout}"); + + // No non-Go edge/zero-edge claim. + assert!(!stdout.contains(OWNER_LINK_ZERO_EDGE), "{stdout}"); + assert!(!stdout.contains("candidate app."), "{stdout}"); + assert!(!stdout.contains("candidate Service."), "{stdout}"); + assert!(!stdout.contains("candidate App."), "{stdout}"); + + // Both honesty caveats present. + assert!( + stdout.contains("structural owner and mechanically filtered"), + "{stdout}" + ); + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} + +/// US-068 integration task 2: same mixed scope run under several file-creation +/// orders must yield byte-identical stdout AND stderr (owner rollups, term +/// indices, ranges, caveats, and the Go appendix). +#[test] +fn discover_text_or_wave2a_determinism_across_file_creation_orders() { + let dir = temp_repo("discover_wave2a_determinism"); + write_wave2a_full_mixed_scope(&dir); + + let run = |d: &Path| { + srcwalk() + .args([ + "discover", + "alpha,beta", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(d) + .output() + .unwrap() + }; + let first = run(&dir); + assert!( + first.status.success(), + "{}", + String::from_utf8_lossy(&first.stderr) + ); + + // Recreate the same files in reverse lexical order in the same directory. + // This changes file-creation order without changing the rendered scope path. + let mut files = fs::read_dir(&dir) + .unwrap() + .map(|entry| { + let path = entry.unwrap().path(); + let bytes = fs::read(&path).unwrap(); + (path, bytes) + }) + .collect::>(); + files.sort_by(|(left, _), (right, _)| left.cmp(right)); + for (path, _) in &files { + fs::remove_file(path).unwrap(); + } + for (path, bytes) in files.iter().rev() { + fs::write(path, bytes).unwrap(); + } + + let second = run(&dir); + assert!( + second.status.success(), + "{}", + String::from_utf8_lossy(&second.stderr) + ); + assert_eq!( + first.stdout, second.stdout, + "stdout differs across creation orders" + ); + assert_eq!( + first.stderr, second.stderr, + "stderr differs across creation orders" + ); + + let _ = fs::remove_dir_all(&dir); +} + +/// US-068 integration task 3: one malformed file per Wave 2A language. Raw hits +/// remain visible; the error-overlapping region abstains; a valid region in the +/// same partially-parsed file stays eligible; no outer owner leakage occurs. +#[test] +fn discover_text_or_wave2a_malformed_files_abstain_without_outer_leakage() { + let dir = temp_repo("discover_wave2a_malformed"); + // Java: valid method + malformed method (unclosed param list) in one class. + fs::write( + dir.join("Bad.java"), + "class Service {\n void good() {\n // alpha\n }\n void bad( {\n // beta\n }\n}\n", + ) + .unwrap(); + // Kotlin: malformed statement inside a function body leaves the valid region + // eligible while the error-overlapping region abstains. + fs::write( + dir.join("Bad.kt"), + "class App {\n fun good() {\n val a = \"alpha\"\n }\n fun bad() {\n val b = \"beta\"\n if ( {\n val c = \"gamma\"\n }\n }\n}\n", + ) + .unwrap(); + // C#: valid method + malformed method in one class. + fs::write( + dir.join("Bad.cs"), + "class Service {\n void Good() {\n // alpha\n }\n void Bad( {\n // beta\n }\n}\n", + ) + .unwrap(); + // PHP: valid function + malformed function in one file. + fs::write( + dir.join("Bad.php"), + "alpha;\n}\n", + ) + .unwrap(); + let us067_before = run(&us067_dir, "alpha"); + assert!( + us067_before.status.success(), + "{}", + String::from_utf8_lossy(&us067_before.stderr) + ); + for (name, source) in [ + ("NonMatch.java", "class N { void m() { int x = 1; } }\n"), + ("NonMatch.kt", "class N { fun m() { val x = 1 } }\n"), + ("NonMatch.cs", "class N { void M() { int x = 1; } }\n"), + ("NonMatch.php", "=3 terms) renders owner +/// evidence for every language with no non-Go edge/zero-edge sentence. +#[test] +fn discover_text_or_wave2a_compact_rollup_attributes_all_languages() { + let dir = temp_repo("discover_wave2a_compact"); + write_wave2a_full_mixed_scope(&dir); + // Compact rendering intentionally ranks at most eight files. Keep one + // representative JS file here; the inline mixed test covers TS and TSX. + fs::remove_file(dir.join("app.ts")).unwrap(); + fs::remove_file(dir.join("App.tsx")).unwrap(); + + let output = srcwalk() + .args([ + "discover", + "alpha,beta,gamma", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .args(["--budget", "20000", "--limit", "20"]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + + // Compact rollup owner line header present. + assert!( + stdout.contains("owners (#N=Nth query term; *K=hits)"), + "{stdout}" + ); + // Compact owner anchors for every language. + for (file, owner) in [ + ("feature.go —", "First:2-2[#1]"), + ("app.py —", "load:1-2[#1]"), + ("lib.rs —", "load:1-3[#1]"), + ("app.js —", "greet:1-3[#1]"), + ("Service.java —", "Service.handle:2-4[#1]"), + ("App.kt —", "App.load:2-4[#1]"), + ("Program.cs —", "Service.Load:2-4[#1]"), + ("page.php —", "load:2-4[#1]"), + ] { + assert!(stdout.contains(file), "missing {file}:\n{stdout}"); + assert!(stdout.contains(owner), "missing {owner}:\n{stdout}"); + } + // Go mechanical appendix still present and Go-only edge. + assert!(stdout.contains("## Mechanical Go calls"), "{stdout}"); + assert!( + stdout.contains("Second calls First@feature.go:3"), + "{stdout}" + ); + // No non-Go zero-edge sentence. + assert!(!stdout.contains(OWNER_LINK_ZERO_EDGE), "{stdout}"); + // Non-Go honesty caveat retained. + assert!( + stdout.contains("structural lexical ownership candidates"), + "{stdout}" + ); + + let _ = fs::remove_dir_all(&dir); +} From 968d0c8d04de71217697b3501258baefbe71b7f3 Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 21:03:22 +0700 Subject: [PATCH 23/26] feat(search): advise on low-signal text terms --- skills/srcwalk/GUIDE.md | 2 +- src/commands/find.rs | 21 +++- src/commands/multi_scope.rs | 68 +++++++++- src/search/content.rs | 86 +++++++++++++ src/search/cooccurrence.rs | 1 + src/search/low_signal.rs | 207 +++++++++++++++++++++++++++++++ src/search/mod.rs | 18 ++- src/search/pagination.rs | 1 + src/search/symbol.rs | 1 + src/search/symbol/batch.rs | 1 + src/search/symbol/glob_search.rs | 1 + src/types.rs | 3 + tests/intent_first_cli.rs | 144 +++++++++++++++++++++ 13 files changed, 546 insertions(+), 8 deletions(-) create mode 100644 src/search/low_signal.rs diff --git a/skills/srcwalk/GUIDE.md b/skills/srcwalk/GUIDE.md index 0520f82..5952d27 100644 --- a/skills/srcwalk/GUIDE.md +++ b/skills/srcwalk/GUIDE.md @@ -64,7 +64,7 @@ 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 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. diff --git a/src/commands/find.rs b/src/commands/find.rs index 06a5391..ce97c09 100644 --- a/src/commands/find.rs +++ b/src/commands/find.rs @@ -158,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)?; @@ -168,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)), @@ -206,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 (query_term_index, term) in &indexed_terms { - let mut result = search::search_content_raw_with_artifact(term, scope, glob, artifact)?; + 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 @@ -274,6 +287,9 @@ pub(crate) fn run_text_or_filtered_with_artifact( 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`.", @@ -1053,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() 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/search/content.rs b/src/search/content.rs index fd91dab..17f5866 100644 --- a/src/search/content.rs +++ b/src/search/content.rs @@ -1,5 +1,6 @@ use std::io::Read; use std::path::Path; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use super::file_metadata; @@ -45,6 +46,9 @@ pub fn search( ) } +/// Content search. `eligible_files` is always 0 here: counting eligibility is +/// opt-in and only the explicit literal-text routes request it, so out-of-scope +/// regex/co-occurrence/expanded/inferred routes incur no per-file counter. pub fn search_with_artifact( pattern: &str, scope: &Path, @@ -52,6 +56,33 @@ pub fn search_with_artifact( context: Option<&Path>, glob: Option<&str>, artifact: ArtifactMode, +) -> Result { + search_with_artifact_impl(pattern, scope, is_regex, context, glob, artifact, false) +} + +/// Explicit literal-text search variant that also counts eligible files in the +/// same walker pass via an atomic counter. Only single-scope `--as text` Search +/// and explicit Text OR call this; every other content caller stays on +/// `search_with_artifact` with `eligible_files = 0` and no per-file lock. +pub fn search_with_artifact_counting( + pattern: &str, + scope: &Path, + is_regex: bool, + context: Option<&Path>, + glob: Option<&str>, + artifact: ArtifactMode, +) -> Result { + search_with_artifact_impl(pattern, scope, is_regex, context, glob, artifact, true) +} + +fn search_with_artifact_impl( + pattern: &str, + scope: &Path, + is_regex: bool, + context: Option<&Path>, + glob: Option<&str>, + artifact: ArtifactMode, + count_eligible: bool, ) -> Result { let matcher = if is_regex { RegexMatcher::new(pattern) @@ -64,6 +95,7 @@ pub fn search_with_artifact( })?; let matches: Mutex> = Mutex::new(Vec::new()); + let eligible_files = AtomicUsize::new(0); let walker = if artifact.enabled() { super::io::walker_with_artifact_dirs(scope, glob)? } else { @@ -73,6 +105,7 @@ pub fn search_with_artifact( walker.run(|| { let matcher = &matcher; let matches = &matches; + let eligible_files = &eligible_files; Box::new(move |entry| { let Ok(entry) = entry else { @@ -104,6 +137,13 @@ pub fn search_with_artifact( } } + // On the opt-in counting variant, tally eligibility in this existing + // content-search pass, after every walker/glob/artifact/binary/size + // guard and before I/O. Non-counting callers skip the atomic touch. + if count_eligible { + eligible_files.fetch_add(1, Ordering::Relaxed); + } + let (file_lines, mtime) = file_metadata(path); let mut file_matches = Vec::new(); @@ -150,6 +190,11 @@ pub fn search_with_artifact( let mut all_matches = matches .into_inner() .unwrap_or_else(std::sync::PoisonError::into_inner); + let eligible_files = if count_eligible { + eligible_files.load(Ordering::Relaxed) + } else { + 0 + }; rank::sort(&mut all_matches, pattern, scope, context); @@ -160,6 +205,7 @@ pub fn search_with_artifact( scope: scope.to_path_buf(), matches: all_matches, total_found: total, + eligible_files, definition_candidates: 0, name_occurrence_candidates: 0, definitions: 0, @@ -169,3 +215,43 @@ pub fn search_with_artifact( offset: 0, }) } + +#[cfg(test)] +mod tests { + use crate::ArtifactMode; + + use super::{search_with_artifact, search_with_artifact_counting}; + + #[test] + fn eligible_counting_is_opt_in() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("a.rs"), "fn one() { frobnicate }\n").unwrap(); + std::fs::write(dir.path().join("b.rs"), "fn two() { frobnicate }\n").unwrap(); + + // Non-opt-in content search must not collect an eligible denominator. + let plain = search_with_artifact( + "frobnicate", + dir.path(), + false, + None, + None, + ArtifactMode::Source, + ) + .unwrap(); + assert_eq!(plain.eligible_files, 0, "non-opt-in route abstains"); + assert_eq!(plain.total_found, 2); + + // The opt-in literal-text variant reports the eligible-file count. + let counted = search_with_artifact_counting( + "frobnicate", + dir.path(), + false, + None, + None, + ArtifactMode::Source, + ) + .unwrap(); + assert_eq!(counted.eligible_files, 2, "opt-in route counts eligibility"); + assert_eq!(counted.total_found, 2); + } +} diff --git a/src/search/cooccurrence.rs b/src/search/cooccurrence.rs index 6dc6cd4..596d037 100644 --- a/src/search/cooccurrence.rs +++ b/src/search/cooccurrence.rs @@ -108,6 +108,7 @@ pub fn search_same_line_ordered( scope: scope.to_path_buf(), matches: all_matches, total_found: total, + eligible_files: 0, definition_candidates: 0, name_occurrence_candidates: 0, definitions: 0, diff --git a/src/search/low_signal.rs b/src/search/low_signal.rs new file mode 100644 index 0000000..f507df1 --- /dev/null +++ b/src/search/low_signal.rs @@ -0,0 +1,207 @@ +use crate::types::SearchResult; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct LowSignalTermStats { + pub(crate) term: String, + pub(crate) total_matches: usize, + pub(crate) matched_files: usize, + pub(crate) eligible_files: usize, +} + +pub(crate) fn low_signal_term_stats(term: &str, result: &SearchResult) -> LowSignalTermStats { + let matched_files = result + .matches + .iter() + .map(|matched| &matched.path) + .collect::>() + .len(); + LowSignalTermStats { + term: term.to_string(), + total_matches: result.total_found, + matched_files, + eligible_files: result.eligible_files, + } +} + +/// v1 thresholds are evidence-derived, not a universal semantic classifier. +/// Validation date: 2026-08-12. Pinned repositories: Ktor +/// `a8d8038939d788547b807acbc580609e7603d9dd`, Spring Framework +/// `68e6acd37ed0c12e395ef96d170971028e727383`, Symfony +/// `3b11ffbe2520436b0951974d1993dc2144f91dd3`, and dotnet/runtime +/// `656d1d6f42b140e751f65a2ec58e5066b54e1f54`. The closest observed separator +/// was runtime `GetTypeInfo` near 1.26% versus runtime `execute` near 1.92%, a +/// 0.66 percentage-point margin. Retuning any constant requires new +/// cross-repository evidence, an updated matrix and boundary tests, and reviewer +/// approval. +const MIN_MATCHES: usize = 400; +const MIN_MATCHED_FILES: usize = 150; +const SPREAD_SCALE: u128 = 1_000; +const MIN_SPREAD: u128 = 15; + +pub(crate) fn low_signal_term_advisory(stats: &LowSignalTermStats) -> Option { + if stats.eligible_files == 0 + || stats.total_matches < MIN_MATCHES + || stats.matched_files < MIN_MATCHED_FILES + { + return None; + } + + let matched_scaled = (stats.matched_files as u128).checked_mul(SPREAD_SCALE)?; + let eligible_scaled = (stats.eligible_files as u128).checked_mul(MIN_SPREAD)?; + if matched_scaled < eligible_scaled { + return None; + } + + Some(format!( + "> Note: {} matches across {} of {} eligible files for `{}`; if this spread is not intentional, consider `overview`, a narrower term or scope, or a structural route.", + format_count(stats.total_matches), + format_count(stats.matched_files), + format_count(stats.eligible_files), + escape_term(&stats.term), + )) +} + +/// Put shared advisory lines into the trailing footer immediately before the +/// existing generic `> Next:` action. The budget layer preserves this footer. +pub(crate) fn insert_low_signal_advisories(output: String, advisories: &[String]) -> String { + if advisories.is_empty() { + return output; + } + let notes = advisories.join("\n"); + let Some((body, footer)) = crate::format::split_trailing_footer(&output) else { + return format!("{}\n\n{notes}", output.trim_end()); + }; + + let footer = footer.trim(); + // Insert before the generic `> Next:` action when present; otherwise append + // at the footer end so pre-existing caveats/notes stay first (contract: existing + // evidence first, advisory before generic Next). + let insertion = footer.find("> Next:").unwrap_or(footer.len()); + let (before, after) = footer.split_at(insertion); + let before = before.trim_end(); + let after = after.trim_start(); + let mut rendered_footer = String::new(); + if !before.is_empty() { + rendered_footer.push_str(before); + rendered_footer.push('\n'); + } + rendered_footer.push_str(¬es); + if !after.is_empty() { + rendered_footer.push('\n'); + rendered_footer.push_str(after); + } + format!("{}\n\n{rendered_footer}", body.trim_end()) +} + +fn format_count(value: usize) -> String { + let digits = value.to_string(); + let mut rendered = String::with_capacity(digits.len() + digits.len() / 3); + for (index, character) in digits.chars().enumerate() { + if index > 0 && (digits.len() - index).is_multiple_of(3) { + rendered.push(','); + } + rendered.push(character); + } + rendered +} + +fn escape_term(term: &str) -> String { + let mut escaped = String::with_capacity(term.len()); + for character in term.chars() { + match character { + '\\' => escaped.push_str("\\\\"), + '`' => escaped.push_str("\\`"), + '\n' => escaped.push_str("\\n"), + '\r' => escaped.push_str("\\r"), + '\t' => escaped.push_str("\\t"), + character if character.is_control() => { + use std::fmt::Write as _; + let _ = write!(escaped, "\\u{{{:x}}}", character as u32); + } + character => escaped.push(character), + } + } + escaped +} + +#[cfg(test)] +mod tests { + use super::{insert_low_signal_advisories, low_signal_term_advisory, LowSignalTermStats}; + + fn stats( + total_matches: usize, + matched_files: usize, + eligible_files: usize, + ) -> LowSignalTermStats { + LowSignalTermStats { + term: "execute".to_string(), + total_matches, + matched_files, + eligible_files, + } + } + + #[test] + fn threshold_boundaries_are_inclusive() { + assert!(low_signal_term_advisory(&stats(399, 150, 1_000)).is_none()); + assert!(low_signal_term_advisory(&stats(400, 149, 1_000)).is_none()); + assert!(low_signal_term_advisory(&stats(400, 150, 10_001)).is_none()); + assert_eq!( + low_signal_term_advisory(&stats(400, 150, 10_000)).as_deref(), + Some("> Note: 400 matches across 150 of 10,000 eligible files for `execute`; if this spread is not intentional, consider `overview`, a narrower term or scope, or a structural route.") + ); + } + + #[test] + fn zero_eligible_files_never_trigger() { + assert!(low_signal_term_advisory(&stats(10_000, 10_000, 0)).is_none()); + } + + #[test] + fn repeated_calls_are_byte_identical_and_wording_is_conditional() { + let stats = stats(452, 171, 3_046); + let first = low_signal_term_advisory(&stats).unwrap(); + assert_eq!(first, low_signal_term_advisory(&stats).unwrap()); + assert!(first.contains("if this spread is not intentional")); + for forbidden in ["stop", "must", "avoid"] { + assert!(!first.to_ascii_lowercase().contains(forbidden), "{first}"); + } + } + + #[test] + fn term_escaping_keeps_the_note_single_line_and_quoted() { + let mut stats = stats(400, 150, 10_000); + stats.term = "a`b\\c\n".to_string(); + let note = low_signal_term_advisory(&stats).unwrap(); + assert!(note.contains("for `a\\`b\\\\c\\n`;"), "{note}"); + assert!(!note.contains('\n')); + } + + #[test] + fn advisory_inserts_before_existing_next_footer() { + let output = "body\n\n> Caveat: existing\n\n> Next: continue".to_string(); + let note = low_signal_term_advisory(&stats(400, 150, 10_000)).unwrap(); + let rendered = insert_low_signal_advisories(output, &[note]); + assert!( + rendered.contains("> Caveat: existing\n> Note:"), + "{rendered}" + ); + assert!(rendered.find("> Note:").unwrap() < rendered.find("> Next:").unwrap()); + } + + #[test] + fn advisory_appends_after_existing_notes_when_no_next() { + // Footer with existing caveat + note but no `> Next:`. The low-signal + // note must go after the existing note, not before it. + let out = "body\n\n> Caveat: existing\n\n> Note: prior note\n".to_string(); + let note = low_signal_term_advisory(&stats(400, 150, 10_000)).unwrap(); + let rendered = insert_low_signal_advisories(out, &[note]); + let caveat = rendered.find("> Caveat:").unwrap(); + let prior = rendered.find("> Note: prior note").unwrap(); + let low = rendered.rfind("> Note: 400 matches").unwrap(); + assert!( + caveat < prior && prior < low, + "existing evidence must precede advisory:\n{rendered}" + ); + } +} diff --git a/src/search/mod.rs b/src/search/mod.rs index 3b3b8c5..b85c65c 100644 --- a/src/search/mod.rs +++ b/src/search/mod.rs @@ -11,6 +11,7 @@ mod filter; pub mod glob; mod go_imports; pub mod io; +mod low_signal; pub mod pagination; pub mod rank; pub mod siblings; @@ -40,6 +41,9 @@ pub use self::display::{ pub use self::filter::apply_general_filter; pub(crate) use self::io::{file_metadata, read_file_bytes}; use self::io::{parse_pattern, walker}; +pub(crate) use self::low_signal::{ + insert_low_signal_advisories, low_signal_term_advisory, low_signal_term_stats, +}; use self::pagination::paginate; use self::display::{ @@ -526,22 +530,28 @@ pub fn search_symbol_glob_raw_with_artifact( } /// Raw content search — returns structured result for programmatic inspection. -pub fn search_content_raw( +/// `eligible_files` is always 0 (counting is opt-in). +pub fn search_content_raw_with_artifact( query: &str, scope: &Path, glob: Option<&str>, + artifact: ArtifactMode, ) -> Result { - search_content_raw_with_artifact(query, scope, glob, ArtifactMode::Source) + let (pattern, is_regex) = parse_pattern(query); + content::search_with_artifact(pattern, scope, is_regex, None, glob, artifact) } -pub fn search_content_raw_with_artifact( +/// Raw literal-text search that also counts eligible files in the same pass. +/// Only the explicit single-scope `--as text` and Text OR routes call this; +/// every other content caller stays on `search_content_raw_with_artifact`. +pub(crate) fn search_content_raw_with_artifact_counting( query: &str, scope: &Path, glob: Option<&str>, artifact: ArtifactMode, ) -> Result { let (pattern, is_regex) = parse_pattern(query); - content::search_with_artifact(pattern, scope, is_regex, None, glob, artifact) + content::search_with_artifact_counting(pattern, scope, is_regex, None, glob, artifact) } /// Raw regex search — returns structured result for programmatic inspection. diff --git a/src/search/pagination.rs b/src/search/pagination.rs index a317cfa..39a68ba 100644 --- a/src/search/pagination.rs +++ b/src/search/pagination.rs @@ -67,6 +67,7 @@ mod tests { hit(3, false, false), ], total_found: 3, + eligible_files: 0, definition_candidates: 1, name_occurrence_candidates: 1, definitions: 1, diff --git a/src/search/symbol.rs b/src/search/symbol.rs index 051dc0a..651657c 100644 --- a/src/search/symbol.rs +++ b/src/search/symbol.rs @@ -121,6 +121,7 @@ pub fn search_with_artifact( query: query.to_string(), scope: scope.to_path_buf(), total_found: total, + eligible_files: 0, definition_candidates: def_count, name_occurrence_candidates: merged .iter() diff --git a/src/search/symbol/batch.rs b/src/search/symbol/batch.rs index 8ad2988..e18d39b 100644 --- a/src/search/symbol/batch.rs +++ b/src/search/symbol/batch.rs @@ -84,6 +84,7 @@ pub(super) fn search_batch( query: (*query).to_string(), scope: scope.to_path_buf(), total_found: total, + eligible_files: 0, definition_candidates: def_count, name_occurrence_candidates: merged .iter() diff --git a/src/search/symbol/glob_search.rs b/src/search/symbol/glob_search.rs index e676d10..926efe7 100644 --- a/src/search/symbol/glob_search.rs +++ b/src/search/symbol/glob_search.rs @@ -137,6 +137,7 @@ pub(super) fn search_name_glob_with_artifact( scope: scope.to_path_buf(), matches: merged, total_found: total, + eligible_files: 0, definition_candidates: total, name_occurrence_candidates: 0, definitions: total, diff --git a/src/types.rs b/src/types.rs index 39ff22b..c9953d5 100644 --- a/src/types.rs +++ b/src/types.rs @@ -317,6 +317,9 @@ pub struct SearchResult { pub scope: PathBuf, pub matches: Vec, pub total_found: usize, + /// Number of files that survived content-search eligibility guards before matching. + /// This denominator is unpaginated and remains stable through filtering and pagination. + pub(crate) eligible_files: usize, /// Definition candidates before pagination; retained so ambiguity stays visible on every page. pub definition_candidates: usize, /// Text-matched name occurrences before pagination; excludes literal text-search matches. diff --git a/tests/intent_first_cli.rs b/tests/intent_first_cli.rs index 1f9394c..273572b 100644 --- a/tests/intent_first_cli.rs +++ b/tests/intent_first_cli.rs @@ -3621,3 +3621,147 @@ fn discover_text_or_wave2a_compact_rollup_attributes_all_languages() { let _ = fs::remove_dir_all(&dir); } + +// US-069: low-signal term advisory for literal text Search and Text OR. +const LOW_SIGNAL_ADVISORY: &str = "> Note: 450 matches across 150 of 1,000 eligible files for `frobnicate`; if this spread is not intentional, consider `overview`, a narrower term or scope, or a structural route."; + +/// Build a deterministic repo: `a/` and `b/` each hold 500 eligible source files. +/// 150 of the 1,000 files (75 per dir) carry 3 `frobnicate` matches each +/// (450 matches total), comfortably above the 400/150/1.5% advisory boundary. +fn build_low_signal_repo(name: &str) -> PathBuf { + let dir = temp_repo(name); + for sub in ["a", "b"] { + let sub = dir.join(sub); + fs::create_dir_all(&sub).unwrap(); + for i in 0..75 { + fs::write( + sub.join(format!("m{i:03}.rs")), + "fn a() { frobnicate }\nfn b() { frobnicate }\nfn c() { frobnicate }\n", + ) + .unwrap(); + } + for i in 75..500 { + fs::write(sub.join(format!("g{i:03}.rs")), "fn x() {}\n").unwrap(); + } + } + dir +} + +#[test] +fn discover_low_signal_route_coverage_and_guard() { + let dir = build_low_signal_repo("low_signal_route_guard"); + + // Explicit single-term text Search emits the exact shared advisory. + let single = srcwalk() + .args(["discover", "frobnicate", "--as", "text", "--scope"]) + .arg(&dir) + .arg("--no-budget") + .output() + .unwrap(); + assert!(single.status.success()); + let single_out = String::from_utf8_lossy(&single.stdout); + assert!(single_out.contains(LOW_SIGNAL_ADVISORY), "{single_out}"); + + // Text OR emits the same line for the triggering term. + let or = srcwalk() + .args([ + "discover", + "frobnicate,unrelated", + "--match", + "any", + "--as", + "text", + "--scope", + ]) + .arg(&dir) + .arg("--no-budget") + .output() + .unwrap(); + assert!(or.status.success()); + let or_out = String::from_utf8_lossy(&or.stdout); + assert!(or_out.contains(LOW_SIGNAL_ADVISORY), "{or_out}"); + + // Multi-scope inferred/mixed routes abstain: no explicit literal-text route + // exists, so the advisory must never appear even for a high-spread term. + let multi = srcwalk() + .args(["discover", "frobnicate", "--scope"]) + .arg(dir.join("a")) + .arg("--scope") + .arg(dir.join("b")) + .arg("--no-budget") + .output() + .unwrap(); + assert!(multi.status.success()); + let multi_out = String::from_utf8_lossy(&multi.stdout); + assert!(!multi_out.contains("eligible files"), "{multi_out}"); + + // Below-threshold term emits no advisory. + fs::write(dir.join("a/one.rs"), "fn tiny() { frobnicate }\n").unwrap(); + let below = srcwalk() + .args(["discover", "tiny", "--as", "text", "--scope"]) + .arg(&dir) + .arg("--no-budget") + .output() + .unwrap(); + let below_out = String::from_utf8_lossy(&below.stdout); + assert!(!below_out.contains("eligible files"), "{below_out}"); + + // File, access, and co-occurrence routes never emit the advisory. + for (args, scope) in [ + (vec!["discover", "*.rs", "--as", "file"], &dir), + (vec!["discover", "frobnicate", "--as", "access"], &dir), + ( + vec!["discover", "frobnicate,frobnicate", "--match", "all"], + &dir, + ), + ] { + let output = srcwalk() + .args(&args) + .arg("--scope") + .arg(scope) + .arg("--no-budget") + .output() + .unwrap(); + let out = String::from_utf8_lossy(&output.stdout); + assert!(!out.contains("eligible files"), "{args:?}\n{out}"); + } + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn discover_low_signal_budget_survives_and_replays() { + let dir = build_low_signal_repo("low_signal_budget_replay"); + + // Enough output plus a tiny budget forces body truncation; the advisory + // must survive once and stay before the final `> Next:`. + let first = srcwalk() + .args(["discover", "frobnicate", "--as", "text", "--scope"]) + .arg(&dir) + .arg("--budget") + .arg("80") + .output() + .unwrap(); + assert!(first.status.success()); + let first_out = String::from_utf8_lossy(&first.stdout); + assert_eq!( + first_out.matches(LOW_SIGNAL_ADVISORY).count(), + 1, + "advisory must appear exactly once under budget:\n{first_out}" + ); + let note_idx = first_out.find(LOW_SIGNAL_ADVISORY).unwrap(); + let next_idx = first_out.rfind("> Next:").unwrap(); + assert!(note_idx < next_idx, "advisory must precede final `> Next:`"); + + // Identical command replays byte-identically. + let second = srcwalk() + .args(["discover", "frobnicate", "--as", "text", "--scope"]) + .arg(&dir) + .arg("--budget") + .arg("80") + .output() + .unwrap(); + assert_eq!(first_out, String::from_utf8_lossy(&second.stdout)); + + let _ = fs::remove_dir_all(&dir); +} From f3020079ae4d346de8ae0335e52e2010cbc85e61 Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 22:19:46 +0700 Subject: [PATCH 24/26] chore: exclude internal story records --- .../US-065-output-compaction-file-grouping.md | 384 ---------------- ...multilanguage-owner-attribution-phase-1.md | 417 ------------------ 2 files changed, 801 deletions(-) delete mode 100644 docs/stories/US-065-output-compaction-file-grouping.md delete mode 100644 docs/stories/US-067-multilanguage-owner-attribution-phase-1.md diff --git a/docs/stories/US-065-output-compaction-file-grouping.md b/docs/stories/US-065-output-compaction-file-grouping.md deleted file mode 100644 index d2896a8..0000000 --- a/docs/stories/US-065-output-compaction-file-grouping.md +++ /dev/null @@ -1,384 +0,0 @@ -# US-065 Output Compaction: Group Repeated Paths And Hoist Stable Metadata - -## Status - -implemented — review complete; real Windows verification pending - -## Lane - -normal (with stronger validation) - -## Intake Record - -- Input type: measured output-efficiency follow-up from the Go owner-evidence - validation. -- Risk flags: existing output behavior and agent-visible public contracts; path - rendering is platform-sensitive. No matching, ranking, evidence, or semantic - relation changes. -- Implementation owner: Toby. -- Single working branch: `feat/owner-evidence-output-compaction`; continue on - this branch. Do not create a second feature branch for US-065. -- Scope split: this story ships independently before multi-language owner - attribution. Multi-language owners are explicitly out of scope here. - -## Problem Statement - -Several high-frequency navigation outputs repeat a copy-pasteable repository path -on every hit even when adjacent entries are from the same file. One discover -section spends about 25% of its bytes repeating paths. Definition output also -repeats an identical provenance line per entry even though Tests and Comments -already hoist it once per section. - -Measured redundant surfaces on `benchmark/fixtures/repos/pebble`: - -1. Text OR per-term details (`render_text_or_term_details`): every hit repeats the - full path; 10 same-file hits print the path 10 times. -2. Single-term discover Tests and Comments facets: every hit repeats the path. -3. `trace callers`: every visible call site repeats the path. -4. Discover Definitions: identical `source · kind · confidence` provenance is - printed after every definition (172 repetitions in one audit query). - -Estimated opportunity on exploratory commands: 15–25% less stdout without -removing evidence. - -## Existing Conventions To Reuse - -Do not invent a new packet grammar. Reuse these shipped shapes: - -- Discover name occurrences: `batch.go [4 name occurrences]` followed by - indented `:LINE | text` rows. -- Text OR file-rollup: one file header with indented hits and terms. -- Deps: one directory/file header with indented children. -- Assess: callers grouped by file. - -The new shape must look like these existing grouped packets. - -## Feature Shape Gate - -1. Product fit: yes — reduces context bloat in the commands agents call most. -2. Intent shape: default rendering improvement; no new command, flag, config, or - environment variable. -3. Cognitive load: none — the existing file-group convention is reused. -4. Evidence source: unchanged. Every hit, line, owner anchor, caller attribute, - and provenance tuple remains visible. -5. Output bounds: output must not grow for single-hit files; ordering, limits, - pagination, collapse pointers, and budgets remain unchanged. -6. Platform scope: displayed paths stay copy-pasteable from the current working - directory. Windows verification is mandatory. -7. Validation: unit, integration, byte-accounting, round-trip, and Windows tests. -8. Agent-facing UX: update GUIDE/README only if an affected example or stated - packet shape exists there. - -## Hard Invariants - -1. **Never shorten or strip the scope prefix from a displayed path.** Grouping - means printing the same current `rel_nonempty`/anchor path once as a file - header, not changing the path value. -2. A printed group path must remain directly copy-pasteable into `srcwalk show` - and printed `> Next:` commands from the command's working directory. -3. No hit, definition, call site, owner anchor, metadata tuple, receiver, arg - count, expansion, caveat, omission note, or pointer may disappear. -4. Preserve the current evidence order. File groups follow first appearance; - entries inside each group retain current relative order. Do not re-rank. -5. Apply current pagination, limits, top-K collapse, budgets, and omission - accounting **before** presentation grouping. Grouping must not change which - entries are visible or reachable. -6. A file with one visible entry keeps its current one-line shape. Group only - files with at least two visible entries so compaction cannot create bloat. -7. Same input and worker count produce deterministic, byte-stable output. -8. Identity-equivalence acceptance is measured with `--no-budget` (or a budget - large enough to render the complete compared slice). On budgeted paths, - compaction must never lose a previously visible entry; it may retain extra - detail that now fits inside the same budget. - -## Product Contract - -### A. Text OR Per-Term Details - -Seam: `render_text_or_term_details` in `src/commands/find.rs`. - -Current repeated shape: - -```text - path/to/file.go:10 [owner Foo@1-30] — text - path/to/file.go:20 [owner Foo@1-30] — text -``` - -Required grouped shape for two or more hits in one file: - -```text - path/to/file.go [2 matches] - :10 [owner Foo@1-30] — text - :20 [owner Foo@1-30] — text -``` - -Grouping is **conditional**: it is applied only when the grouped form is strictly -smaller in bytes than the current repeated inline form. Short paths (e.g. a -2-hit `batch.go`) can tie or grow under a group header, so such groups stay -inline to honor the no-growth invariant. Render both candidates and pick the -smaller; on a tie keep the inline (ungrouped) form. - -Single-hit files remain byte-identical to current output. - -The `[N matches]` noun is intentionally facet-local rather than copied from -`[N name occurrences]`; the evidence kind is already established by the enclosing -term section. - -#### Owner-tag compaction - -Owner information is evidence and must not be dropped. Within a multi-hit file -group: - -- A contiguous run of **three or more** hits with the exact same owner anchor - (`qualified name`, start, end) prints the owner once as a subgroup header. - K=3 is deliberate: K=2 can grow output after subgroup indentation and the - `[2 hits]` label, violating the no-growth invariant: - - ```text - [owner Foo@1-30] [3 hits] - :10 — text - :20 — text - :24 — text - ``` - -- Runs of one or two, a unique owner, mixed owner, or unattributed hit stay - inline on their hit rows. -- Only contiguous equal-owner runs may be folded; do not reorder hits to create - owner groups. -- Owner grouping is presentation-only. It must use the existing owner evidence - already attached to each hit and must not invoke new analysis. - -### B. Single-Term Tests And Comments - -Seams: Tests and Comments facet loops in -`format_search_result_with_header` (`src/search/display/mod.rs`). - -For each facet independently, group two or more visible hits from the same file: - -```text -### Tests (3) -source: ... - commit_test.go [2 matches] - :100 — first snippet - :130 — second snippet - db_test.go:50 — single-hit snippet -``` - -- Keep the existing section-level provenance behavior. -- Tests and Comments do not share a group even when paths match. -- Single-hit rows remain in their current shape. -- As in Seam A, grouping is conditional: render both candidates and pick the - strictly-smaller one; on a tie keep the inline form. - -### C. Trace Callers - -Seam: source-mode rendering in -`search_callers_expanded_with_artifact` (`src/search/callers/single.rs`). Artifact -caller grouping is already separate and is not redesigned. - -After current filtering, ranking, offset, limit, and top-K collapse select the -visible call sites, group two or more visible entries from the same file: - -```text -<- calls - pkg/file.go [2 call sites] - [fn] CallerA :40 args=1 - [fn] CallerB :72 prefix=x(type) args=2 -``` - -- Grouping occurs only on the already-selected visible page. It must not turn - `precision::K` from call sites into file groups. -- `+N more` and `--offset` pointers remain byte-identical and enumerate the same - remaining call sites. -- `--expand` source windows remain attached to the correct child call site and - retain exact source lines. -- Single call sites keep the current line shape. -- As in Seam A, grouping is conditional: render the grouped and ungrouped - candidates and pick the strictly-smaller one; on a tie keep the inline form. - `--expand` windows are included in both candidates, interleaved at the correct - child call site, so the byte comparison (and the retained source windows) stay - correct. - -### D. Definition Provenance Hoist - -Seams: compact Definitions facet in `format_compact_facet_matches` and definition -formatting/provenance helpers in `src/search/display`. - -A provenance tuple is `(source, displayed kind, confidence)`. For a Definitions -section: - -1. Select the most frequent tuple among visible definitions as the section - default; ties resolve by first occurrence. -2. Print that default once immediately below `### Definitions (N)`. -3. Do not repeat it after entries using the section default. -4. An entry with a different tuple prints its own provenance directly beneath - that entry. -5. All-mixed and one-entry cases must remain honest; no tuple may be inferred or - generalized beyond the entries that carry it. -6. The default is computed from the visible Definitions section instance for - the current invocation/page. It is deterministic per invocation and is never - cached or carried between `--offset` pages. - -The same hoist is applied to the compact `Matches — same package` (`usages_local`) -facet. Its default is chosen from the **existing rendered provenance carriers** -— one `group[0]` per path group, or a singleton row — never weighted by the -number of child hits; ties resolve to the first-seen carrier. The default is -printed once immediately below the heading, and identical per-group provenance -is suppressed. Definitions remains entry-level (each visible definition is its -own carrier). Deviations print locally. The cross-package (`usages_cross`) -section is intentionally **not** hoisted — it keeps per-group provenance. This -contract is bounded to Definitions and usages_local in this story; do not refactor -every provenance surface speculatively. - -## Design Seams - -- `src/commands/find.rs::render_text_or_term_details`: stable group-by-path plus - contiguous owner-run rendering. -- `src/search/display/mod.rs::format_search_result_with_header`: Tests/Comments - file groups and Definitions section-default provenance. -- `src/search/display/mod.rs::format_compact_facet_matches` and - `src/search/display/semantic.rs`: suppress per-entry provenance only when it - exactly equals the explicit section default. -- `src/search/callers/single.rs::search_callers_expanded_with_artifact`: group the - final visible source call-site slice, after all selection semantics. -- Use existing path functions (`rel_nonempty`, anchor display) unchanged. -- A small stable grouping helper is acceptable if it serves multiple seams - without erasing their different entry contracts. Do not force a generic - renderer abstraction merely to share a loop. - -## Acceptance Criteria - -### Correctness - -- Every pre-change visible entry maps one-to-one to a post-change entry with the - same path, line/range, text, owner, metadata, and caller fields. -- When the grouped candidate wins, a multi-hit file path appears exactly once - within its section group and child rows use `:LINE` or `:START-END` anchors. - When grouping is unprofitable or a tie, the file's exact inline rows are - retained at their original positions in the visible slice; no row is moved or - reordered. -- Single-hit files are byte-identical to current output. -- Owner runs fold only for three or more contiguous hits with the exact same - owner; K=2 stays inline, and mixed/unattributed rows stay honest. -- Definitions with uniform provenance print it once. Mixed-provenance fixtures - print the default once and each deviation locally. The same hoist applies to - the usages_local section; usages_cross keeps per-group provenance. -- Single-hit files, usages_cross groups, and non-compact paths stay byte-identical - to current output. -- Trace collapse/pagination exposes exactly the same call-site identities before - and after compaction; printed pointer commands return the same remainder. -- Group paths and printed commands round-trip when pasted from repository root, - nested scope, and Windows working directories. - -### Efficiency - -- Target: on the pinned Pebble audit command set, combined stdout bytes decrease - by 15% with identical evidence identities and omission counts. 15% is a target, - not a hard gate. Record the actual combined `--no-budget` reduction; hard - escalation is required only below 10%. A result of 10–15% is accepted honestly - with no scope chasing. -- The Text OR per-term detail section with 10 same-file hits prints the path once - and is strictly smaller. -- No representative command grows in bytes solely because of grouping. Grouping - is conditional (applied only when strictly smaller); on a tie the inline form - is kept, so grouping never grows output. -- Report bytes and o200k tokens separately; do not equate stdout bytes with API - billed tokens. - -### Compatibility - -- Non-grouped outputs, artifact callers, Text OR file-rollup mode, ranking, - matching, budgets, caps, and exit codes remain unchanged. -- Existing exact-format integration tests are updated in the same PR; unrelated - snapshots remain byte-identical. -- GUIDE/README examples are updated only where their exact output changed. - -## Pinned Validation Corpus - -Run from `benchmark/fixtures/repos/pebble` (or reproduce equivalent committed -fixtures in integration tests): - -Two explicit measurement modes are run on the pinned set. - -**Mode A — `--no-budget` (compaction KPI)**: all four commands use `--no-budget`: - -```bash -srcwalk discover 'strictWALTail,readWAL' --match any --as text --scope . --no-budget -srcwalk discover SyncWait --scope . --no-budget -srcwalk discover Set --as symbol --scope . --no-budget -srcwalk trace callers Set --scope . --no-budget -``` - -**Mode B — original/default budget**: same four commands WITHOUT `--no-budget` -(original flags). These runs prove (a) no previously visible evidence is lost and -(b) within the same budget the compact rendering retains at least as much -evidence, potentially more. Default-budget bytes are NOT the compaction KPI. - -For both modes, record before/after: - -- stdout bytes and o200k tokens; -- ordered evidence identity list `(section, path, line/range, kind, owner)`; -- path occurrence count per section; -- omission/pagination/pointer text; -- pasted `show`/pointer command success. - -If a pinned query no longer exercises the audited surface after fixture changes, -replace it with a committed minimal fixture and document the replacement; do not -relax the acceptance rule. - -## Validation Matrix - -| Layer | Required proof | -| --- | --- | -| Unit | stable first-appearance grouping; single/multi boundary; profitable/unprofitable/tie grouping decisions; interleaved order preservation (ungrouped rows keep original slice positions; profitable group emits at first occurrence); owner-run K=2 inline / K=3 folded; uniform/mixed/tied provenance defaults; carrier-majority default for usages_local; page-local default | -| Integration | exact packets for all four surfaces; single-hit byte identity; no lost evidence identities; collapse/offset/expand caller cases | -| Measurement | pinned Pebble before/after byte + o200k report in both modes (A `--no-budget` KPI, B default-budget evidence-retention); record actual reduction; hard escalation only below 10% | -| Round-trip | grouped path copied into `show`; unchanged pointer commands execute and return expected remainder | -| Platform | real Windows build/run for grouped relative, nested, and cross-directory paths | -| Release | `cargo fmt`; targeted tests; `cargo test --locked`; `cargo clippy -- -D warnings`; docs/examples aligned | - -## Windows Gate - -This story cannot be declared release-ready from Unix-only tests. On a real -Windows runner: - -1. Build srcwalk. -2. Run one grouped discover Text OR, one grouped Tests/Comments fixture, and one - grouped trace callers fixture. -3. Paste each displayed group path into `srcwalk show`. -4. Run any printed continuation pointer. -5. Confirm no slash conversion, drive-prefix, quoting, or nested-scope regression. - -Parser/string round-trip tests alone do not satisfy this gate. - -## Documentation And Release Notes - -- Release notes: “group repeated same-file hits (only when strictly smaller) and - hoist stable definition and same-package-usage provenance; evidence, ordering, - paths, and reachability unchanged.” -- No GUIDE concept is added: agents already understand file headers and `:LINE` - child rows. Update GUIDE only if an existing exact format statement/example is - invalidated. -- Update any README exact-output example touched by the implementation. - -## Out Of Scope - -- Removing, truncating, or re-ranking evidence. -- Stripping scope prefixes or shortening paths. -- Changing owner inference, owner edge inference, matching, pagination, budgets, - or collapse constants. -- Artifact caller redesign. -- Grouping every renderer in the repository. -- Multi-language owners. Follow-up plan is owners-only (no edges) for TS/JS, - Python, and Rust first; Java, C/C++, and C# second. That work requires a - separate spec and must not block this story. -- Benchmark semantic scoring; this story is presentation-preserving and is gated - by identity equivalence, byte reduction, and round-trip tests. - -## Done Bar - -US-065 is done only when all acceptance criteria pass, the actual pinned-corpus -reduction is recorded (15% target; hard escalation only below 10%; 10–15% -accepted honestly with no scope chasing), exact-format docs/tests are updated, -and real Windows verification is attached. Internal merge may precede the -Windows run only if the PR is explicitly marked not release-ready. diff --git a/docs/stories/US-067-multilanguage-owner-attribution-phase-1.md b/docs/stories/US-067-multilanguage-owner-attribution-phase-1.md deleted file mode 100644 index 172e93e..0000000 --- a/docs/stories/US-067-multilanguage-owner-attribution-phase-1.md +++ /dev/null @@ -1,417 +0,0 @@ -# US-067: Multilanguage Owner Attribution — Phase 1 - -## Status - -ready for implementation — audit conditions incorporated - -## Lane - -normal (accuracy-sensitive evidence feature) - -## Context And Release Boundary - -- Implementation owner: Toby after design audit approval. -- Review owner: Rocky; independent contract audit: Gizmo. -- Single working branch: `feat/owner-evidence-output-compaction`. Do not create a - second branch. -- This story is part of one future release bundle: existing Go owner evidence, - US-065 output compaction, and this phase-1 multilanguage owner attribution. -- The release version is intentionally undecided. Do not change Cargo/npm/lock - versions, tag, publish, push, or ship without an explicit user instruction. -- Run the real Windows gate once after this story lands, for the complete bundle. - -## Evidence-Based Scope Decision - -Owner ranges and rollups carried the measured navigation value: owner-only -rollups were consumed in 10/95 eligible historical shows, while call edges were -useful mainly in chain-shaped tasks and require language-specific binding rules. -Therefore phase 1 adds **owner attribution only** for: - -1. TypeScript/JavaScript: `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs`; -2. Python; -3. Rust. - -No call edges are inferred for these languages. A language may receive edges only -under a later evidence-backed story with its own binding and accuracy contract. - -## User Outcome - -For the existing Text OR flow, a hit inside a supported named callable shows the -same owner evidence shape already used by Go: - -```text - path/to/file.ts - owners (#N=Nth query term; *K=hits): Service.handle:20-48[#1,#3*2] -``` - -In non-compact per-term detail mode, the existing inline shape is also reused: - -```text - path/to/file.py:31 [owner Service.handle@20-48] — matched text -``` - -No new command, flag, configuration, section, trigger, or output encoding is -introduced. - -## Existing Design Seam - -Current ownership is built in `src/evidence/owner_links.rs`: - -1. `build_owner_link_evidence` groups visible Text OR hits by path. -2. Go files are parsed; `collect_file_owners` creates `OwnerAnchor`s. -3. `narrowest_owner` attributes a line to one unique narrowest callable range. -4. Go-only lexical analysis builds mechanically filtered call edges. -5. `src/commands/find.rs` renders inline tags, compact `owners (#N=...)` - rollups, and the Go call appendix. - -Phase 1 belongs at the owner-extraction boundary. It must not add language rules -inside `find.rs` or weaken the Go edge engine. - -## Core Data Contract - -### Owner regions, not only owner anchors - -Each parsed supported file produces nested callable regions of two kinds: - -```text -Named(owner anchor) -AnonymousBarrier(start_line, end_line) -``` - -For every visible hit: - -1. Find all callable regions whose inclusive line range contains the hit. -2. Select the unique narrowest range by `(end_line - start_line)`. -3. If the narrowest region is `Named`, attach that owner. -4. If it is `AnonymousBarrier`, abstain. -5. If equally narrow regions tie, abstain. - -An anonymous callable is a barrier, not merely an omitted owner node. Otherwise a -hit inside `items.map(x => ...)`, a Python lambda, or a Rust closure could fall -through and be falsely attributed to an enclosing named function. - -A named callable nested inside an anonymous barrier remains eligible within its -own narrower range. - -Region extraction must be exhaustive over **all callable node kinds** in each -version-pinned grammar. Every callable node is classified as either a supported -`Named` owner or an `AnonymousBarrier`; silently omitting a callable node is a -contract violation. Thus unsupported but callable constructs—object-literal -methods, getters/setters outside supported forms, IIFEs, prototype-assigned -functions, Python lambdas, Rust closures, and future callable kinds exposed by -the pinned grammar—cannot leak hits to an outer owner. - -Each adapter maintains a version-pinned callable-kind manifest audited against -the grammar's bundled node-type metadata. Tests must prove every manifest kind -produces exactly one region classification, and fixtures must exercise every -kind. A grammar upgrade that adds or changes a callable kind must fail this -coverage check until the adapter classifies it deliberately. - -### Anchor identity - -Every named anchor contains: - -- exact repository path; -- unqualified callable name; -- explicit display-qualified name; -- inclusive 1-indexed start/end lines from the callable AST node; -- source language. - -Qualified display identity must be separate from Go receiver/binding identity. -Do not overload `receiver_type` to encode Python, JS, or Rust containers. Existing -Go edge fields may remain Go-specific. - -Ordering and equality are deterministic over path, qualified name, and range. -No owner may render placeholder names such as `` or ``. - -### Parse failure and local error regions - -If a supported file cannot be read, produces no tree, or its root node itself is -an `ERROR`, preserve all raw text hits and emit no owner evidence for that file. -For a partial tree with local `ERROR` or missing-node descendants: - -1. Record every error/missing byte range and inclusive line range. -2. A callable whose byte range overlaps any error range is replaced by an - `AnonymousBarrier` covering the full callable; it is never a `Named` owner. -3. An error range outside a callable is itself an abstention barrier, so a hit on - an error-overlapping line cannot fall through to an enclosing owner. -4. Named regions with no error overlap remain eligible. - -Because Text OR hit inputs are line-based, any hit line intersecting an error -range abstains even when the parser provides narrower columns. Never recover -owner names from signatures, indentation, regexes, or raw-line guessing. - -## Language Contracts - -### A. TypeScript And JavaScript Family - -Use the grammar selected by the existing `Lang`/extension routing, including the -TSX grammar for `.tsx` and JavaScript grammar for JS/JSX/MJS/CJS. - -#### Supported named owners - -1. Named function and generator declarations: `load`. -2. Class methods with a static/simple/private identifier name: - `Service.handle`, `Service.#reset`. -3. A direct variable declarator with a simple identifier whose initializer is an - arrow or function expression: `load`. -4. A class field with a simple/private property name whose direct value is an - arrow or function expression: `Service.handle`. -5. A function expression with an explicit name may use that explicit name when - no supported binding/property owner exists. -6. Nested supported named callables append lexical containers with `.`: - `outer.inner`, `Service.handle.inner`. -7. TypeScript namespace/internal-module and ECMAScript module-block lexical - containers append with `.` (for example `Api.load`) but are not callable - owners themselves. This prevents equal unqualified names in separate - namespaces from conflating. - -Transparent syntax wrappers such as `export`, `default`, TypeScript annotations, -and decorators do not become containers and do not change the callable node -range. - -#### Required abstentions/barriers - -- Inline anonymous arrows/functions used as call arguments, returns, array/object - elements, JSX expressions, or assignment targets without a supported simple - binding/property name. -- Computed method/property names whose stable source name is not a simple or - private identifier. -- Overload signatures or declarations without a body. -- Any construct whose class/binding container cannot be read structurally. -- Object-literal methods/accessors, IIFEs, and prototype/member-assigned function - expressions are barriers unless they independently satisfy a supported named - binding form above. - -Do not invent labels such as `callback@42`, ``, property text, or a callee -name from the surrounding call. - -### B. Python - -#### Supported named owners - -1. Synchronous and asynchronous `function_definition` nodes. -2. Class methods: `Service.handle`. -3. Nested classes and functions use their complete lexical hierarchy with `.`: - `Outer.Inner.handle`, `outer.inner`, `Outer.method.inner`. - -The anchor range starts at the underlying `def`/`async def` node and ends at its -body. A `decorated_definition` wrapper is transparent: decorator lines are not -inside the callable owner range, and a hit in a decorator expression is not -attributed to the decorated function. - -#### Required abstentions/barriers - -- Every `lambda` is an anonymous barrier. -- A malformed decorated definition or a callable with no structural name - abstains. -- Do not infer class/function hierarchy from indentation or rendered signatures. - -### C. Rust - -#### Supported named owners - -1. Top-level body-bearing `function_item`: `run`. -2. Lexically nested functions/modules use Rust `::`: `outer::inner`, - `server::run`. -3. Inherent impl method: `Type::method`. -4. Trait default/body method: `Trait::method`. -5. Trait implementation method: `::method`. - -For impl names, read the AST `type` and optional `trait` fields. Preserve their -trimmed source spelling. Collapse every non-empty run recognized by Rust -`str::split_whitespace` to exactly one ASCII space; preserve all other source -tokens and punctuation. Do not semantically resolve aliases or modules. Examples: - -```text -impl Store => Store::get -impl Cache for Store => as Cache>::get -``` - -The trait-qualified form is binding: it prevents a trait method from being -presented as the same owner as an inherent method with the same name. - -#### Required abstentions/barriers - -- Every closure expression is an anonymous barrier. -- Trait signatures and extern declarations without bodies are not owners. -- If an impl target or trait name cannot be extracted structurally, its methods - abstain rather than fall back to an unqualified name. -- Macro-generated owners are not inferred from expanded or guessed source. - -## Rendering And Trigger Parity - -- Run attribution in the same existing Text OR flow and at the same point after - filtering/pagination as Go. -- Existing compact selection remains unchanged: compact file rollup is selected - by the current term/match thresholds (including three-or-more terms); otherwise - existing per-term detail rows are used. -- Reuse `OwnerAnchor`, inline `[owner ...@START-END]`, and - `owners (#N=Nth query term; *K=hits)` rendering. -- Preserve US-065 conditional file grouping and K=3 repeated-owner folding. -- Preserve path rendering, term indices, count multipliers, ordering, caps, - budgets, and omission accounting. -- Artifact mode continues to abstain exactly as today. - -### Capability-honest call appendix - -Owner attribution support and edge-analysis support are separate capabilities. - -- New-language owners never populate `OwnerCallEvidence`. -- `## Mechanical Go calls`, its zero-edge sentence, and its call-specific caveat - are driven only by Go owner/edge analysis. -- A non-Go-only result must not say “No direct name-level call evidence...”; - absence means unsupported analysis, not measured zero. -- A mixed-language query may render non-Go owner rollups plus a Go-only mechanical - appendix, but that appendix must remain explicitly labeled Go. -- Existing Go-only output stays byte-identical. -- Non-Go owner output includes one concise honesty caveat stating that ranges are - structural lexical ownership candidates, not runtime ownership or binding - proof. It must not imply call analysis ran. - -The evidence model should carry the capability/attempt distinction explicitly; -do not infer it from `edges.is_empty()`. - -## Implementation Shape - -Keep orchestration and Go edges in `owner_links.rs`, but do not add three large -parser implementations to that already-large file. Add focused owner extractors, -for example: - -```text -src/evidence/owners/mod.rs -src/evidence/owners/js_ts.rs -src/evidence/owners/python.rs -src/evidence/owners/rust.rs -``` - -A small shared walker for `Named`/`AnonymousBarrier`, lexical container stacks, -and unique-narrowest selection is appropriate. Language-specific node kinds, -field extraction, and qualified naming stay in their adapter. - -Do not refactor unrelated outline, caller, callee, qualified-symbol, or semantic -search logic. Existing outline entries may be reused only where they preserve the -contracts above; direct AST extraction is required for barriers, decorators, and -Rust impl identity. - -## Correctness Invariants - -1. Raw matches, ranking, pagination, and omission counts are identical with - attribution enabled or abstaining. -2. Every attributed hit has exactly one structurally containing callable range. -3. The displayed qualified name and inclusive range match source exactly. -4. The narrowest callable region wins; ties and anonymous barriers abstain. -5. Parse errors and unsupported name forms produce no owner evidence, never a - fallback guess. -6. No new-language edge or zero-edge claim is rendered. -7. Existing Go attribution, Go edges, output, and tests remain byte-identical. -8. Same source and visible hit slice produce deterministic byte-stable output. -9. TS/JS family extensions route through the correct existing grammar. -10. Scope-relative and Windows path behavior remains unchanged. - -## Accuracy Suite - -Create curated table-driven fixtures per language adapter. “0 wrong” cannot be -satisfied by abstaining everywhere. - -### Per-language minimum - -For each of JS/TS family, Python, and Rust: - -- at least 60 positive hit assertions across supported owner forms; -- at least 20 explicit abstention assertions across anonymous barriers, - unsupported names, body-less declarations, malformed source, and equal-range - ambiguity where applicable; -- 100% of required supported-form positives attributed; -- 100% exact qualified names and inclusive ranges; -- 0 false attributions; -- deterministic output under repeated runs; -- 100% callable-kind manifest coverage against the pinned grammar node metadata; - every callable kind classified as `Named` or `AnonymousBarrier`. - -The JS/TS curated matrix must contain `.ts`, `.tsx`, `.js`, and `.jsx` fixtures, -not only one grammar. Include nested named callables inside and outside anonymous -barriers. Python must include decorated async methods and nested class/def -hierarchies. Rust must include inherent impl, trait default method, trait impl, -generics, modules, nested functions, and closures. - -Add cross-language orchestration tests proving one Text OR query can attribute -supported files while preserving raw hits from malformed/unsupported files. - -## Real-Repository Replay - -Use the already-pinned benchmark repositories and SHAs: - -| Language | Repository | SHA | -| --- | --- | --- | -| TypeScript | Effect | `9245bc59ebfa688e8c92dd691296ee69d0815e59` | -| JavaScript | Express | `1140301f6a0ed5a05bc1ef38d48294f75a49580c` | -| Python | FastAPI | `6fa573ce0bc16fe445f93db413d20146dd9ff35d` | -| Rust | ripgrep | `0a88cccd5188074de96f54a4b6b44a63971ac157` | - -Predeclare at least one three-term Text OR query per repository before examining -candidate results. If the first query yields fewer than 50 attributed hit-owner -pairs, add another query and record why; do not cherry-pick only easy owners. - -For each repository, audit attributed pairs in deterministic -`(path,line,qualified_name,start,end)` order. Start with the first 50, which must -span at least 10 distinct files. If they do not, continue in the same order until -10 files are represented and audit every additional pair traversed; never skip -pairs to manufacture spread. - -- required result: every audited pair has exact range containment and - qualified-name correctness (at least 50 pairs across at least 10 files); -- required false-attribution count: 0; -- record total raw hits, attributed hits, barrier abstentions observed, parse-error - abstentions, and distinct owner forms; -- report attribution rate descriptively, not as a quality score. - -Also replay the same commands twice and require byte-identical owner rollups. -No new model A/B is required: this gate proves attribution accuracy, while prior -experiments already established owner-value demand. - -## Regression And Verification Matrix - -| Layer | Required proof | -| --- | --- | -| Unit | Per-language 60 positive + 20 abstention assertions; callable-kind manifest 100%; exact names/ranges; barriers; local errors; deterministic ties | -| Integration | Existing trigger parity; compact and detail shapes; mixed languages; artifact abstention; no non-Go edge/zero-edge claim | -| Go regression | Existing Go exact outputs and complete Go owner/edge suite byte-identical | -| Real repos | Effect/Express/FastAPI/ripgrep deterministic audit; ≥50 pairs and ≥10 files each; 0 false attribution | -| Build | `cargo fmt`; `cargo fmt --check`; targeted tests; `cargo test --locked`; `cargo clippy -- -D warnings` | -| npm | `node npm/install.test.js`; `(cd npm && npm pack --dry-run)` if package metadata or release surface changes | -| Platform | One real Windows build/run after phase 1, covering Go plus TS/Python/Rust owner paths and pasted `show` anchors | - -## Documentation - -After behavior is verified: - -- Update GUIDE language scope and state explicitly that call edges remain Go-only. -- Update README only if an existing language-support/output statement becomes - incomplete; do not add speculative examples. -- Keep CHANGELOG under `Unreleased` and draft one bundled release note covering - Go owners/edges, US-065 compaction, and phase-1 owner-only languages. -- Do not choose or write a release version until the user decides it. - -## Out Of Scope - -- Call edges for TypeScript/JavaScript, Python, or Rust. -- Dynamic dispatch, callback target, dependency-injection, protocol, trait-object, - import, or binding resolution. -- New flags, config, intent classifier, trigger thresholds, caps, or ranking. -- C, C++, Java, C#, or any phase-2 language. -- Anonymous-owner synthetic names. -- Semantic module/package inference from paths. -- New model A/B runs. -- Version bump, tag, publish, push, or release. - -## Done Bar - -Implementation is complete only when the curated matrices and callable-kind -manifests pass with 0 false attributions, all four deterministic real-repo audits -cover at least 50 pairs across at least 10 files with every audited pair exact, -Go output is unchanged, docs describe owner-only language scope honestly, and -full local verification passes. The complete release bundle is only -release-eligible after the real Windows gate; actual versioning and shipping -still require an explicit -user command. From b1184266acb1cef4097952de97b3cf88caa46f01 Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 22:25:33 +0700 Subject: [PATCH 25/26] test: expect normalized Windows owner paths --- src/commands/find.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/commands/find.rs b/src/commands/find.rs index ce97c09..caf65f9 100644 --- a/src/commands/find.rs +++ b/src/commands/find.rs @@ -2216,16 +2216,27 @@ mod tests { 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, r"C:\repo\pkg\a.go"); + assert_eq!(e0.call_file, expected_call_file); assert_eq!(e0.call_line, 22); - assert_eq!(e0.cand_file, r"C:\repo\pkg\a.go"); + 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, r"C:\repo\pkg\a.go"); + assert_eq!(e1.call_file, expected_call_file); assert_eq!(e1.call_line, 12); - assert_eq!(e1.cand_file, r"C:\repo\pkg\sub.go"); + assert_eq!(e1.cand_file, expected_candidate_file); assert_eq!(e1.def_range, "7-20"); } From 9bea1994d12a02b8afb43dc6f6e5995ea392032c Mon Sep 17 00:00:00 2001 From: sting8k Date: Wed, 12 Aug 2026 22:38:01 +0700 Subject: [PATCH 26/26] chore(release): prepare 1.6.0 --- CHANGELOG.md | 2 +- Cargo.lock | 2 +- Cargo.toml | 2 +- npm/package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bf377c8..1ef9d08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ 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. 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/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"