From 68632764662f3890103bd67c0dd717fd54ec206e Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Sun, 30 Aug 2026 05:04:36 -0400 Subject: [PATCH 01/33] analysis(rust): model custom test harnesses and registered test-producers Add a bounded, repository-governed Rust test-harness registry ([analysis.test_harnesses] in ripr.toml, #3532). Registration is exact configuration only - never inferred from filenames, imports, macro suffixes, or function names - and fails closed at parse time on unknown adapter versions, kind/adapter mismatches, root escapes, lookalike markers, and duplicate/conflicting registrations. Two families are supported end to end: - custom_harness + libtest_mimic_v1: an exact [[test]] harness = false target is evidence role; its members become HarnessHelper (inert #[test] attributes never enter the executable-test denominator) and the adapter establishes one subject per exact token-anchored Trial::test("name", ...) registration (works inside vec![] token trees), with dynamic names, loop-driven registration, unanchored or ambiguously imported Trial paths, and duplicate names staying typed limitations. - registered_attribute + exact_attribute_v1: functions carrying the exact registered attribute path (spelled fully or bound by a top-level use resolving to the marker) become RegisteredTestAttribute executable tests through the shared #3531 role authority; lookalike spellings and same-named unrelated imports never classify. Subject facts carry harness kind, adapter generation, provenance, subject identity, a claim (named_invocation | named_function), and a named_unexecuted selector capability - no passive analysis starts Cargo or a harness. Harness targets join the workspace source-role context (opt-in still wins), the diff and repo pipelines consume the registry, the LSP scope partition stays converged, and check JSON gains a conditional test_harnesses projection that is absent without registrations (byte-identical output; zero golden drift). The per-file fact cache stays at 0.7: registry roles are derived post-cache on every run, so the on-disk fact shape is unchanged. Closes #3532 --- CHANGELOG.md | 17 + .../src/analysis/facts/harness_registry.rs | 837 ++++++++++++++++++ .../analysis/facts/harness_registry/tests.rs | 655 ++++++++++++++ crates/ripr/src/analysis/facts/mod.rs | 23 +- crates/ripr/src/analysis/facts/model.rs | 147 ++- .../src/analysis/facts/parameterized_tests.rs | 12 +- crates/ripr/src/analysis/facts/test_styles.rs | 2 +- .../src/analysis/facts/test_styles/tests.rs | 16 +- .../src/analysis/git_candidate_execution.rs | 2 + .../ripr/src/analysis/harness_projection.rs | 85 ++ crates/ripr/src/analysis/language/adapter.rs | 6 + .../ripr/src/analysis/language/perl/tests.rs | 1 + crates/ripr/src/analysis/language/python.rs | 4 + .../analysis/language/python/python_tests.rs | 6 + crates/ripr/src/analysis/language/rust.rs | 171 +++- .../src/analysis/language/typescript/mod.rs | 2 + .../src/analysis/language/typescript/tests.rs | 5 + crates/ripr/src/analysis/mod.rs | 18 + crates/ripr/src/analysis/pipeline.rs | 27 + crates/ripr/src/analysis/rust_index.rs | 3 +- crates/ripr/src/analysis/seam_inventory.rs | 75 +- crates/ripr/src/analysis/syntax/mod.rs | 2 +- crates/ripr/src/analysis/syntax/ra.rs | 12 +- .../src/analysis/workspace/source_role.rs | 69 +- crates/ripr/src/app.rs | 5 + crates/ripr/src/app/check.rs | 1 + crates/ripr/src/app/check/options_builder.rs | 1 + crates/ripr/src/app/check/output_builder.rs | 1 + crates/ripr/src/app/check_artifact.rs | 9 +- crates/ripr/src/app/tests/mod.rs | 1 + crates/ripr/src/config.rs | 112 ++- crates/ripr/src/config/model.rs | 176 +++- crates/ripr/src/config/tests.rs | 121 +++ crates/ripr/src/lsp/diagnostics.rs | 6 + crates/ripr/src/output/badge/tests.rs | 2 + crates/ripr/src/output/diff_report.rs | 4 + crates/ripr/src/output/github.rs | 5 + crates/ripr/src/output/human.rs | 36 + crates/ripr/src/output/json/mod.rs | 8 + crates/ripr/src/output/json/report.rs | 200 +++++ crates/ripr/src/output/next_step.rs | 1 + crates/ripr/src/output/render.rs | 1 + crates/ripr/src/output/sarif.rs | 1 + docs/OUTPUT_SCHEMA.md | 63 ++ docs/specs/RIPR-SPEC-0153-rust-source-role.md | 8 +- policy/no-panic-allowlist.toml | 4 +- policy/public_api.txt | 3 + 47 files changed, 2914 insertions(+), 52 deletions(-) create mode 100644 crates/ripr/src/analysis/facts/harness_registry.rs create mode 100644 crates/ripr/src/analysis/facts/harness_registry/tests.rs create mode 100644 crates/ripr/src/analysis/harness_projection.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 04dfa6b7d84..d93b6ef126b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,23 @@ are scoped or reviewed. ### Added +- New repository-governed Rust test-harness registry + (`[analysis.test_harnesses]` in `ripr.toml`): repositories can teach + ripr, through exact registrations only, about bounded custom test + harnesses and test-producing source forms. A registered + `harness = false` custom target (libtest-mimic adapter) is evidence + role whose exact source-visible `Trial::test("name", ...)` trials with + stable names become the executable subjects, its inert `#[test]` + attributes never enter the test denominator, and one exact registered + test-producing attribute is classified through the shared source-role + authority. Subject facts carry harness kind, adapter generation, + provenance, subject identity, and a named-unexecuted selector + capability; dynamic trial names, loop-driven registration, ambiguous + imports, lookalike markers, stale or conflicting registrations, and + unknown adapter versions are named fail-closed limitations. Check JSON + gains a `test_harnesses` projection only when registrations exist + ([#3532](https://github.com/EffortlessMetrics/ripr-swarm/issues/3532)). + - New `ripr mcp --stdio [--root PATH]` command: a bounded, read-only Model Context Protocol server that exposes exact workspace status (`ripr_workspace_status` tool and `ripr://workspace/status` resource) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs new file mode 100644 index 00000000000..bef411adce5 --- /dev/null +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -0,0 +1,837 @@ +//! Repository-governed Rust test-harness registry (#3532). +//! +//! This module is the one authority that turns exact +//! `[analysis.test_harnesses]` registrations into typed source facts. It +//! runs once per index build, after the parameterized-test promotion and +//! the test-styles normalizer, so every downstream consumer (diff probes, +//! seam inventory, evidence relation, test selectors, projections) reads +//! the same derived facts. +//! +//! The authority model keeps the required distinctions apart: +//! +//! - a registered custom target is evidence-role, but NOT every function +//! in it is an executable test — members carry +//! [`FunctionSourceRole::HarnessHelper`] and only adapter-established +//! subjects register `TestFact`s; +//! - a registered macro/attribute invocation is a test container, but +//! RIPR did not expand every generated case — subjects state their +//! [`HarnessSubjectClaim`]; +//! - a known selector route ([`HarnessSelectorCapability::NamedUnexecuted`]) +//! is not a selector that ran — passive analysis never starts Cargo or +//! a harness; +//! - unregistered or ambiguous harnesses become typed limitations — +//! never production reclassification and never executable-test +//! optimism. +//! +//! Everything here is exact-match on configured inputs. There is no +//! inference from filenames, crate imports, macro suffixes, or function +//! names, and a registration that names a file outside the analyzed +//! index simply grants nothing (fail closed). + +use super::model::{FunctionFact, FunctionSourceRole, RustIndex, TestFact}; +use super::test_styles::normalized_test_attribute_path as normalized_attribute_path; +use super::{ + HarnessLimitationFact, HarnessSelectorCapability, HarnessSubjectClaim, HarnessSubjectFact, +}; +use crate::analysis::rust_index::{ + OracleFact, classify_assertion, extract_call_facts, extract_identifier_tokens, + extract_literal_facts, +}; +use crate::analysis::syntax::ra::{LineIndex, parser_oracles_for_function, slice_text}; +use crate::config::{TestHarnessAdapter, TestHarnessKind, TestHarnessRegistration}; +use ra_ap_syntax::ast::{self, HasName}; +use ra_ap_syntax::{AstNode, Edition, SourceFile, TextSize}; +use std::collections::BTreeSet; +use std::path::Path; + +/// Apply every registration whose target file is present in the index. +/// Registrations for files outside the analyzed set grant nothing. +/// +/// Empty registrations leave the index untouched (no-op), so +/// repositories without registrations keep every existing output. +pub(super) fn apply_registrations( + index: &mut RustIndex, + registrations: &[TestHarnessRegistration], +) { + if registrations.is_empty() { + return; + } + let mut subjects = Vec::new(); + let mut limitations = Vec::new(); + for registration in registrations { + // Exact target identity only: a registration whose file is not in + // this index (stale, wrong package, unanalyzed scope) applies to + // nothing here. + let Some(facts) = index.files.get(®istration.target) else { + continue; + }; + let source = facts.source.clone(); + match (registration.kind, registration.adapter) { + (TestHarnessKind::CustomHarnessTarget, TestHarnessAdapter::LibtestMimicV1) => { + apply_libtest_mimic_target( + index, + registration, + &source, + &mut subjects, + &mut limitations, + ) + } + (TestHarnessKind::RegisteredAttribute, TestHarnessAdapter::ExactAttributeV1) => { + apply_registered_attribute( + index, + registration, + &source, + &mut subjects, + &mut limitations, + ) + } + // The config parser rejects unknown kind/adapter pairs, so this + // arm is unreachable today; if it ever becomes reachable the + // safe behavior is to grant nothing. + _ => {} + } + } + subjects.sort_by(|left, right| { + left.file + .cmp(&right.file) + .then(left.start_line.cmp(&right.start_line)) + .then(left.end_line.cmp(&right.end_line)) + .then(left.name.cmp(&right.name)) + }); + limitations.sort_by(|left, right| { + left.file + .cmp(&right.file) + .then(left.line.cmp(&right.line)) + .then(left.code.cmp(&right.code)) + .then(left.detail.cmp(&right.detail)) + }); + limitations.dedup(); + index.harness_subjects = subjects; + index.harness_limitations = limitations; +} + +/// libtest-mimic adapter, generation 1 (#3532). +/// +/// Establishes one subject per exact source-visible trial registration +/// with a stable string-literal name (`Trial::test("name", ...)`), where +/// the `Trial` path is anchored to the registered marker crate path — +/// either spelled fully qualified (`::Trial::test`) or bound by a +/// top-level `use` whose path resolves to `::Trial`. Discovery +/// runs over the file's token stream, so trial registrations inside +/// collection macros (`vec![...]`) are still exact token matches, while +/// everything the issue names as a limitation stays one: +/// +/// - dynamic (non-literal) trial names; +/// - trial registration inside a loop (runtime-only discovery); +/// - unanchored or ambiguously imported `Trial` paths; +/// - duplicate trial names (two subject claims on one identity). +fn apply_libtest_mimic_target( + index: &mut RustIndex, + registration: &TestHarnessRegistration, + source: &str, + subjects: &mut Vec, + limitations: &mut Vec, +) { + let target = registration.target.clone(); + demote_harness_target_functions(index, &target); + let parse = SourceFile::parse(source, Edition::CURRENT); + if !parse.errors().is_empty() { + limitations.push(HarnessLimitationFact { + registration_id: registration.registration_id.clone(), + code: "parse_unavailable".to_string(), + file: target, + line: 1, + detail: "the registered harness target did not parse; no trial subjects were established (fail closed)".to_string(), + }); + return; + } + let line_index = LineIndex::new(source); + let trial_bindings = top_level_use_bindings(parse.tree().syntax(), "Trial"); + let tokens: Vec = parse + .tree() + .syntax() + .descendants_with_tokens() + .filter_map(|element| element.into_token()) + .collect(); + let mut claimed_names = BTreeSet::new(); + + for position in 0..tokens.len() { + let Some(matched) = match_trial_path(&tokens, position, ®istration.marker) else { + continue; + }; + let line = line_index.line(tokens[position].text_range().start()); + // Anchoring: the bare `Trial` form needs a top-level import bound + // from exactly the marker path; the qualified form carries the + // marker in the path itself. + if !matched.qualified { + match resolve_trial_binding(&trial_bindings, ®istration.marker) { + TrialBindingResolution::MarkerAnchored => {} + TrialBindingResolution::Ambiguous { conflicting } => { + limitations.push(HarnessLimitationFact { + registration_id: registration.registration_id.clone(), + code: "ambiguous_import".to_string(), + file: target.clone(), + line, + detail: format!( + "bare `Trial::test` cannot be tied to marker `{}`; conflicting imports bind Trial from ({conflicting})", + registration.marker + ), + }); + continue; + } + TrialBindingResolution::Unbound => { + limitations.push(HarnessLimitationFact { + registration_id: registration.registration_id.clone(), + code: "unanchored_trial_path".to_string(), + file: target.clone(), + line, + detail: format!( + "`Trial::test` has no top-level import bound from marker `{}`; the invocation is not classified", + registration.marker + ), + }); + continue; + } + } + } + + if in_loop(tokens[position].parent_ancestors()) { + limitations.push(HarnessLimitationFact { + registration_id: registration.registration_id.clone(), + code: "dynamic_trial_registration".to_string(), + file: target.clone(), + line, + detail: "trial registration runs inside a loop; runtime-discovered trials remain unresolved".to_string(), + }); + continue; + } + let Some(name_token) = tokens.get(matched.name_token_index) else { + continue; + }; + let Some(name) = string_literal_token_text(name_token) else { + limitations.push(HarnessLimitationFact { + registration_id: registration.registration_id.clone(), + code: "dynamic_trial_name".to_string(), + file: target.clone(), + line: line_index.line(name_token.text_range().start()), + detail: + "trial name is not a simple string literal; generated names remain unresolved" + .to_string(), + }); + continue; + }; + if !claimed_names.insert(name.clone()) { + limitations.push(HarnessLimitationFact { + registration_id: registration.registration_id.clone(), + code: "duplicate_subject".to_string(), + file: target.clone(), + line, + detail: format!( + "trial name `{name}` is registered more than once; conflicting subject claims fail closed" + ), + }); + continue; + } + // The subject span runs from the trial path to the balanced + // closing parenthesis of the registration call. + let Some(end_offset) = balanced_call_end(&tokens, matched.open_paren_index) else { + continue; + }; + let start: TextSize = tokens[position].text_range().start(); + let start_line = line_index.line(start); + let end_line = line_index.line_for_range_end(TextSize::new(end_offset)); + let body = slice_text(source, start, TextSize::new(end_offset)); + let calls = extract_call_facts(&body, start_line); + let literals = extract_literal_facts(&body, start_line); + let assertions = + parser_oracles_for_node_tokens(&tokens, matched.name_token_index, start_line); + let subject = HarnessSubjectFact { + registration_id: registration.registration_id.clone(), + harness_kind: registration.kind.as_str().to_string(), + adapter: registration.adapter.as_str().to_string(), + marker: registration.marker.clone(), + name: name.clone(), + file: target.clone(), + start_line, + end_line, + body: body.clone(), + calls: calls.clone(), + assertions: assertions.clone(), + literals: literals.clone(), + selector: HarnessSelectorCapability::NamedUnexecuted, + claim: HarnessSubjectClaim::NamedInvocation, + provenance: TestHarnessRegistration::provenance().to_string(), + }; + let test = TestFact { + name, + file: target.clone(), + start_line, + end_line, + body, + calls, + assertions, + literals, + attrs: Vec::new(), + }; + subjects.push(subject); + push_file_test(index, &target, test.clone()); + index.tests.push(test); + } +} + +/// The exact token shapes this adapter matches at `position`: +/// `Trial :: test (` (bare, import-anchored) or +/// `::Trial :: test (` (qualified). Path separators count as +/// either one `::` token or two `:` tokens — inside macro token trees +/// (`vec![...]`) the raw punctuation form is what the tokenizer emits. +/// Returns the index of the first argument token and whether the +/// qualified form matched. +fn match_trial_path( + tokens: &[ra_ap_syntax::SyntaxToken], + position: usize, + marker: &str, +) -> Option { + let text = |index: usize| tokens.get(index).map(|token| token.text()); + let is_ident_eq = + |index: usize, expected: &str| text(index).is_some_and(|value| value == expected); + let l_paren = |index: usize| { + tokens + .get(index) + .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::L_PAREN) + }; + // Length of the path separator starting at `index`: 1 for `::`, 2 for + // `:` `:`, or None. + fn separator(tokens: &[ra_ap_syntax::SyntaxToken], index: usize) -> Option { + match tokens.get(index).map(|token| token.kind()) { + Some(ra_ap_syntax::SyntaxKind::COLON2) => Some(1), + Some(ra_ap_syntax::SyntaxKind::COLON) + if tokens + .get(index + 1) + .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::COLON) => + { + Some(2) + } + _ => None, + } + } + + for qualified in [false, true] { + let mut segments: Vec<&str> = if qualified { + marker.split("::").collect() + } else { + Vec::new() + }; + segments.push("Trial"); + segments.push("test"); + let mut cursor = position; + let mut matched_segments = 0usize; + for segment in &segments { + if !is_ident_eq(cursor, segment) { + break; + } + cursor += 1; + matched_segments += 1; + if matched_segments < segments.len() { + let Some(width) = separator(tokens, cursor) else { + break; + }; + cursor += width; + } + } + if matched_segments == segments.len() && l_paren(cursor) { + return Some(TrialPathMatch { + qualified, + name_token_index: cursor + 1, + open_paren_index: cursor, + }); + } + } + None +} + +struct TrialPathMatch { + qualified: bool, + name_token_index: usize, + open_paren_index: usize, +} + +/// Offset just past the `)` balancing the `(` at `open_paren_index`, +/// bounded to the token stream. `None` (unbalanced) means the span is not +/// provable and the match is skipped. +fn balanced_call_end(tokens: &[ra_ap_syntax::SyntaxToken], open_paren_index: usize) -> Option { + let mut depth: usize = 0; + for token in &tokens[open_paren_index..] { + match token.kind() { + ra_ap_syntax::SyntaxKind::L_PAREN => depth += 1, + ra_ap_syntax::SyntaxKind::R_PAREN => { + depth = depth.checked_sub(1)?; + if depth == 0 { + let end: u32 = token.text_range().end().into(); + return Some(end); + } + } + _ => {} + } + } + None +} + +/// Assertion evidence for one trial subject: the exact assertion-macro and +/// `unwrap`/`expect` tokens inside the registration's own argument span. +/// Only tokens between the name argument and the balanced close count, so +/// adjacent code never credits this subject. +fn parser_oracles_for_node_tokens( + tokens: &[ra_ap_syntax::SyntaxToken], + name_token_index: usize, + start_line: usize, +) -> Vec { + let mut assertions = Vec::new(); + let mut depth: usize = 1; + let mut index = name_token_index + 1; + let line_offset = start_line.saturating_sub(1); + while index < tokens.len() && depth > 0 { + let token = &tokens[index]; + match token.kind() { + ra_ap_syntax::SyntaxKind::L_PAREN => depth += 1, + ra_ap_syntax::SyntaxKind::R_PAREN => depth = depth.saturating_sub(1), + ra_ap_syntax::SyntaxKind::IDENT => { + let name = token.text(); + if !is_assertion_macro_name(name) { + index += 1; + continue; + } + // assert!(..) / assert_eq!(..) — the bang and token tree + // follow; the assertion text is the macro invocation. + let mut text = name.to_string(); + let mut cursor = index + 1; + if tokens + .get(cursor) + .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::BANG) + { + text.push('!'); + cursor += 1; + if tokens + .get(cursor) + .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::L_PAREN) + { + let mut macro_depth = 1; + cursor += 1; + while cursor < tokens.len() && macro_depth > 0 { + let inner = &tokens[cursor]; + match inner.kind() { + ra_ap_syntax::SyntaxKind::L_PAREN => macro_depth += 1, + ra_ap_syntax::SyntaxKind::R_PAREN => macro_depth -= 1, + _ => {} + } + text.push_str(inner.text()); + cursor += 1; + } + text.push(')'); + } + } + let classification = classify_assertion(&text); + assertions.push(OracleFact { + line: line_offset + 1, + kind: classification.kind, + strength: classification.strength, + observed_tokens: extract_identifier_tokens(&text), + text, + }); + } + _ => {} + } + index += 1; + } + assertions.sort_by(|left, right| left.line.cmp(&right.line).then(left.text.cmp(&right.text))); + assertions +} + +fn is_assertion_macro_name(name: &str) -> bool { + matches!( + name, + "assert" | "assert_eq" | "assert_ne" | "assert_matches" | "matches" + ) || name.starts_with("insta::assert") + || name.contains("snapshot") +} +/// Exact registered test-producing attribute adapter, generation 1 +/// (#3532). Promotes functions carrying the exact registered attribute +/// path through the shared #3531 role authority. The attribute must +/// either be spelled as the full registered path (`#[]`) or bound +/// in the target file by a top-level `use` resolving to the marker; a +/// lookalike spelling or a same-named unrelated import never classifies. +fn apply_registered_attribute( + index: &mut RustIndex, + registration: &TestHarnessRegistration, + source: &str, + subjects: &mut Vec, + limitations: &mut Vec, +) { + let target = registration.target.clone(); + let parse = SourceFile::parse(source, Edition::CURRENT); + let use_bindings = if parse.errors().is_empty() { + top_level_use_bindings(parse.tree().syntax(), marker_leaf(®istration.marker)) + } else { + limitations.push(HarnessLimitationFact { + registration_id: registration.registration_id.clone(), + code: "parse_unavailable".to_string(), + file: target.clone(), + line: 1, + detail: "the registered attribute target did not parse; no registered subjects were established (fail closed)".to_string(), + }); + BTreeSet::new() + }; + let promoted_functions: Vec<(usize, String, TestFact, HarnessSubjectFact)> = { + let Some(facts) = index.files.get(&target) else { + return; + }; + let mut promoted = Vec::new(); + for function in &facts.functions { + let Some(resolution) = + resolve_registered_attribute(&function.attrs, ®istration.marker, &use_bindings) + else { + continue; + }; + let line = match resolution { + RegisteredAttributeResolution::Matched => function.start_line, + RegisteredAttributeResolution::Ambiguous { detail } => { + limitations.push(HarnessLimitationFact { + registration_id: registration.registration_id.clone(), + code: "ambiguous_import".to_string(), + file: target.clone(), + line: function.start_line, + detail, + }); + continue; + } + RegisteredAttributeResolution::Unresolved { detail } => { + limitations.push(HarnessLimitationFact { + registration_id: registration.registration_id.clone(), + code: "unresolved_marker_import".to_string(), + file: target.clone(), + line: function.start_line, + detail, + }); + continue; + } + }; + // Built-in exact test attributes keep precedence: the function + // is already an executable test and must not register twice + // (#3499's families continue to work without duplicate + // registry entries). + if function.source_role.registers_executable_test() { + continue; + } + let test = registered_attribute_test_fact(function); + let subject = HarnessSubjectFact { + registration_id: registration.registration_id.clone(), + harness_kind: registration.kind.as_str().to_string(), + adapter: registration.adapter.as_str().to_string(), + marker: registration.marker.clone(), + name: function.name.clone(), + file: target.clone(), + start_line: function.start_line, + end_line: function.end_line, + body: function.body.clone(), + calls: function.calls.clone(), + assertions: test.assertions.clone(), + literals: function.literals.clone(), + selector: HarnessSelectorCapability::NamedUnexecuted, + claim: HarnessSubjectClaim::NamedFunction, + provenance: TestHarnessRegistration::provenance().to_string(), + }; + promoted.push((line, function.name.clone(), test, subject)); + } + promoted + }; + if promoted_functions.is_empty() { + return; + } + + let Some(facts) = index.files.get_mut(&target) else { + return; + }; + for function in &mut facts.functions { + if promoted_functions + .iter() + .any(|(line, name, _, _)| *line == function.start_line && *name == function.name) + && !function.source_role.registers_executable_test() + { + function.source_role = FunctionSourceRole::RegisteredTestAttribute; + } + } + for (_, name, test, subject) in &promoted_functions { + let _ = name; + subjects.push(subject.clone()); + push_file_test(index, &target, test.clone()); + index.tests.push(test.clone()); + } + // Mirror the promotion into the flat function list so every consumer + // of `index.functions` sees the same producer-owned role. + for function in &mut index.functions { + if function.file != target { + continue; + } + if promoted_functions + .iter() + .any(|(line, name, _, _)| *line == function.start_line && *name == function.name) + && !function.source_role.registers_executable_test() + { + function.source_role = FunctionSourceRole::RegisteredTestAttribute; + } + } +} + +fn registered_attribute_test_fact(function: &FunctionFact) -> TestFact { + TestFact { + name: function.name.clone(), + file: function.file.clone(), + start_line: function.start_line, + end_line: function.end_line, + body: function.body.clone(), + calls: function.calls.clone(), + assertions: parser_oracles_for_function(&function.body, function.start_line) + .unwrap_or_else(|| { + crate::analysis::rust_index::extract_assertions(&function.body, function.start_line) + }), + literals: function.literals.clone(), + attrs: function.attrs.clone(), + } +} + +fn push_file_test(index: &mut RustIndex, target: &Path, test: TestFact) { + let Some(facts) = index.files.get_mut(target) else { + return; + }; + if facts + .tests + .iter() + .all(|existing| existing.name != test.name || existing.start_line != test.start_line) + { + facts.tests.push(test); + facts.tests.sort_by(|left, right| { + left.start_line + .cmp(&right.start_line) + .then(left.end_line.cmp(&right.end_line)) + .then(left.name.cmp(&right.name)) + }); + } +} + +/// Demote every function in a registered `harness = false` target to the +/// evidence-only helper role and drop the target's executable +/// `TestFact`s. With `harness = false` the libtest harness never +/// collects this file, so a `#[test]` attribute alone establishes nothing and +/// no member enters the executable-test denominator on its own: the +/// whole target is helper-evidence, and executable subjects come only +/// from adapter-established trial registrations. +fn demote_harness_target_functions(index: &mut RustIndex, target: &Path) { + let demoted: BTreeSet = { + let Some(facts) = index.files.get(target) else { + return; + }; + facts + .functions + .iter() + .filter(|function| function.source_role != FunctionSourceRole::HarnessHelper) + .map(|function| function.name.clone()) + .collect() + }; + if demoted.is_empty() { + return; + } + let Some(facts) = index.files.get_mut(target) else { + return; + }; + for function in &mut facts.functions { + function.source_role = FunctionSourceRole::HarnessHelper; + } + facts.tests.retain(|test| !demoted.contains(&test.name)); + index + .tests + .retain(|test| test.file != target || !demoted.contains(&test.name)); + for function in &mut index.functions { + if function.file == target { + function.source_role = FunctionSourceRole::HarnessHelper; + } + } +} + +enum RegisteredAttributeResolution { + Matched, + Ambiguous { detail: String }, + Unresolved { detail: String }, +} + +/// Resolve one function's attributes against the registered marker. +fn resolve_registered_attribute( + attrs: &[String], + marker: &str, + use_bindings: &BTreeSet, +) -> Option { + for attribute in attrs { + let Some(path) = normalized_attribute_path(attribute) else { + continue; + }; + if path == marker { + return Some(RegisteredAttributeResolution::Matched); + } + let Some((_prefix, name)) = marker.rsplit_once("::") else { + continue; + }; + if path != name { + continue; + } + // Bare spelling: the file must bind the name from exactly the + // registered path. Any other binding of the same name is the + // same-named-unrelated-import conflict. + let anchored = use_bindings.contains(marker); + let conflicting = use_bindings + .iter() + .any(|binding| binding != marker && binding.ends_with(&format!("::{name}"))); + if anchored && !conflicting { + return Some(RegisteredAttributeResolution::Matched); + } + if conflicting { + return Some(RegisteredAttributeResolution::Ambiguous { + detail: format!( + "`#[{name}]` cannot be tied to registered marker `{marker}`; the file's imports bind that name from more than one path" + ), + }); + } + return Some(RegisteredAttributeResolution::Unresolved { + detail: format!( + "`#[{name}]` matches the last segment of registered marker `{marker}`, but no top-level import in this file binds that name from the registered path" + ), + }); + } + None +} + +fn marker_leaf(marker: &str) -> &str { + marker.rsplit_once("::").map_or(marker, |(_, leaf)| leaf) +} + +/// Collect the full binding paths for `name` from top-level `use` items +/// (e.g. `use libtest_mimic::Trial;` binds `libtest_mimic::Trial`; +/// `use myco::{contract_test, other};` binds `myco::contract_test`). +/// Bounded to the shapes this walker can establish: glob imports, re-exports +/// through nested modules, and aliases away from the bound name grant no +/// binding, so the authority fails closed instead of guessing. +fn top_level_use_bindings(syntax: &ra_ap_syntax::SyntaxNode, name: &str) -> BTreeSet { + let mut bindings = BTreeSet::new(); + for use_item in syntax.children().filter_map(ast::Use::cast) { + let Some(use_tree) = use_item.use_tree() else { + continue; + }; + collect_use_bindings(&use_tree, String::new(), name, &mut bindings); + } + bindings +} + +fn collect_use_bindings( + tree: &ast::UseTree, + prefix: String, + name: &str, + out: &mut BTreeSet, +) { + let path_text = tree.path().map(|path| { + path.syntax() + .text() + .to_string() + .chars() + .filter(|character| !character.is_whitespace()) + .collect::() + }); + let alias = tree.rename().and_then(|rename| rename.name()); + if let Some(list) = tree.use_tree_list() { + let child_prefix = match (&path_text, prefix.is_empty()) { + (Some(path), false) => format!("{prefix}::{path}"), + (Some(path), true) => path.clone(), + (None, _) => prefix, + }; + for nested in list.use_trees() { + collect_use_bindings(&nested, child_prefix.clone(), name, out); + } + return; + } + let Some(tree_name) = alias.map(|named| named.text().to_string()).or_else(|| { + path_text + .as_ref() + .and_then(|path| path.rsplit("::").next()) + .map(ToString::to_string) + }) else { + return; + }; + if tree_name != name { + return; + } + let full = match (&path_text, prefix.is_empty()) { + (Some(path), false) => format!("{prefix}::{path}"), + (Some(path), true) => path.clone(), + (None, false) => prefix, + (None, true) => tree_name, + }; + out.insert(full); +} + +enum TrialBindingResolution { + MarkerAnchored, + Ambiguous { conflicting: String }, + Unbound, +} + +fn resolve_trial_binding(bindings: &BTreeSet, marker: &str) -> TrialBindingResolution { + let anchored_full = format!("{marker}::Trial"); + let matches_marker = |binding: &String| { + binding == &anchored_full || binding.ends_with(&format!("::{anchored_full}")) + }; + let anchored = bindings.iter().any(matches_marker); + let conflicting = bindings + .iter() + .filter(|binding| !matches_marker(binding)) + .cloned() + .collect::>(); + if anchored && conflicting.is_empty() { + return TrialBindingResolution::MarkerAnchored; + } + if anchored || conflicting.len() > 1 { + return TrialBindingResolution::Ambiguous { + conflicting: conflicting.join(", "), + }; + } + // No binding at all, or exactly one binding from another path: the + // invocation cannot be tied to the registered marker. + TrialBindingResolution::Unbound +} + +/// Whether the ancestor chain of a token sits inside a loop expression — +/// the bounded signal for runtime-only trial discovery. Works through +/// macro token trees too, because tokens keep their ancestor nodes. +fn in_loop(mut ancestors: impl Iterator) -> bool { + ancestors.any(|ancestor| { + ast::WhileExpr::can_cast(ancestor.kind()) + || ast::ForExpr::can_cast(ancestor.kind()) + || ast::LoopExpr::can_cast(ancestor.kind()) + }) +} + +/// Exact simple string-literal text of one token. Escaped spellings, +/// raw strings, and empty names are not demonstrated by this bounded parser and +/// stay unresolved (fail closed). +fn string_literal_token_text(token: &ra_ap_syntax::SyntaxToken) -> Option { + if token.kind() != ra_ap_syntax::SyntaxKind::STRING { + return None; + } + let text = token.text().trim(); + let body = text.strip_prefix('"')?.strip_suffix('"')?; + if body.is_empty() || body.contains(BACKSLASH) { + return None; + } + Some(body.to_string()) +} + +/// The one escape character this bounded parser refuses to guess about. +const BACKSLASH: char = '\\'; + +#[cfg(test)] +mod tests; diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs new file mode 100644 index 00000000000..26a3357dde4 --- /dev/null +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -0,0 +1,655 @@ +//! Discriminating tests for the repository-governed harness registry +//! (#3532): one per required fixture family, each pinning a boundary the +//! issue names — exact subjects, inert attributes, dynamic limitations, +//! lookalike and ambiguous controls, and stale/wrong-target fail-closed +//! behavior. + +use super::*; +use crate::analysis::facts::build_index_with_test_harnesses; +use std::fs; +use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; + +struct TempDir(PathBuf); + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn temp_dir(name: &str) -> Result> { + let stamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|time| time.as_nanos()) + .unwrap_or(0); + let root = std::env::temp_dir().join(format!("ripr-harness-{name}-{stamp}")); + fs::create_dir_all(&root)?; + Ok(TempDir(root)) +} + +fn registration( + registration_id: &str, + target: &str, + kind: TestHarnessKind, + adapter: TestHarnessAdapter, + marker: &str, +) -> TestHarnessRegistration { + TestHarnessRegistration { + registration_id: registration_id.to_string(), + target: PathBuf::from(target), + kind, + adapter, + marker: marker.to_string(), + } +} + +fn custom_target_registration(target: &str) -> TestHarnessRegistration { + registration( + "mimic-suite", + target, + TestHarnessKind::CustomHarnessTarget, + TestHarnessAdapter::LibtestMimicV1, + "libtest_mimic", + ) +} + +fn attribute_registration(target: &str, marker: &str) -> TestHarnessRegistration { + registration( + "contract-tests", + target, + TestHarnessKind::RegisteredAttribute, + TestHarnessAdapter::ExactAttributeV1, + marker, + ) +} + +fn write_workspace( + root: &TempDir, + files: &[(&str, &str)], +) -> Result<(), Box> { + fs::create_dir_all(root.0.join("src"))?; + fs::create_dir_all(root.0.join("tests"))?; + fs::write( + root.0.join("Cargo.toml"), + "[package]\nname = 'harness-fixture'\nversion = '0.1.0'\nedition = '2024'\n", + )?; + for (path, source) in files { + let full = root.0.join(path); + if let Some(parent) = full.parent() { + fs::create_dir_all(parent)?; + } + fs::write(full, source)?; + } + Ok(()) +} + +#[test] +fn without_registrations_the_index_is_unchanged() -> Result<(), Box> { + let root = temp_dir("no-registrations")?; + write_workspace( + &root, + &[("src/lib.rs", "pub fn production_control() -> i32 { 1 }\n")], + )?; + let plain = build_index_with_test_harnesses(&root.0, &[PathBuf::from("src/lib.rs")], &[])?; + assert!(plain.harness_subjects.is_empty()); + assert!(plain.harness_limitations.is_empty()); + Ok(()) +} + +#[test] +fn harness_false_target_is_evidence_role_with_exact_trial_subjects() +-> Result<(), Box> { + let root = temp_dir("mimic-target")?; + write_workspace( + &root, + &[ + ( + "src/lib.rs", + "pub fn price(amount: i32) -> i32 {\n amount * 2\n}\n", + ), + ( + "tests/price_mimic.rs", + r#" +use libtest_mimic::{Arguments, Trial}; + +fn parse_args(args: &[String]) -> usize { + args.len() +} + +fn check_beta() -> Result<(), String> { + Ok(()) +} + +fn static_trials() -> Vec { + vec![ + Trial::test("alpha_parses", || Ok(())), + Trial::test("beta_round_trips", check_beta), + ] +} + +fn collected(name: &str) -> Trial { + Trial::test(name, || Ok(())) +} + +fn dynamic_trials(count: usize) -> Vec { + let mut trials = Vec::new(); + for index in 0..count { + trials.push(Trial::test(format!("case_{index}"), || Ok(()))); + } + trials +} + +#[test] +fn ordinary_test_attribute_is_inert_without_the_harness() { + assert_eq!(parse_args(&[]), 0); +} +"#, + ), + ( + "tests/ordinary.rs", + "#[test]\nfn ordinary_libtest_runs_here() {\n assert_eq!(1, 1);\n}\n", + ), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("tests/price_mimic.rs"), + PathBuf::from("tests/ordinary.rs"), + ]; + let registrations = [custom_target_registration("tests/price_mimic.rs")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + + // Exact static trial names are the executable subjects. + let subject_names = index + .harness_subjects + .iter() + .map(|subject| subject.name.as_str()) + .collect::>(); + assert_eq!(subject_names, vec!["alpha_parses", "beta_round_trips"]); + for subject in &index.harness_subjects { + assert_eq!(subject.harness_kind, "custom_harness"); + assert_eq!(subject.adapter, "libtest_mimic_v1"); + assert_eq!(subject.marker, "libtest_mimic"); + assert_eq!(subject.file.as_path(), Path::new("tests/price_mimic.rs")); + assert_eq!( + subject.selector, + HarnessSelectorCapability::NamedUnexecuted, + "the trial name is a selector candidate, represented as unexecuted" + ); + assert_eq!(subject.claim, HarnessSubjectClaim::NamedInvocation); + assert_eq!(subject.provenance, "ripr.toml [analysis.test_harnesses]"); + } + assert!( + index + .harness_subjects + .iter() + .find(|subject| subject.name == "beta_round_trips") + .is_some_and(|subject| !subject.body.is_empty() && subject.body.contains("check_beta")), + "the invocation body is retained so oracle evidence stays observable" + ); + + // The subjects enter the executable-test denominator. + let test_names = index + .tests + .iter() + .filter(|test| test.file.as_path() == Path::new("tests/price_mimic.rs")) + .map(|test| test.name.as_str()) + .collect::>(); + assert_eq!(test_names, vec!["alpha_parses", "beta_round_trips"]); + + // The inert `#[test]` attribute does not make the fn a test here: + // the whole registered target is helper-evidence only. + let inert = index + .functions + .iter() + .find(|function| function.name == "ordinary_test_attribute_is_inert_without_the_harness") + .ok_or("missing inert attribute fn")?; + assert_eq!(inert.source_role, FunctionSourceRole::HarnessHelper); + assert!( + index + .tests + .iter() + .all(|test| test.name != "ordinary_test_attribute_is_inert_without_the_harness"), + "inert attributes must not enter the executable-test denominator" + ); + + // Dynamic shapes remain typed limitations. + let codes = index + .harness_limitations + .iter() + .map(|limitation| limitation.code.as_str()) + .collect::>(); + assert!(codes.contains(&"dynamic_trial_name"), "{codes:?}"); + assert!(codes.contains(&"dynamic_trial_registration"), "{codes:?}"); + + // The ordinary libtest target beside the custom target keeps its + // executable test. + assert!( + index + .tests + .iter() + .any(|test| test.name == "ordinary_libtest_runs_here"), + "an ordinary libtest target beside the custom target is unaffected" + ); + let ordinary = index + .functions + .iter() + .find(|function| function.name == "ordinary_libtest_runs_here") + .ok_or("missing ordinary test fn")?; + assert_eq!(ordinary.source_role, FunctionSourceRole::TestAttribute); + + // Same function name in production and harness files: the production + // one stays a production subject. + let production = index + .functions + .iter() + .find(|function| { + function.name == "price" && function.file.as_path() == Path::new("src/lib.rs") + }) + .ok_or("missing production fn")?; + assert_eq!(production.source_role, FunctionSourceRole::Production); + Ok(()) +} + +#[test] +fn unanchored_and_ambiguous_trial_paths_fail_closed() -> Result<(), Box> { + let root = temp_dir("trial-anchors")?; + write_workspace( + &root, + &[( + "tests/unanchored.rs", + r#" +use other_crate::Trial; + +fn trials() -> Vec { + vec![Trial::test("unanchored_case", || Ok(()))] +} +"#, + )], + )?; + let files = [PathBuf::from("tests/unanchored.rs")]; + let registrations = [custom_target_registration("tests/unanchored.rs")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert!(index.harness_subjects.is_empty()); + assert!( + index + .harness_limitations + .iter() + .any(|limitation| limitation.code == "unanchored_trial_path"), + "{:?}", + index.harness_limitations + ); + + // Same-named imports from two paths are non-clean and named. + let root = temp_dir("trial-ambiguous")?; + write_workspace( + &root, + &[( + "tests/ambiguous.rs", + r#" +use libtest_mimic::Trial; +use other_crate::Trial; + +fn trials() -> Vec { + vec![Trial::test("ambiguous_case", || Ok(()))] +} +"#, + )], + )?; + let files = [PathBuf::from("tests/ambiguous.rs")]; + let registrations = [custom_target_registration("tests/ambiguous.rs")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert!(index.harness_subjects.is_empty()); + let ambiguous = index + .harness_limitations + .iter() + .find(|limitation| limitation.code == "ambiguous_import") + .ok_or("missing ambiguous-import limitation")?; + assert!(ambiguous.detail.contains("conflicting imports bind Trial")); + Ok(()) +} + +#[test] +fn duplicate_trial_names_name_the_conflict_and_stay_one_subject() +-> Result<(), Box> { + let root = temp_dir("duplicate-trials")?; + write_workspace( + &root, + &[( + "tests/duplicates.rs", + r#" +use libtest_mimic::Trial; + +fn trials() -> Vec { + vec![ + Trial::test("same_name", || Ok(())), + Trial::test("same_name", || Ok(())), + ] +} +"#, + )], + )?; + let files = [PathBuf::from("tests/duplicates.rs")]; + let registrations = [custom_target_registration("tests/duplicates.rs")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert_eq!(index.harness_subjects.len(), 1); + assert!( + index + .harness_limitations + .iter() + .any(|limitation| limitation.code == "duplicate_subject" + && limitation.detail.contains("same_name")), + "{:?}", + index.harness_limitations + ); + Ok(()) +} + +#[test] +fn fully_qualified_trial_calls_match_the_marker_path() -> Result<(), Box> { + let root = temp_dir("qualified-trials")?; + write_workspace( + &root, + &[( + "tests/qualified.rs", + "fn trials() -> Vec {\n vec![libtest_mimic::Trial::test(\"qualified_case\", || Ok(()))]\n}\n", + )], + )?; + let files = [PathBuf::from("tests/qualified.rs")]; + let registrations = [custom_target_registration("tests/qualified.rs")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert_eq!( + index + .harness_subjects + .iter() + .map(|subject| subject.name.as_str()) + .collect::>(), + vec!["qualified_case"] + ); + Ok(()) +} + +#[test] +fn registered_attribute_promotes_exact_matches_only() -> Result<(), Box> { + let root = temp_dir("registered-attribute")?; + write_workspace( + &root, + &[( + "crates/contract/tests/api.rs", + r#" +use myco::contract_test; + +pub fn price(amount: i32) -> i32 { + amount * 2 +} + +#[contract_test] +fn price_round_trips() { + assert_eq!(price(2), 4); +} + +#[myco::contract_test] +fn price_rejects_zero() { + assert_ne!(price(0), 1); +} + +#[myco::contract_tests] +fn lookalike_suffix_is_not_registered() { + assert_eq!(price(1), 2); +} + +#[myco_contract_test] +fn lookalike_prefix_is_not_registered() { + assert_eq!(price(1), 2); +} + +fn plain_helper() -> i32 { + price(3) +} +"#, + )], + )?; + let target = "crates/contract/tests/api.rs"; + let files = [PathBuf::from(target)]; + let registrations = [attribute_registration(target, "myco::contract_test")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + + let mut subject_names = index + .harness_subjects + .iter() + .map(|subject| subject.name.as_str()) + .collect::>(); + subject_names.sort_unstable(); + assert_eq!( + subject_names, + vec!["price_rejects_zero", "price_round_trips"] + ); + for subject in &index.harness_subjects { + assert_eq!(subject.harness_kind, "registered_attribute"); + assert_eq!(subject.adapter, "exact_attribute_v1"); + assert_eq!(subject.marker, "myco::contract_test"); + assert_eq!(subject.claim, HarnessSubjectClaim::NamedFunction); + assert_eq!(subject.selector, HarnessSelectorCapability::NamedUnexecuted); + } + + let promoted = index + .functions + .iter() + .find(|function| function.name == "price_round_trips") + .ok_or("missing promoted fn")?; + assert_eq!( + promoted.source_role, + FunctionSourceRole::RegisteredTestAttribute + ); + assert!( + index + .tests + .iter() + .any(|test| test.name == "price_round_trips"), + "registered attribute tests join the executable-test denominator" + ); + assert!( + index.functions.iter().all(|function| function.name + != "lookalike_suffix_is_not_registered" + || !function.source_role.is_evidence_role()), + "prefix/suffix lookalikes must never classify" + ); + assert!( + index + .tests + .iter() + .all(|test| !test.name.contains("lookalike")), + "lookalikes must not join the test denominator" + ); + Ok(()) +} + +#[test] +fn same_named_unrelated_import_is_ambiguous_and_fails_closed() +-> Result<(), Box> { + let root = temp_dir("attribute-ambiguous")?; + write_workspace( + &root, + &[( + "tests/ambiguous_attr.rs", + r#" +use other_crate::contract_test; + +#[contract_test] +fn ambiguous_owner() { + assert_eq!(1, 1); +} +"#, + )], + )?; + let files = [PathBuf::from("tests/ambiguous_attr.rs")]; + let registrations = [attribute_registration( + "tests/ambiguous_attr.rs", + "myco::contract_test", + )]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert!(index.harness_subjects.is_empty()); + assert!( + index + .harness_limitations + .iter() + .any(|limitation| limitation.code == "ambiguous_import"), + "{:?}", + index.harness_limitations + ); + let function = index + .functions + .iter() + .find(|function| function.name == "ambiguous_owner") + .ok_or("missing fn")?; + assert_eq!( + function.source_role, + FunctionSourceRole::Production, + "an ambiguous import must not classify the fn as an executable test" + ); + Ok(()) +} + +#[test] +fn stale_or_foreign_registrations_grant_nothing() -> Result<(), Box> { + let root = temp_dir("stale-registration")?; + write_workspace( + &root, + &[( + "src/lib.rs", + "pub fn price(amount: i32) -> i32 {\n amount * 2\n}\n", + )], + )?; + // The registration names a file that is not part of this analysis + // (stale, removed, or another package's scope). + let registrations = [custom_target_registration("other_pkg/tests/mimic.rs")]; + let files = [PathBuf::from("src/lib.rs")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert!(index.harness_subjects.is_empty()); + assert!(index.harness_limitations.is_empty()); + assert!(index.tests.is_empty()); + Ok(()) +} + +#[test] +fn bare_attribute_without_marker_import_stays_unclassified() +-> Result<(), Box> { + // `#[contract_test]` with no import binding at all cannot be established + // to be the registered marker path; the authority names the gap + // instead of guessing. + let root = temp_dir("attribute-unresolved")?; + write_workspace( + &root, + &[( + "tests/unresolved_attr.rs", + "#[contract_test]\nfn unresolved_owner() {\n assert_eq!(1, 1);\n}\n", + )], + )?; + let files = [PathBuf::from("tests/unresolved_attr.rs")]; + let registrations = [attribute_registration( + "tests/unresolved_attr.rs", + "myco::contract_test", + )]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert!(index.harness_subjects.is_empty()); + assert!( + index + .harness_limitations + .iter() + .any(|limitation| limitation.code == "unresolved_marker_import"), + "{:?}", + index.harness_limitations + ); + Ok(()) +} + +#[test] +fn cached_index_applies_registrations_identically() -> Result<(), Box> { + let root = temp_dir("cached-harness")?; + let file = PathBuf::from("tests/cached_mimic.rs"); + let source = br#" +use libtest_mimic::Trial; + +fn trials() -> Vec { + vec![Trial::test("cached_case", || Ok(()))] +} +"# + .to_vec(); + let files = [(file.clone(), source)]; + let registrations = [custom_target_registration("tests/cached_mimic.rs")]; + + let cold = crate::analysis::facts::build_index_from_loaded_files_with_cache_and_test_harnesses( + &root.0, + &files, + ®istrations, + )?; + let warm = crate::analysis::facts::build_index_from_loaded_files_with_cache_and_test_harnesses( + &root.0, + &files, + ®istrations, + )?; + for index in [&cold.index, &warm.index] { + assert_eq!( + index + .harness_subjects + .iter() + .map(|subject| subject.name.as_str()) + .collect::>(), + vec!["cached_case"] + ); + assert_eq!(index.tests.len(), 1); + } + assert_eq!(cold.file_fact_cache.hits, 0); + assert_eq!(warm.file_fact_cache.hits, 1); + Ok(()) +} + +#[test] +fn built_in_test_attributes_precede_a_registered_marker() -> Result<(), Box> +{ + // A fn carrying BOTH `#[test]` and the registered attribute must not + // register twice: the built-in #3499 family keeps precedence. + let root = temp_dir("builtin-precedence")?; + write_workspace( + &root, + &[( + "tests/both_attrs.rs", + r#" +use myco::contract_test; + +#[test] +#[contract_test] +fn double_attributed() { + assert_eq!(1, 1); +} +"#, + )], + )?; + let files = [PathBuf::from("tests/both_attrs.rs")]; + let registrations = [ + custom_target_registration("tests/other.rs"), + attribute_registration("tests/both_attrs.rs", "myco::contract_test"), + ]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert!( + index.harness_subjects.is_empty(), + "the built-in attribute already owns the fn" + ); + assert_eq!( + index + .tests + .iter() + .filter(|test| test.name == "double_attributed") + .count(), + 1, + "exactly one executable test fact, from the built-in family" + ); + let function = index + .functions + .iter() + .find(|function| function.name == "double_attributed") + .ok_or("missing fn")?; + assert_eq!(function.source_role, FunctionSourceRole::TestAttribute); + Ok(()) +} diff --git a/crates/ripr/src/analysis/facts/mod.rs b/crates/ripr/src/analysis/facts/mod.rs index fca9dda7ced..d1545ae272b 100644 --- a/crates/ripr/src/analysis/facts/mod.rs +++ b/crates/ripr/src/analysis/facts/mod.rs @@ -1,5 +1,6 @@ mod build; pub(crate) mod cfg_predicates; +mod harness_registry; mod includes; mod model; mod parameterized_tests; @@ -8,7 +9,21 @@ mod test_styles; use std::path::{Path, PathBuf}; +use crate::config::TestHarnessRegistration; + pub fn build_index(root: &Path, files: &[PathBuf]) -> Result { + build_index_with_test_harnesses(root, files, &[]) +} + +/// Index construction with the repository-governed harness registry +/// (#3532) applied: exact registrations derive typed subject and +/// limitation facts after the ordinary role authorities run. Without +/// registrations the result is identical to [`build_index`]. +pub fn build_index_with_test_harnesses( + root: &Path, + files: &[PathBuf], + registrations: &[TestHarnessRegistration], +) -> Result { let mut index = build::build_index(root, files)?; parameterized_tests::promote_explicit_test_case_functions(&mut index); test_styles::normalize_index_test_styles(&mut index); @@ -18,17 +33,20 @@ pub fn build_index(root: &Path, files: &[PathBuf]) -> Result)], + registrations: &[TestHarnessRegistration], ) -> Result { let mut cached = build::build_index_from_loaded_files_with_cache(root, files)?; parameterized_tests::promote_explicit_test_case_functions(&mut cached.index); test_styles::normalize_index_test_styles(&mut cached.index); role_composition::compose_index_source_roles(&mut cached.index, root); + harness_registry::apply_registrations(&mut cached.index, registrations); Ok(cached) } @@ -39,6 +57,9 @@ pub use model::{ ModuleDeclarationFact, ModulePathTarget, OracleFact, ProbeShapeFact, ResolvedIncludeParent, ReturnFact, RustIncludeLimitation, RustIndex, SourceRoleProvenance, SourceRoleProvenanceEdge, SourceRoleProvenanceEdgeKind, TestFact, TestSummary, + CallFact, FileFacts, FunctionFact, FunctionSourceRole, FunctionSummary, HarnessLimitationFact, + HarnessSelectorCapability, HarnessSubjectClaim, HarnessSubjectFact, LiteralFact, OracleFact, + ProbeShapeFact, ReturnFact, RustIncludeLimitation, RustIndex, TestFact, TestSummary, }; #[cfg(test)] pub(crate) use model::{WorkspaceFileAuthority, WorkspaceRootAuthority}; diff --git a/crates/ripr/src/analysis/facts/model.rs b/crates/ripr/src/analysis/facts/model.rs index f826c34effb..aae28304f17 100644 --- a/crates/ripr/src/analysis/facts/model.rs +++ b/crates/ripr/src/analysis/facts/model.rs @@ -246,6 +246,20 @@ pub struct RustIndex { pub include_parents: BTreeMap, #[serde(default)] pub include_limitations: Vec, + /// Executable test subjects established by registered harness + /// adapters (#3532). Empty without registrations; every entry carries + /// its registration provenance, harness kind, adapter generation, + /// subject identity, and selector capability so consumers project + /// them without reconstructing any of it. + #[serde(default)] + pub harness_subjects: Vec, + /// Typed limitations recorded by registered harness adapters (#3532): + /// shapes the registration saw but could not classify (dynamic names, + /// loop-driven registration, ambiguous imports). Unregistered or + /// ambiguous harnesses are limitations here, never production or + /// executable-test optimism. + #[serde(default)] + pub harness_limitations: Vec, #[serde(default)] pub(crate) workspace_authority: Option, } @@ -406,11 +420,21 @@ pub struct FileFacts { /// - `TestAttribute` and `ParameterizedExpansion` are executable tests: /// they carry (or were promoted from) an exact supported test-defining /// attribute and register `TestFact`s — the test selector denominator. +/// - `RegisteredTestAttribute` is an executable test carrying an exact +/// repository-registered test-producing attribute (#3532 harness +/// registry); it registers a `TestFact` through this same role +/// authority. /// - `CfgTestModule` is evidence-only helper role: a function inside a /// test-required module (`#[cfg(test)]`, or a `test` conjunct in /// `cfg(all(...))` through the shared `cfg_predicates` authority). It /// stays evidence-capable without entering the executable-test /// denominator. +/// - `HarnessHelper` is evidence-only helper role inside a registered +/// custom test-harness target (#3532, e.g. a `[[test]]` +/// `harness = false` libtest-mimic suite): the custom harness never +/// runs libtest collection, so an attribute alone never makes a member +/// an executable test. Executable subjects come only from the harness +/// registry's adapter. /// - `Production` is ordinary non-evidence source and remains a /// production-subject candidate. Production-subject *eligibility* is /// still the consumer-side composition of this role with the file-level @@ -421,10 +445,8 @@ pub struct FileFacts { /// Dimensions with no function-level producer today are deliberately absent /// rather than fabricated: the explicit production-like opt-in /// (`analysis.production_like_targets`) acts at the file `SourceRole` -/// layer, and a typed unknown awaits a real producer (#3499 / #3532 own the -/// next attribute and registered-harness families). Extending this enum is -/// a producer change; a renderer or consumer may display the role but may -/// not recalculate it. +/// layer. Extending this enum is a producer change; a renderer or +/// consumer may display the role but may not recalculate it. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum FunctionSourceRole { @@ -446,6 +468,17 @@ pub enum FunctionSourceRole { /// (`facts::parameterized_tests`) from an exact `#[test_case(...)]` /// family attribute. Registers an executable, promoted `TestFact`. ParameterizedExpansion, + /// Carries an exact repository-registered test-producing attribute + /// through the harness registry (#3532, `analysis.test_harnesses`). + /// Classified through this same role authority; registers an + /// executable `TestFact` whose provenance is the registration. + RegisteredTestAttribute, + /// Member of a registered custom test-harness target (#3532, e.g. a + /// `[[test]]` `harness = false` libtest-mimic suite). Evidence-only: + /// the custom harness does not run libtest collection, so no + /// executable `TestFact` is registered for this variant alone. + /// Executable subjects are the adapter-established harness subjects. + HarnessHelper, } impl FunctionSourceRole { @@ -460,6 +493,16 @@ impl FunctionSourceRole { pub fn is_evidence_role(self) -> bool { !matches!(self, Self::Production) } + + /// Whether functions with this role register executable `TestFact`s — + /// the test selector denominator. Evidence-only helper roles + /// (`CfgTestModule`, `HarnessHelper`) never enter it on their own. + pub fn registers_executable_test(self) -> bool { + matches!( + self, + Self::TestAttribute | Self::ParameterizedExpansion | Self::RegisteredTestAttribute + ) + } } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -499,6 +542,102 @@ pub struct TestFact { pub attrs: Vec, } +/// Whether a selector route is known for one harness subject (#3532). +/// A registration can describe a selector adapter; passive analysis +/// never runs it, so every capability stays explicitly unexecuted. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HarnessSelectorCapability { + /// No selector route is known to RIPR for this subject. + None, + /// A named selector candidate exists (e.g. the libtest-mimic trial + /// name, or the registered attribute's test name). Represented as + /// unexecuted: no passive analysis starts Cargo or the harness. + NamedUnexecuted, +} + +impl HarnessSelectorCapability { + /// Stable wire string for projections. + pub fn as_str(self) -> &'static str { + match self { + Self::None => "none", + Self::NamedUnexecuted => "named_unexecuted", + } + } +} + +/// What the adapter claims one harness subject is (#3532). The claim is +/// stated per subject so consumers never assume expansion. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HarnessSubjectClaim { + /// The source invocation itself is one source-level test subject + /// (e.g. one `Trial::test("name", ...)` registration). Generated + /// cases inside it are not enumerated. + NamedInvocation, + /// The function is one executable test (registered test-producing + /// attribute). + NamedFunction, +} + +impl HarnessSubjectClaim { + /// Stable wire string for projections. + pub fn as_str(self) -> &'static str { + match self { + Self::NamedInvocation => "named_invocation", + Self::NamedFunction => "named_function", + } + } +} + +/// One executable test subject established by a registered harness +/// adapter (#3532). A matching adapter emits these typed subject facts +/// rather than mutating `FunctionFact` ad hoc. Each subject also +/// registers an ordinary `TestFact` (same name/file/span) so the +/// executable-test denominator and every existing test consumer see it. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct HarnessSubjectFact { + /// The registration that authorized this subject. + pub registration_id: String, + /// Harness family (e.g. `custom_harness`, `registered_attribute`). + pub harness_kind: String, + /// Adapter generation (e.g. `libtest_mimic_v1`). + pub adapter: String, + /// Exact source marker the adapter matched (crate path or attribute + /// path). Prefix/suffix lookalikes never produce subjects. + pub marker: String, + /// Stable subject identity: the trial name or the test fn name. + pub name: String, + pub file: PathBuf, + pub start_line: usize, + pub end_line: usize, + pub body: String, + pub calls: Vec, + pub assertions: Vec, + pub literals: Vec, + pub selector: HarnessSelectorCapability, + pub claim: HarnessSubjectClaim, + /// Trust provenance of the authorizing registration (e.g. + /// `ripr.toml [analysis.test_harnesses]`). + pub provenance: String, +} + +/// One typed limitation recorded by a registered harness adapter (#3532): +/// a shape the registration saw but could not classify statically. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct HarnessLimitationFact { + /// The registration that observed the limitation. + pub registration_id: String, + /// Stable limitation code, e.g. `dynamic_trial_name`, + /// `dynamic_trial_registration`, `ambiguous_import`, + /// `unanchored_trial_path`. + pub code: String, + pub file: PathBuf, + pub line: usize, + /// Human-readable detail naming what could not be classified and why. + pub detail: String, +} + #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct OracleFact { pub line: usize, diff --git a/crates/ripr/src/analysis/facts/parameterized_tests.rs b/crates/ripr/src/analysis/facts/parameterized_tests.rs index 60399f8f112..eb558c01d81 100644 --- a/crates/ripr/src/analysis/facts/parameterized_tests.rs +++ b/crates/ripr/src/analysis/facts/parameterized_tests.rs @@ -314,9 +314,17 @@ fn stacked_test_case(value: i32) { let files = [(file.clone(), source)]; let cold = - crate::analysis::facts::build_index_from_loaded_files_with_cache(&root.0, &files)?; + crate::analysis::facts::build_index_from_loaded_files_with_cache_and_test_harnesses( + &root.0, + &files, + &[], + )?; let warm = - crate::analysis::facts::build_index_from_loaded_files_with_cache(&root.0, &files)?; + crate::analysis::facts::build_index_from_loaded_files_with_cache_and_test_harnesses( + &root.0, + &files, + &[], + )?; for index in [&cold.index, &warm.index] { assert_eq!( diff --git a/crates/ripr/src/analysis/facts/test_styles.rs b/crates/ripr/src/analysis/facts/test_styles.rs index c28c9f5ecc8..475c9c98e30 100644 --- a/crates/ripr/src/analysis/facts/test_styles.rs +++ b/crates/ripr/src/analysis/facts/test_styles.rs @@ -276,7 +276,7 @@ fn join_leading_attribute(lines: &[&str]) -> Option<(String, String, usize)> { None } -fn normalized_test_attribute_path(attribute: &str) -> Option { +pub(super) fn normalized_test_attribute_path(attribute: &str) -> Option { let body = attribute.trim().strip_prefix("#[")?; let closing = body.rfind(']')?; let trailing = body.get(closing + 1..)?.trim(); diff --git a/crates/ripr/src/analysis/facts/test_styles/tests.rs b/crates/ripr/src/analysis/facts/test_styles/tests.rs index d26abbb91d6..cb90610271d 100644 --- a/crates/ripr/src/analysis/facts/test_styles/tests.rs +++ b/crates/ripr/src/analysis/facts/test_styles/tests.rs @@ -472,10 +472,18 @@ fn fallback_lookalike() {} .iter() .map(|file| fs::read(root.join(file)).map(|bytes| (file.clone(), bytes))) .collect::, _>>()?; - let cold_cached = super::super::build_index_from_loaded_files_with_cache(&root, &loaded_files) - .map_err(std::io::Error::other)?; - let warm_cached = super::super::build_index_from_loaded_files_with_cache(&root, &loaded_files) - .map_err(std::io::Error::other)?; + let cold_cached = super::super::build_index_from_loaded_files_with_cache_and_test_harnesses( + &root, + &loaded_files, + &[], + ) + .map_err(std::io::Error::other)?; + let warm_cached = super::super::build_index_from_loaded_files_with_cache_and_test_harnesses( + &root, + &loaded_files, + &[], + ) + .map_err(std::io::Error::other)?; assert_eq!(index_test_names(&cold_cached.index), expected_tests); assert_eq!(index_test_names(&warm_cached.index), expected_tests); assert!( diff --git a/crates/ripr/src/analysis/git_candidate_execution.rs b/crates/ripr/src/analysis/git_candidate_execution.rs index e9094a0c54f..ecd84645a03 100644 --- a/crates/ripr/src/analysis/git_candidate_execution.rs +++ b/crates/ripr/src/analysis/git_candidate_execution.rs @@ -702,6 +702,7 @@ mod tests { git_timeout: None, git_candidate: Some(s.clone()), production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let error = @@ -760,6 +761,7 @@ mod tests { git_timeout: None, git_candidate: Some(subject), production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let result = crate::analysis::run_analysis_with_oracle_policy( diff --git a/crates/ripr/src/analysis/harness_projection.rs b/crates/ripr/src/analysis/harness_projection.rs new file mode 100644 index 00000000000..a4a76e411d0 --- /dev/null +++ b/crates/ripr/src/analysis/harness_projection.rs @@ -0,0 +1,85 @@ +//! Public projection records for the repository-governed test-harness +//! registry (#3532). +//! +//! These records carry what a registration established for one run — +//! harness kind, provenance, subject identity, selector capability, and +//! typed limitations — so CLI, LSP, and packet surfaces can project the +//! registry's facts without reconstructing them from paths, attributes, +//! or names. Empty records (no registrations) project nothing. + +pub use crate::analysis::facts::{HarnessLimitationFact, HarnessSubjectFact}; +#[cfg(test)] +pub use crate::analysis::facts::{HarnessSelectorCapability, HarnessSubjectClaim}; +use std::path::PathBuf; + +/// What one registration established for one analysis run. +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct TestHarnessProjection { + /// Stable registration identifier from `ripr.toml`. + pub registration_id: String, + /// Harness family (`custom_harness` | `registered_attribute`). + pub harness_kind: String, + /// Adapter generation (e.g. `libtest_mimic_v1`). + pub adapter: String, + /// Exact source marker the registration matched. + pub marker: String, + /// Exact registered target file (workspace-relative, forward-slashed). + pub target: PathBuf, + /// Trust provenance of the registration. + pub provenance: String, + /// Executable test subjects the adapter established, in source order. + pub subjects: Vec, + /// Typed limitations the adapter recorded, in source order. + pub limitations: Vec, +} + +impl TestHarnessProjection { + pub(crate) fn from_registration(registration: &crate::config::TestHarnessRegistration) -> Self { + Self { + registration_id: registration.registration_id.clone(), + harness_kind: registration.kind.as_str().to_string(), + adapter: registration.adapter.as_str().to_string(), + marker: registration.marker.clone(), + target: registration + .target + .to_string_lossy() + .replace('\\', "/") + .into(), + provenance: crate::config::TestHarnessRegistration::provenance().to_string(), + subjects: Vec::new(), + limitations: Vec::new(), + } + } +} + +/// Build one projection per registration (registration order preserved) +/// from the typed facts the harness registry left on the index. +pub(crate) fn projections_from_index( + index: &crate::analysis::facts::RustIndex, + registrations: &[crate::config::TestHarnessRegistration], +) -> Vec { + if registrations.is_empty() { + return Vec::new(); + } + let mut projections: Vec = registrations + .iter() + .map(TestHarnessProjection::from_registration) + .collect(); + for subject in &index.harness_subjects { + if let Some(projection) = projections + .iter_mut() + .find(|projection| projection.registration_id == subject.registration_id) + { + projection.subjects.push(subject.clone()); + } + } + for limitation in &index.harness_limitations { + if let Some(projection) = projections + .iter_mut() + .find(|projection| projection.registration_id == limitation.registration_id) + { + projection.limitations.push(limitation.clone()); + } + } + projections +} diff --git a/crates/ripr/src/analysis/language/adapter.rs b/crates/ripr/src/analysis/language/adapter.rs index 29583ac2f4a..9f63242c7e8 100644 --- a/crates/ripr/src/analysis/language/adapter.rs +++ b/crates/ripr/src/analysis/language/adapter.rs @@ -21,6 +21,9 @@ use std::path::Path; #[derive(Clone, Debug, Default)] pub(crate) struct LanguageDiffResult { pub(crate) findings: Vec, + /// Test-harness registry projections (#3532): what each exact + /// registration established for this run. Empty without registrations. + pub(crate) harness_projections: Vec, pub(crate) changed_files: usize, /// Number of distinct changed source lines for which the adapter /// generated at least one probe. This is a producer fact, not a proxy for @@ -48,6 +51,9 @@ pub(crate) struct LanguageDiffResult { #[derive(Clone, Debug, Default)] pub(crate) struct LanguageRepoResult { pub(crate) findings: Vec, + /// Test-harness registry projections (#3532); empty without + /// registrations. + pub(crate) harness_projections: Vec, pub(crate) production_files: usize, /// Number of discovered-language files intentionally excluded as generated /// source. The pipeline records this as a partial run disclosure. diff --git a/crates/ripr/src/analysis/language/perl/tests.rs b/crates/ripr/src/analysis/language/perl/tests.rs index 40cb8f23ab1..6fb203d2f45 100644 --- a/crates/ripr/src/analysis/language/perl/tests.rs +++ b/crates/ripr/src/analysis/language/perl/tests.rs @@ -63,6 +63,7 @@ fn packet_test_options() -> crate::analysis::AnalysisOptions { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), } } diff --git a/crates/ripr/src/analysis/language/python.rs b/crates/ripr/src/analysis/language/python.rs index b7513c2c8bd..4716cb39698 100644 --- a/crates/ripr/src/analysis/language/python.rs +++ b/crates/ripr/src/analysis/language/python.rs @@ -6668,6 +6668,7 @@ impl LanguageAdapter for PythonAdapter { } Ok(LanguageDiffResult { findings, + harness_projections: Vec::new(), changed_files: changed_count, candidate_line_count: 0, changed_files_by_language: Vec::new(), @@ -6690,6 +6691,7 @@ impl LanguageAdapter for PythonAdapter { // § "Repo-Mode Analysis Is Rust-Only" for the limitation contract. Ok(LanguageRepoResult { findings: Vec::new(), + harness_projections: Vec::new(), production_files: 0, skipped_files: 0, }) @@ -10609,6 +10611,7 @@ def test_build_user_smoke(): git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let policy = OraclePolicy::default(); @@ -10639,6 +10642,7 @@ def test_build_user_smoke(): git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let policy = OraclePolicy::default(); diff --git a/crates/ripr/src/analysis/language/python/python_tests.rs b/crates/ripr/src/analysis/language/python/python_tests.rs index 1161f8228e4..92b5f5d19fd 100644 --- a/crates/ripr/src/analysis/language/python/python_tests.rs +++ b/crates/ripr/src/analysis/language/python/python_tests.rs @@ -1412,6 +1412,7 @@ fn analyze_diff_emits_finding_for_changed_python_file_on_disk() -> Result<(), St git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let policy = OraclePolicy::default(); @@ -1503,6 +1504,7 @@ fn analyze_diff_suppresses_multiline_docstring_interior_change() -> Result<(), S git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let changed_files = vec![ChangedFile { @@ -1554,6 +1556,7 @@ fn analyze_diff_does_not_hide_behavior_after_same_line_docstring() -> Result<(), git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let changed_files = vec![ChangedFile { @@ -1602,6 +1605,7 @@ fn analyze_diff_does_not_hide_code_replaced_by_multiline_docstring() -> Result<( git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let changed_files = vec![ChangedFile { @@ -1693,6 +1697,7 @@ def test_encode_status():\n assert encode_status('paid')['status'] == 'paid'\ git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let policy = OraclePolicy::default(); @@ -2468,6 +2473,7 @@ fn analyze_diff_counts_python_file_but_skips_unreadable_workspace_source() -> Re git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let policy = OraclePolicy::default(); diff --git a/crates/ripr/src/analysis/language/rust.rs b/crates/ripr/src/analysis/language/rust.rs index 14d78856083..e960906d448 100644 --- a/crates/ripr/src/analysis/language/rust.rs +++ b/crates/ripr/src/analysis/language/rust.rs @@ -1608,8 +1608,11 @@ impl RustAdapter { Ok((file.clone(), bytes)) }) .collect::, String>>()?; - let cached = - rust_index::build_index_from_loaded_files_with_cache(&options.root, &loaded_files)?; + let cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + &options.root, + &loaded_files, + &options.test_harnesses, + )?; let mut index = cached.index; if let Some(disclosure) = rust_index::include_resolution_disclosure(&index) { eprintln!("{disclosure}"); @@ -1632,6 +1635,11 @@ impl RustAdapter { analyzable_rust_files.iter().map(|path| path.as_path()), ); source_role_context.production_like_targets = options.production_like_targets.clone(); + source_role_context.harness_targets = options + .test_harnesses + .iter() + .map(|registration| registration.target.clone()) + .collect(); // #2971: The cross-crate calls_owner bypass in find_related_tests // requires a workspace-complete function index. In Instant/Draft/Fast @@ -1720,6 +1728,10 @@ impl RustAdapter { Ok(LanguageDiffResult { findings, + harness_projections: super::super::harness_projection::projections_from_index( + &index, + &options.test_harnesses, + ), changed_files: changed_rust_files, candidate_line_count: candidate_lines.len(), changed_files_by_language: Vec::new(), @@ -1805,6 +1817,11 @@ impl RustAdapter { analyzable_rust_files.iter().map(|path| path.as_path()), ); context.production_like_targets = options.production_like_targets.clone(); + context.harness_targets = options + .test_harnesses + .iter() + .map(|registration| registration.target.clone()) + .collect(); context }; let production_files = analyzable_rust_files @@ -1832,9 +1849,10 @@ impl RustAdapter { Ok((file.clone(), bytes)) }) .collect::, String>>()?; - let cached = rust_index::build_index_from_loaded_files_with_cache( + let cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( &options.root, &loaded_rust_files, + &options.test_harnesses, )?; let mut index = cached.index; if let Some(disclosure) = rust_index::lexical_fallback_disclosure(&index) { @@ -1875,6 +1893,10 @@ impl RustAdapter { Ok(LanguageRepoResult { findings, + harness_projections: super::super::harness_projection::projections_from_index( + &index, + &options.test_harnesses, + ), production_files: production_files.len(), skipped_files, }) @@ -1987,6 +2009,7 @@ mod tests { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &changed_files, @@ -2057,6 +2080,7 @@ mod tests { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &changed_files, @@ -2155,6 +2179,7 @@ mod tests { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &changed_files, @@ -2329,6 +2354,7 @@ fn absent_delimiter_boundary_returns_head() { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &changed_files, @@ -3279,6 +3305,7 @@ fn absent_delimiter_boundary_returns_head() { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &changed_files, @@ -3921,6 +3948,7 @@ let _ = (result, note, raw);"##, git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }; let policy = OraclePolicy::default(); let result = cancellation::with_token(&token, || { @@ -4029,6 +4057,7 @@ let _ = (result, note, raw);"##, git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &changed_files, @@ -4119,6 +4148,7 @@ let _ = (result, note, raw);"##, git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &changed_files, @@ -4164,6 +4194,140 @@ let _ = (result, note, raw);"##, Ok(()) } + #[test] + fn diff_analysis_registered_harness_target_never_seeds_production_probes() -> Result<(), String> + { + // #3532: an exact `[analysis.test_harnesses]` registration makes a + // `harness = false` custom target evidence role outside tests/ — + // its inert `#[test]` attributes and helper plumbing seed no + // production probes, while an unregistered sibling does. + let root = temp_root("registered-harness-diff")?; + write( + &root.join("Cargo.toml"), + "[package]\nname='registered-harness'\nversion='0.1.0'\nedition='2024'\n", + )?; + write( + &root.join("src/lib.rs"), + "pub fn price(amount: i32) -> i32 {\n if amount > 100 { amount - 10 } else { amount }\n}\n", + )?; + write( + &root.join("src/price_mimic.rs"), + "use libtest_mimic::Trial;\n\nfn setup_price(amount: i32) -> i32 {\n if amount < 0 { 0 } else { price(amount) }\n}\n\n#[test]\nfn inert_without_the_harness() {\n assert_eq!(setup_price(100), 90);\n}\n\nfn trials() -> Vec {\n vec![Trial::test(\"price_at_boundary\", || {\n assert_eq!(setup_price(100), 90);\n })]\n}\n", + )?; + write( + &root.join("src/unregistered_helper.rs"), + "pub fn helper_path(amount: i32) -> i32 {\n if amount < 0 { 0 } else { amount }\n}\n", + )?; + let mut diff_text = String::new(); + let mut add_file = |path: &str, lines: &[&str]| { + diff_text.push_str(&format!("diff --git a{path} b{path}\n")); + diff_text.push_str("new file mode 100644\n"); + diff_text.push_str("--- /dev/null\n"); + diff_text.push_str(&format!("+++ b{path}\n")); + diff_text.push_str(&format!("@@ -0,0 +1,{} @@\n", lines.len())); + for line in lines { + diff_text.push_str(&format!("+{line}\n")); + } + }; + add_file( + "/src/lib.rs", + &[ + "pub fn price(amount: i32) -> i32 {", + " if amount > 100 { amount - 10 } else { amount }", + "}", + ], + ); + add_file( + "/src/price_mimic.rs", + &[ + "use libtest_mimic::Trial;", + "", + "fn setup_price(amount: i32) -> i32 {", + " if amount < 0 { 0 } else { price(amount) }", + "}", + "", + "#[test]", + "fn inert_without_the_harness() {", + " assert_eq!(setup_price(100), 90);", + "}", + "", + "fn trials() -> Vec {", + " vec![Trial::test(\"price_at_boundary\", || {", + " assert_eq!(setup_price(100), 90);", + " })]", + "}", + ], + ); + add_file( + "/src/unregistered_helper.rs", + &[ + "pub fn helper_path(amount: i32) -> i32 {", + " if amount < 0 { 0 } else { amount }", + "}", + ], + ); + let changed_files = diff::parse_unified_diff(&diff_text); + let result = RustAdapter.analyze_diff( + &AnalysisOptions { + root, + base: None, + diff_file: None, + mode: AnalysisMode::Ready, + resolved_subject_identity: None, + include_unchanged_tests: true, + resolve_tsconfig_paths: false, + perl_facts_path: None, + git_timeout: None, + git_candidate: None, + production_like_targets: Default::default(), + test_harnesses: vec![crate::config::TestHarnessRegistration { + registration_id: "mimic-suite".to_string(), + target: std::path::PathBuf::from("src/price_mimic.rs"), + kind: crate::config::TestHarnessKind::CustomHarnessTarget, + adapter: crate::config::TestHarnessAdapter::LibtestMimicV1, + marker: "libtest_mimic".to_string(), + }], + }, + &OraclePolicy::default(), + &changed_files, + )?; + let finding_files = result + .findings + .iter() + .map(|finding| { + finding + .probe + .location + .file + .to_string_lossy() + .replace('\\', "/") + }) + .collect::>(); + assert!( + finding_files + .iter() + .all(|file| !file.ends_with("src/price_mimic.rs")), + "a registered harness target must not seed production probes: {finding_files:?}" + ); + assert!( + finding_files + .iter() + .any(|file| file.ends_with("src/unregistered_helper.rs")), + "an unregistered sibling stays a production subject: {finding_files:?}" + ); + // The harness registry's subject facts ride on the diff result. + assert_eq!(result.harness_projections.len(), 1); + assert_eq!(result.harness_projections[0].registration_id, "mimic-suite"); + assert!( + result.harness_projections[0] + .subjects + .iter() + .any(|subject| subject.name == "price_at_boundary"), + "the exact trial registration is a projected subject" + ); + Ok(()) + } + #[test] fn diff_analysis_opt_in_restores_production_like_analysis() -> Result<(), String> { // #3283: `production_like_targets` restores ordinary production @@ -4226,6 +4390,7 @@ let _ = (result, note, raw);"##, git_timeout: None, git_candidate: None, production_like_targets: production_like, + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &changed_files, diff --git a/crates/ripr/src/analysis/language/typescript/mod.rs b/crates/ripr/src/analysis/language/typescript/mod.rs index 9848c470fe5..54cd8aa86b0 100644 --- a/crates/ripr/src/analysis/language/typescript/mod.rs +++ b/crates/ripr/src/analysis/language/typescript/mod.rs @@ -294,6 +294,7 @@ impl LanguageAdapter for TypeScriptAdapter { .collect::, String>>()?; Ok(LanguageDiffResult { findings, + harness_projections: Vec::new(), changed_files: changed_count, candidate_line_count: 0, changed_files_by_language, @@ -320,6 +321,7 @@ impl LanguageAdapter for TypeScriptAdapter { // Rust-Only" for the limitation contract. Ok(LanguageRepoResult { findings: Vec::new(), + harness_projections: Vec::new(), production_files: 0, skipped_files: 0, }) diff --git a/crates/ripr/src/analysis/language/typescript/tests.rs b/crates/ripr/src/analysis/language/typescript/tests.rs index bf7bb2d1a96..0670de7d72c 100644 --- a/crates/ripr/src/analysis/language/typescript/tests.rs +++ b/crates/ripr/src/analysis/language/typescript/tests.rs @@ -4068,6 +4068,7 @@ fn analyze_diff_returns_zero_findings_and_counts_accepted_files() -> Result<(), git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let policy = OraclePolicy::default(); @@ -4101,6 +4102,7 @@ fn analyze_diff_splits_changed_files_into_typescript_and_javascript() -> Result< git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let policy = OraclePolicy::default(); @@ -4136,6 +4138,7 @@ fn analyze_repo_returns_empty_scaffold() -> Result<(), String> { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let policy = OraclePolicy::default(); @@ -7400,6 +7403,7 @@ fn delta5_verify_command_absent_from_missing_list_when_runner_resolved() -> Resu git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let policy = OraclePolicy::default(); @@ -7495,6 +7499,7 @@ fn delta5_verify_command_stays_in_missing_list_when_runner_unresolved() -> Resul git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), resolved_subject_identity: None, }; let policy = OraclePolicy::default(); diff --git a/crates/ripr/src/analysis/mod.rs b/crates/ripr/src/analysis/mod.rs index 8045b672858..878e5a7a2be 100644 --- a/crates/ripr/src/analysis/mod.rs +++ b/crates/ripr/src/analysis/mod.rs @@ -5,6 +5,7 @@ mod classify; mod diff; mod extract; mod facts; +pub(crate) mod harness_projection; mod language; mod pipeline; mod probes; @@ -176,6 +177,7 @@ pub(crate) fn targeted_typescript_findings_for_scope( git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }; let result = TypeScriptAdapter.analyze_diff( &options, @@ -423,6 +425,10 @@ pub struct AnalysisOptions { /// production behavior even though their layout or Cargo target /// declares evidence role. Empty by default. pub production_like_targets: std::collections::BTreeSet, + /// Repository-governed test-harness registrations (#3532): exact + /// configured custom-harness targets and registered test-producing + /// attributes. Empty by default — nothing is inferred. + pub test_harnesses: Vec, /// Immutable Git candidate subject (#3237 / #3276 R1). Threaded from /// `CheckInput` so the object producer (#3277) can consume it here; /// no current analysis path executes it, and `run_check` rejects @@ -547,6 +553,11 @@ impl LanguageRunStatus { #[derive(Clone, Debug)] pub struct AnalysisResult { + /// Test-harness registry projections (#3532): what each exact + /// registration established for this run — harness kind, provenance, + /// subject identity, selector capability, and typed limitations. + /// Empty when the repository has no registrations. + pub harness_projections: Vec, /// Producer-owned completeness and limitation facts. Diff/worktree /// pipelines populate this; repo-scope analysis has no diff denominator. pub(crate) analysis_outcome: Option, @@ -857,6 +868,7 @@ index 0000000..1111111 100644 git_candidate: None, resolved_subject_identity: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }) .unwrap(); assert!(!out.findings.is_empty()); @@ -879,6 +891,7 @@ index 0000000..1111111 100644 git_candidate: None, resolved_subject_identity: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }) .unwrap(); assert!(instant.findings.iter().any(|finding| { @@ -932,6 +945,7 @@ fn premium_customer_gets_discount() { git_candidate: None, resolved_subject_identity: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), })?; if out.findings.is_empty() { @@ -1080,6 +1094,7 @@ fn test_with_predicate() { git_candidate: None, resolved_subject_identity: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), })?; for finding in &out.findings { @@ -1148,6 +1163,7 @@ index 0000000..1111111 100644 git_candidate: None, resolved_subject_identity: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), })?; if !diff_out.findings.is_empty() { @@ -1166,6 +1182,7 @@ index 0000000..1111111 100644 git_candidate: None, resolved_subject_identity: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), })?; if repo_out.findings.is_empty() { @@ -1210,6 +1227,7 @@ mod git_candidate_entry_tests { git_candidate: None, resolved_subject_identity: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }) } diff --git a/crates/ripr/src/analysis/pipeline.rs b/crates/ripr/src/analysis/pipeline.rs index 6f8cbff48df..020669e958c 100644 --- a/crates/ripr/src/analysis/pipeline.rs +++ b/crates/ripr/src/analysis/pipeline.rs @@ -255,6 +255,8 @@ fn run_pipeline_for_diff_text( let parsed_diff = diff::parse_unified_diff_bounded_with_metadata(diff_text)?; let changed_files = parsed_diff.changed_files; let mut limitations = parsed_diff.limitations; + let mut harness_projections: Vec = + Vec::new(); let deleted_file_count = parsed_diff.deleted_file_count; let submodule_file_count = parsed_diff.submodule_file_count; let renamed_file_count = parsed_diff.renamed_file_count; @@ -311,6 +313,7 @@ fn run_pipeline_for_diff_text( } limitations.extend(result.limitations); partial_scope = result.partial_scope.clone(); + harness_projections.extend(result.harness_projections); findings.extend(result.findings); rust_changed_files += result.changed_files; candidate_line_count += result.candidate_line_count; @@ -571,6 +574,7 @@ fn run_pipeline_for_diff_text( )?); Ok(AnalysisResult { + harness_projections, analysis_outcome, summary: summary_result, findings, @@ -675,6 +679,9 @@ pub(crate) fn run_repo_pipeline_with_oracle_policy_and_generated_file_patterns( let mut rust_production_files: usize = 0; let mut files_by_language: Vec<(LanguageId, usize)> = Vec::new(); let mut language_runs: Vec = Vec::new(); + let mut rust_harness_projections: Vec< + crate::analysis::harness_projection::TestHarnessProjection, + > = Vec::new(); for language in languages { cancellation::checkpoint()?; // Non-abort contract (see the diff loop above): preview-language @@ -697,6 +704,7 @@ pub(crate) fn run_repo_pipeline_with_oracle_policy_and_generated_file_patterns( )), }); } + rust_harness_projections = result.harness_projections; findings.extend(result.findings); rust_production_files += result.production_files; files_by_language.push((LanguageId::Rust, result.production_files)); @@ -740,6 +748,7 @@ pub(crate) fn run_repo_pipeline_with_oracle_policy_and_generated_file_patterns( } Ok(AnalysisResult { + harness_projections: rust_harness_projections, analysis_outcome: None, summary: summary_result, findings, @@ -1142,6 +1151,7 @@ mod tests { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::Rust], @@ -1194,6 +1204,7 @@ mod tests { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::Rust], @@ -1325,6 +1336,7 @@ mod tests { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::Rust], @@ -1413,6 +1425,7 @@ mod tests { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::Rust], @@ -1443,6 +1456,7 @@ mod tests { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::Rust], @@ -1468,6 +1482,7 @@ mod tests { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }; let combined = "diff --cc src/lib.rs\n\ index 1111111,2222222..3333333\n\ @@ -1536,6 +1551,7 @@ mod tests { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::Rust], @@ -1577,6 +1593,7 @@ mod tests { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::Rust, LanguageId::Perl], @@ -1681,6 +1698,7 @@ mod tests { git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::Rust, LanguageId::Perl], @@ -1763,6 +1781,7 @@ index 0000000..1111111 100644 git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::TypeScript, LanguageId::Python], @@ -1819,6 +1838,7 @@ index 0000000..1111111 100644 git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::Rust, LanguageId::Python], @@ -1876,6 +1896,7 @@ index 0000000..1111111 100644 git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::TypeScript], @@ -1936,6 +1957,7 @@ index 0000000..1111111 100644 git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::TypeScript], @@ -1993,6 +2015,7 @@ index 0000000..1111111 100644 git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::Rust], @@ -2064,6 +2087,7 @@ index 0000000..1111111 100644 git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::Rust], @@ -2108,6 +2132,7 @@ index 0000000..1111111 100644 git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::Rust, LanguageId::Perl], @@ -2154,6 +2179,7 @@ index 0000000..1111111 100644 git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::Rust], @@ -2198,6 +2224,7 @@ index 0000000..1111111 100644 git_timeout: None, git_candidate: None, production_like_targets: Default::default(), + test_harnesses: Vec::new(), }, &OraclePolicy::default(), &[LanguageId::TypeScript, LanguageId::Python], diff --git a/crates/ripr/src/analysis/rust_index.rs b/crates/ripr/src/analysis/rust_index.rs index 216d79cd8db..84d87f7509e 100644 --- a/crates/ripr/src/analysis/rust_index.rs +++ b/crates/ripr/src/analysis/rust_index.rs @@ -19,11 +19,12 @@ pub(crate) use super::extract::{ }; use super::facts::ModulePathTarget; pub(crate) use super::facts::build_index_from_loaded_files_with_cache; +pub(crate) use super::facts::build_index_from_loaded_files_with_cache_and_test_harnesses; #[cfg(test)] pub use super::facts::{CallFact, LiteralFact, ReturnFact}; pub use super::facts::{ FileFacts, FunctionFact, FunctionSummary, OracleFact, ProbeShapeFact, RustIndex, TestFact, - TestSummary, build_index, + TestSummary, build_index, build_index_with_test_harnesses, }; #[cfg(test)] use super::syntax::LexicalRustSyntaxAdapter; diff --git a/crates/ripr/src/analysis/seam_inventory.rs b/crates/ripr/src/analysis/seam_inventory.rs index 0c3f7037c17..7d92718b3e3 100644 --- a/crates/ripr/src/analysis/seam_inventory.rs +++ b/crates/ripr/src/analysis/seam_inventory.rs @@ -76,6 +76,7 @@ pub(crate) fn inventory_seams_at_with_config( let mut context = workspace::context_for_files(root, rust_files.iter().map(|path| path.as_path())); context.production_like_targets = config.analysis().production_like_targets().clone(); + context.harness_targets = harness_targets_from_config(config); let production_files: Vec = rust_files .iter() .filter(|p| workspace::classify_with(p, &context).seeds_production_findings()) @@ -85,7 +86,11 @@ pub(crate) fn inventory_seams_at_with_config( // Index the full set so `find_owner_function` can resolve owners // even when the seam appears in a file the production filter // includes but tests reference. - let index = rust_index::build_index(root, &rust_files)?; + let index = rust_index::build_index_with_test_harnesses( + root, + &rust_files, + harness_registrations(config), + )?; Ok(inventory_seams_from_index(&production_files, &index)) } @@ -387,6 +392,7 @@ pub(crate) fn inventory_classified_seams_uncached_with_config( let mut uncached_context = workspace::context_for_files(root, rust_files.iter().map(|path| path.as_path())); uncached_context.production_like_targets = config.analysis().production_like_targets().clone(); + uncached_context.harness_targets = harness_targets_from_config(config); let production_files: Vec = rust_files .iter() .filter(|p| workspace::classify_with(p, &uncached_context).seeds_production_findings()) @@ -395,7 +401,11 @@ pub(crate) fn inventory_classified_seams_uncached_with_config( trace_latency_phase("filter_production_files", "ok", filter_started.elapsed()); let index_started = Instant::now(); - let mut index = match rust_index::build_index(root, &rust_files) { + let mut index = match rust_index::build_index_with_test_harnesses( + root, + &rust_files, + harness_registrations(config), + ) { Ok(index) => { trace_latency_phase("build_index", "ok", index_started.elapsed()); index @@ -559,13 +569,18 @@ fn inventory_seam_grip_class_counts_uncached_with_config( let mut context = workspace::context_for_files(root, rust_files.iter().map(|path| path.as_path())); context.production_like_targets = config.analysis().production_like_targets().clone(); + context.harness_targets = harness_targets_from_config(config); let production_files: Vec = rust_files .iter() .filter(|p| workspace::classify_with(p, &context).seeds_production_findings()) .cloned() .collect(); - let mut index = rust_index::build_index(root, &rust_files)?; + let mut index = rust_index::build_index_with_test_harnesses( + root, + &rust_files, + harness_registrations(config), + )?; rust_index::apply_oracle_policy(&mut index, config.oracles()); let seams = inventory_seams_from_index(&production_files, &index); let mut counts = SeamGripClassCounts::new(seams.len()); @@ -593,8 +608,11 @@ fn inventory_compact_classified_seams_from_state_with_config( ), Duration::ZERO, ); - let mut cached = - rust_index::build_index_from_loaded_files_with_cache(&state.workspace_root, &state.files)?; + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + &state.workspace_root, + &state.files, + harness_registrations(config), + )?; cancellation::checkpoint()?; trace_latency_phase( "file_fact_cache", @@ -636,8 +654,11 @@ fn inventory_classified_seams_from_state_with_config( ), Duration::ZERO, ); - let mut cached = - rust_index::build_index_from_loaded_files_with_cache(&state.workspace_root, &state.files)?; + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + &state.workspace_root, + &state.files, + harness_registrations(config), + )?; trace_latency_phase( "file_fact_cache", &cached.file_fact_cache.status_label(), @@ -705,8 +726,11 @@ pub(crate) fn inventory_changed_test_classified_seams_at_with_config_node( let state = collect_workspace_state(root, config)?; let workspace_cache_key = state.cache_key(); let changed_test = normalized_inventory_path(changed_test); - let mut cached = - rust_index::build_index_from_loaded_files_with_cache(&state.workspace_root, &state.files)?; + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + &state.workspace_root, + &state.files, + harness_registrations(config), + )?; rust_index::apply_oracle_policy(&mut cached.index, config.oracles()); let selected_tests = cached @@ -825,8 +849,11 @@ pub(crate) fn inventory_diff_scoped_classified_seams_at_with_config( ), Duration::ZERO, ); - let mut cached = - rust_index::build_index_from_loaded_files_with_cache(&state.workspace_root, &state.files)?; + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + &state.workspace_root, + &state.files, + harness_registrations(config), + )?; trace_latency_phase( "file_fact_cache", &cached.file_fact_cache.status_label(), @@ -1057,8 +1084,11 @@ fn inventory_seam_grip_class_counts_from_state_with_config( ), Duration::ZERO, ); - let mut cached = - rust_index::build_index_from_loaded_files_with_cache(&state.workspace_root, &state.files)?; + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + &state.workspace_root, + &state.files, + harness_registrations(config), + )?; trace_latency_phase( "file_fact_cache", &cached.file_fact_cache.status_label(), @@ -1076,6 +1106,24 @@ fn inventory_seam_grip_class_counts_from_state_with_config( Ok(counts) } +/// Exact registered test-harness target identities (#3532), normalized to +/// the forward-slashed workspace-relative form the role context compares. +fn harness_targets_from_config(config: &RiprConfig) -> std::collections::BTreeSet { + config + .analysis() + .test_harnesses() + .iter() + .map(|registration| registration.target.clone()) + .collect() +} + +/// Registration list for the harness-aware index builds (#3532). Empty +/// without registrations; the index build is then a no-op for the +/// registry and every output stays byte-identical. +fn harness_registrations(config: &RiprConfig) -> &[crate::config::TestHarnessRegistration] { + config.analysis().test_harnesses() +} + fn production_files_from_state_with_role( state: &OwnedWorkspaceState, config: &RiprConfig, @@ -1087,6 +1135,7 @@ fn production_files_from_state_with_role( state.files.iter().map(|(path, _)| path.as_path()), ); context.production_like_targets = config.analysis().production_like_targets().clone(); + context.harness_targets = harness_targets_from_config(config); state .files .iter() diff --git a/crates/ripr/src/analysis/syntax/mod.rs b/crates/ripr/src/analysis/syntax/mod.rs index 46ae6703ff1..a6f6b0ca228 100644 --- a/crates/ripr/src/analysis/syntax/mod.rs +++ b/crates/ripr/src/analysis/syntax/mod.rs @@ -1,6 +1,6 @@ mod adapter; pub(crate) mod lexical; -mod ra; +pub(crate) mod ra; pub use adapter::{ LexicalRustSyntaxAdapter, RaRustSyntaxAdapter, RustSyntaxAdapter, SyntaxNodeFact, TextRange, diff --git a/crates/ripr/src/analysis/syntax/ra.rs b/crates/ripr/src/analysis/syntax/ra.rs index 73d9eda1e4a..f6f95d1145b 100644 --- a/crates/ripr/src/analysis/syntax/ra.rs +++ b/crates/ripr/src/analysis/syntax/ra.rs @@ -1062,7 +1062,7 @@ fn extract_parser_oracles( assertions } -fn is_assertion_macro(macro_name: &str) -> bool { +pub(crate) fn is_assertion_macro(macro_name: &str) -> bool { matches!( macro_name, "assert" | "assert_eq" | "assert_ne" | "assert_matches" | "matches" @@ -1070,12 +1070,12 @@ fn is_assertion_macro(macro_name: &str) -> bool { || macro_name.contains("snapshot") } -struct LineIndex { +pub(crate) struct LineIndex { starts: Vec, } impl LineIndex { - fn new(text: &str) -> Self { + pub(crate) fn new(text: &str) -> Self { let mut starts = vec![0]; for (index, byte) in text.bytes().enumerate() { if byte == b'\n' { @@ -1085,11 +1085,11 @@ impl LineIndex { Self { starts } } - fn line(&self, offset: TextSize) -> usize { + pub(crate) fn line(&self, offset: TextSize) -> usize { self.line_from_offset(text_size_to_usize(offset)) } - fn line_for_range_end(&self, offset: TextSize) -> usize { + pub(crate) fn line_for_range_end(&self, offset: TextSize) -> usize { self.line_from_offset(text_size_to_usize(offset).saturating_sub(1)) } @@ -1106,7 +1106,7 @@ fn text_size_to_usize(offset: TextSize) -> usize { value as usize } -fn slice_text(text: &str, start: TextSize, end: TextSize) -> String { +pub(crate) fn slice_text(text: &str, start: TextSize, end: TextSize) -> String { let start = text_size_to_usize(start); let end = text_size_to_usize(end); text.get(start..end).unwrap_or("").to_string() diff --git a/crates/ripr/src/analysis/workspace/source_role.rs b/crates/ripr/src/analysis/workspace/source_role.rs index d5aafeb9c00..ede900b90ca 100644 --- a/crates/ripr/src/analysis/workspace/source_role.rs +++ b/crates/ripr/src/analysis/workspace/source_role.rs @@ -9,15 +9,18 @@ //! `ripr.toml`) — a repository that intentionally treats a test-support //! target as production-like behavior restores ordinary production //! analysis for that target only; -//! 2. declared Cargo targets (`[[test]]` / `[[bench]]` with an explicit +//! 2. registered test-harness targets (`[analysis.test_harnesses]`, +//! #3532) — exact configured custom-harness and registered-test-producer +//! files are evidence role; +//! 3. declared Cargo targets (`[[test]]` / `[[bench]]` with an explicit //! `path = ...`) — confirms evidence role even outside the default //! `tests/` / `benches/` layouts, which is what lets a confirmed //! `*_test.rs` / `test_*.rs` convention carry evidence role while an //! unconfirmed filename stays a production subject; -//! 3. package layout (`tests/`, `benches/`, `examples/`) and the +//! 4. package layout (`tests/`, `benches/`, `examples/`) and the //! non-source directories (`fixtures/`, `target/`, `.git/`, `.ripr/`, //! `node_modules/`, `editors/`); -//! 4. everything else under a source layout is a production subject. +//! 5. everything else under a source layout is a production subject. //! //! A filename convention alone never classifies a file: without target //! metadata or layout corroboration, `src/foo_test.rs` remains a @@ -88,8 +91,9 @@ impl SourceRole { } } -/// Authoritative context beyond package layout: declared Cargo targets -/// and the repository's explicit production-like opt-in. +/// Authoritative context beyond package layout: declared Cargo targets, +/// the repository's explicit production-like opt-in, and registered +/// test-harness targets. #[derive(Clone, Debug, Default)] pub(crate) struct SourceRoleContext { /// Relative paths of files named by explicit `[[test]]` `path = ...` @@ -100,6 +104,11 @@ pub(crate) struct SourceRoleContext { pub(crate) declared_bench_targets: BTreeSet, /// Relative paths opted in via `[analysis] production_like_targets`. pub(crate) production_like_targets: BTreeSet, + /// Relative paths registered via `[analysis.test_harnesses]` (#3532): + /// exact configured custom-harness targets and registered test + /// producers. Evidence role; the explicit production-like opt-in + /// still wins over a harness registration. + pub(crate) harness_targets: BTreeSet, } impl SourceRoleContext { @@ -117,6 +126,9 @@ pub(crate) fn classify_with(path: &Path, context: &SourceRoleContext) -> SourceR if context.production_like_targets.contains(&normalized) { return SourceRole::ProductionLikeTestInfrastructure; } + if context.harness_targets.contains(&normalized) { + return SourceRole::TestEvidence; + } if context.declared_test_targets.contains(&normalized) { return SourceRole::TestEvidence; } @@ -342,6 +354,53 @@ mod tests { ); } + #[test] + fn harness_registrations_confirm_evidence_role_but_opt_in_wins() { + // #3532: an exact registered harness target is evidence role even + // outside the default layouts; the explicit production-like opt-in + // stays a separate, stronger control; nothing leaks to siblings. + let mut context = SourceRoleContext::empty(); + context + .harness_targets + .insert(PathBuf::from("src/custom_mimic.rs")); + context + .production_like_targets + .insert(PathBuf::from("tests/opted_in.rs")); + context + .declared_test_targets + .insert(PathBuf::from("src/contract_test.rs")); + + assert_eq!( + classify_with(Path::new("src/custom_mimic.rs"), &context), + SourceRole::TestEvidence, + "a registered harness target is evidence role in any layout" + ); + assert!( + !classify_with(Path::new("src/custom_mimic.rs"), &context).seeds_production_findings(), + "a registered harness target never seeds production seams" + ); + assert_eq!( + classify_with(Path::new("tests/opted_in.rs"), &context), + SourceRole::ProductionLikeTestInfrastructure, + "the production-like opt-in wins over harness role" + ); + assert_eq!( + classify_with(Path::new("tests/other.rs"), &context), + SourceRole::TestEvidence + ); + assert_eq!( + classify_with(Path::new("src/undeclared.rs"), &context), + SourceRole::ProductionSubject, + "registration must not leak to unregistered files" + ); + // Declared-target confirmation and harness registration agree on + // evidence role; priority between them is not observable. + assert_eq!( + classify_with(Path::new("src/contract_test.rs"), &context), + SourceRole::TestEvidence + ); + } + #[test] fn windows_paths_match_context_sets() { let mut context = SourceRoleContext::empty(); diff --git a/crates/ripr/src/app.rs b/crates/ripr/src/app.rs index 53b0c23fef9..ae4bb33326b 100644 --- a/crates/ripr/src/app.rs +++ b/crates/ripr/src/app.rs @@ -187,6 +187,11 @@ impl Mode { pub struct CheckOutput { /// Output schema version for machine consumers. pub schema_version: String, + /// Test-harness registry projections (#3532): what each exact + /// registration established for this run. Empty when the repository + /// has no registrations, so every existing consumer output is + /// unchanged. + pub harness_projections: Vec, /// Tool identifier. pub tool: String, /// Mode used for this analysis. diff --git a/crates/ripr/src/app/check.rs b/crates/ripr/src/app/check.rs index e020165d41d..275d7d66ecb 100644 --- a/crates/ripr/src/app/check.rs +++ b/crates/ripr/src/app/check.rs @@ -84,6 +84,7 @@ pub fn repo_seam_inventory_input(input: CheckInput) -> CheckOutput { output_builder::check_output_from_analysis( input, AnalysisResult { + harness_projections: Vec::new(), analysis_outcome: None, summary: Summary::default(), findings: Vec::new(), diff --git a/crates/ripr/src/app/check/options_builder.rs b/crates/ripr/src/app/check/options_builder.rs index 1dec645f601..75dce7f019a 100644 --- a/crates/ripr/src/app/check/options_builder.rs +++ b/crates/ripr/src/app/check/options_builder.rs @@ -17,6 +17,7 @@ pub(crate) fn analysis_options_from_input_and_config( git_timeout: input.git_timeout, git_candidate: input.git_candidate.clone(), production_like_targets: config.analysis().production_like_targets().clone(), + test_harnesses: config.analysis().test_harnesses().to_vec(), resolved_subject_identity: None, } } diff --git a/crates/ripr/src/app/check/output_builder.rs b/crates/ripr/src/app/check/output_builder.rs index 833b2128206..8d299399299 100644 --- a/crates/ripr/src/app/check/output_builder.rs +++ b/crates/ripr/src/app/check/output_builder.rs @@ -7,6 +7,7 @@ pub(super) fn check_output_from_analysis( analysis: AnalysisResult, ) -> CheckOutput { CheckOutput { + harness_projections: analysis.harness_projections, schema_version: CHECK_OUTPUT_SCHEMA_VERSION.to_string(), tool: "ripr".to_string(), mode: input.mode, diff --git a/crates/ripr/src/app/check_artifact.rs b/crates/ripr/src/app/check_artifact.rs index 7edda4fb47c..5f6aba108ba 100644 --- a/crates/ripr/src/app/check_artifact.rs +++ b/crates/ripr/src/app/check_artifact.rs @@ -429,11 +429,12 @@ fn closed_analysis_options_view(options: &AnalysisOptions) -> (bool, Option<&Pat // Git candidate subjects before analysis, so an // artifact can never carry one until #3277/#3278 // record the subject's resolved identity here + test_harnesses: _, // recorded via the config identity production_like_targets: _, // recorded via the config identity - // allowlist: the opt-in originates in - // `[analysis]` (#3283), which the - // versioned config identity already - // hashes field-by-field + // allowlist: the opt-in originates in + // `[analysis]` (#3283), which the + // versioned config identity already + // hashes field-by-field } = options; (*include_unchanged_tests, perl_facts_path.as_deref()) } diff --git a/crates/ripr/src/app/tests/mod.rs b/crates/ripr/src/app/tests/mod.rs index ccda67a0dea..0b996f33568 100644 --- a/crates/ripr/src/app/tests/mod.rs +++ b/crates/ripr/src/app/tests/mod.rs @@ -76,6 +76,7 @@ fn sample_finding(file: &str, line: usize) -> Finding { fn check_output_with(findings: Vec) -> CheckOutput { CheckOutput { + harness_projections: Vec::new(), schema_version: CHECK_OUTPUT_SCHEMA_VERSION.to_string(), tool: "ripr".to_string(), mode: Mode::Draft, diff --git a/crates/ripr/src/config.rs b/crates/ripr/src/config.rs index 106bf57a2ed..dd56bc65f51 100644 --- a/crates/ripr/src/config.rs +++ b/crates/ripr/src/config.rs @@ -17,7 +17,8 @@ mod python; use model::{BunUbProfileConfig, FindingSeverityConfig, ProfilesConfig, SeamSeverityConfig}; pub use model::{ CHECK_ARTIFACT_CONFIG_IDENTITY_VERSION, CheckInputExplicit, ConfigIdentityRole, ConfigSeverity, - LspDiagnosticProfile, OraclePolicy, PerlConfig, RiprConfig, SeverityConfig, TypescriptConfig, + LspDiagnosticProfile, OraclePolicy, PerlConfig, RiprConfig, SeverityConfig, TestHarnessAdapter, + TestHarnessKind, TestHarnessRegistration, TypescriptConfig, }; #[cfg(test)] pub(crate) use python::PYTHON_PROJECT_EXCLUDED_DIRS; @@ -237,13 +238,17 @@ pub(crate) fn check_artifact_config_identity_hash(config: &RiprConfig) -> String /// comparable). Closed set: when the producer starts consuming another config /// field, add it here in the same PR; do not widen the filter to whole /// sections. -pub(crate) const REPO_EXPOSURE_CONSUMED_CONFIG_FIELDS: [&str; 4] = [ +pub(crate) const REPO_EXPOSURE_CONSUMED_CONFIG_FIELDS: [&str; 5] = [ "oracles.broad_error_strength", "oracles.mock_expectation_strength", "oracles.snapshot_strength", // The production-like opt-in changes which files are production // subjects in the repo seam inventory (#3283). "analysis.production_like_targets", + // Harness registrations change which files are evidence subjects and + // which functions are executable tests in the repo seam inventory + // (#3532). + "analysis.test_harnesses", ]; /// Canonical config identity for the repo-exposure artifact input identity @@ -313,6 +318,9 @@ impl RiprConfig { } config.analysis.production_like_targets = parsed; } + if let Some(registrations) = analysis.test_harnesses { + config.analysis.test_harnesses = parse_test_harness_registrations(registrations)?; + } } if let Some(oracles) = raw.oracles { if let Some(strength) = oracles.snapshot_strength { @@ -533,6 +541,20 @@ struct RawAnalysisConfig { mode: Option, include_unchanged_tests: Option, production_like_targets: Option>, + test_harnesses: Option>, +} + +/// Raw `[analysis.test_harnesses]` entry (#3532). Every field is exact: +/// unknown values, root escapes, and kind/adapter mismatches fail closed +/// at parse time with named errors. +#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct RawTestHarnessRegistration { + registration_id: Option, + target: Option, + kind: Option, + adapter: Option, + marker: Option, } #[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] @@ -817,6 +839,92 @@ fn parse_relative_path(field: &str, value: &str) -> Result { Ok(path) } +/// Parse and validate `[analysis.test_harnesses]` entries (#3532). +/// +/// Fail-closed rules, each with a named error: +/// - every field is required (missing fields fail, not default); +/// - `target` must be a repository-relative path ([`parse_relative_path`]); +/// - `kind` and `adapter` must be known values (unknown versions fail +/// closed) and must match each other; +/// - `marker` must be an exact identifier path — no wildcards, globs, +/// prefixes, or attribute arguments; +/// - duplicate `registration_id`s or two registrations claiming the same +/// `target` are non-clean and named. +fn parse_test_harness_registrations( + registrations: Vec, +) -> Result, String> { + let mut parsed = Vec::with_capacity(registrations.len()); + let mut seen_ids = std::collections::BTreeSet::new(); + let mut seen_targets = std::collections::BTreeSet::new(); + for (index, raw) in registrations.into_iter().enumerate() { + let position = format!("analysis.test_harnesses[{index}]"); + let registration_id = required_text(&position, "registration_id", raw.registration_id)?; + if !seen_ids.insert(registration_id.clone()) { + return Err(format!( + "{position}: registration_id `{registration_id}` is registered twice; conflicting registrations fail closed" + )); + } + let target = parse_relative_path( + &format!("{position}.target"), + &required_text(&position, "target", raw.target)?, + )?; + if !seen_targets.insert(normalize_identity_path(&target)) { + return Err(format!( + "{position}: target `{}` is claimed by two registrations; conflicting registrations fail closed", + target.to_string_lossy().replace('\\', "/") + )); + } + let kind = TestHarnessKind::parse(&required_text(&position, "kind", raw.kind)?)?; + let adapter = + TestHarnessAdapter::parse(&required_text(&position, "adapter", raw.adapter)?)?; + if !adapter.supports_kind(kind) { + return Err(format!( + "{position}: adapter `{}` does not support kind `{}`; the mismatch fails closed", + adapter.as_str(), + kind.as_str() + )); + } + let marker = required_text(&position, "marker", raw.marker)?; + if !marker_path_is_exact(&marker) { + return Err(format!( + "{position}: marker `{marker}` must be an exact identifier path (e.g. `libtest_mimic`, `myco::contract_test`) without wildcards, prefixes, or arguments" + )); + } + parsed.push(TestHarnessRegistration { + registration_id, + target, + kind, + adapter, + marker, + }); + } + Ok(parsed) +} + +fn required_text(position: &str, field: &str, value: Option) -> Result { + match value { + Some(text) if !text.trim().is_empty() => Ok(text.trim().to_string()), + Some(_) => Err(format!("{position}.{field} must not be empty")), + None => Err(format!("{position}.{field} is required")), + } +} + +fn normalize_identity_path(path: &Path) -> String { + path.to_string_lossy().replace('\\', "/") +} + +/// Exact marker paths only: `::`-separated Rust identifiers, no +/// wildcards, globs, whitespace, or attribute arguments. A lookalike +/// marker (`myco::contract_test*`, `myco::contract_test(`) never parses. +fn marker_path_is_exact(marker: &str) -> bool { + !marker.is_empty() + && marker.split("::").all(|segment| { + let mut characters = segment.chars(); + matches!(characters.next(), Some(first) if first.is_ascii_alphabetic() || first == '_') + && characters.all(|rest| rest.is_ascii_alphanumeric() || rest == '_') + }) +} + #[cfg(test)] mod tests; diff --git a/crates/ripr/src/config/model.rs b/crates/ripr/src/config/model.rs index a5ff9ac850c..4914b113dcd 100644 --- a/crates/ripr/src/config/model.rs +++ b/crates/ripr/src/config/model.rs @@ -83,6 +83,10 @@ pub struct AnalysisConfig { /// Workspace-relative targets opted in as production-like /// test infrastructure (#3283). Empty by default. pub production_like_targets: std::collections::BTreeSet, + /// Repository-governed test-harness registrations (#3532). Empty by + /// default: without an explicit registration, no custom harness or + /// registered test producer is recognized. + pub test_harnesses: Vec, } impl AnalysisConfig { @@ -100,6 +104,130 @@ impl AnalysisConfig { pub(crate) fn include_unchanged_tests(&self) -> Option { self.include_unchanged_tests } + + /// Repository-governed test-harness registrations (#3532): exact + /// configured inputs only — never inferred from filenames, imports, + /// macro suffixes, or function names. + pub(crate) fn test_harnesses(&self) -> &[TestHarnessRegistration] { + &self.test_harnesses + } +} + +/// The registered family of one test-harness registration (#3532). +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TestHarnessKind { + /// A custom Cargo test target (`[[test]]` with `harness = false`): + /// the whole target is evidence role and its executable subjects come + /// from the harness's own source-visible registration calls. + CustomHarnessTarget, + /// A repository-configured test-producing attribute or macro path + /// applied to functions inside one exact target file. + RegisteredAttribute, +} + +impl TestHarnessKind { + pub(crate) fn parse(value: &str) -> Result { + match value { + "custom_harness" => Ok(Self::CustomHarnessTarget), + "registered_attribute" => Ok(Self::RegisteredAttribute), + other => Err(format!( + "analysis.test_harnesses.kind `{other}` is unknown; expected \"custom_harness\" or \"registered_attribute\" (unknown harness kinds fail closed)" + )), + } + } + + pub(crate) fn as_str(self) -> &'static str { + match self { + Self::CustomHarnessTarget => "custom_harness", + Self::RegisteredAttribute => "registered_attribute", + } + } +} + +/// The exact adapter generation bound to one registration (#3532). +/// Unknown versions fail closed at parse time. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TestHarnessAdapter { + /// libtest-mimic custom harness adapter, generation 1: bounded + /// source-visible `Trial::test("name", ...)` registrations with + /// stable names. + LibtestMimicV1, + /// Exact registered test-producing attribute adapter, generation 1: + /// functions carrying the exact registered attribute path in one + /// target file. + ExactAttributeV1, +} + +impl TestHarnessAdapter { + pub(crate) fn parse(value: &str) -> Result { + match value { + "libtest_mimic_v1" => Ok(Self::LibtestMimicV1), + "exact_attribute_v1" => Ok(Self::ExactAttributeV1), + other => Err(format!( + "analysis.test_harnesses.adapter `{other}` is unknown; expected \"libtest_mimic_v1\" or \"exact_attribute_v1\" (unknown adapter versions fail closed)" + )), + } + } + + pub(crate) fn as_str(self) -> &'static str { + match self { + Self::LibtestMimicV1 => "libtest_mimic_v1", + Self::ExactAttributeV1 => "exact_attribute_v1", + } + } + + /// The adapter generation that supports each registered family. + /// A kind/adapter mismatch is a config error, not a silent no-op. + pub(crate) fn supports_kind(self, kind: TestHarnessKind) -> bool { + matches!( + (kind, self), + ( + TestHarnessKind::CustomHarnessTarget, + TestHarnessAdapter::LibtestMimicV1 + ) | ( + TestHarnessKind::RegisteredAttribute, + TestHarnessAdapter::ExactAttributeV1 + ) + ) + } +} + +/// One repository-governed test-harness registration (#3532) — the +/// configured equivalent of `RustTestHarnessRegistrationV1`: +/// +/// - `registration_id` — stable identifier named in limitations and +/// subject provenance; +/// - `target` — exact workspace-relative file identity of the registered +/// Cargo target file (root escape fails closed at parse time); +/// - `kind` + `adapter` — harness family and adapter generation +/// (unknown versions fail closed); +/// - `marker` — exact source marker: the harness crate path for +/// `custom_harness` targets (e.g. `libtest_mimic`) or the exact +/// attribute path for `registered_attribute` targets (e.g. +/// `myco::contract_test`). Prefix/suffix lookalikes never match. +/// +/// Registration is explicit configuration only. It is never inferred +/// from filenames, crate imports, macro suffixes, or function names. +/// A registration classifies source and describes a selector route; it +/// cannot execute anything during passive analysis and grants no +/// process, network, edit, GitHub, or publication capability. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TestHarnessRegistration { + pub registration_id: String, + pub target: std::path::PathBuf, + pub kind: TestHarnessKind, + pub adapter: TestHarnessAdapter, + pub marker: String, +} + +impl TestHarnessRegistration { + /// Provenance string recorded on derived subject facts, so every + /// projection can name where the authority came from. + pub(crate) fn provenance() -> &'static str { + "ripr.toml [analysis.test_harnesses]" + } } #[derive(Clone, Debug, PartialEq, Eq)] @@ -317,6 +445,43 @@ fn canonical_generated_file_patterns(patterns: &[String]) -> String { encoded } +/// Canonical identity encoding for test-harness registrations (#3532). +/// Length-prefixed, NUL-joined, sorted — injective, so distinct +/// registration sets never hash to the same artifact identity. +fn canonical_test_harnesses_identity(registrations: &[TestHarnessRegistration]) -> String { + let mut ordered = registrations + .iter() + .map(|registration| { + let mut encoded = String::new(); + for field in [ + registration.registration_id.as_str(), + registration + .target + .to_string_lossy() + .replace('\\', "/") + .as_str(), + registration.kind.as_str(), + registration.adapter.as_str(), + registration.marker.as_str(), + ] { + encoded.push_str(&field.len().to_string()); + encoded.push(':'); + encoded.push_str(field); + encoded.push('\u{0}'); + } + encoded + }) + .collect::>(); + ordered.sort(); + + let mut identity = ordered.len().to_string(); + for encoded in ordered { + identity.push('\u{0}'); + identity.push_str(&encoded); + } + identity +} + /// `[perl]` repository configuration (Campaign 31 Phase D, #1407). /// /// When `producer` is set to `"perllsp"`, ripr invokes a Perl facts @@ -538,7 +703,7 @@ pub struct CheckInputExplicit { /// same PR. The classification is closed: the field enumerator destructures /// every config struct without `..`, so an unclassified field fails to /// compile, and a unit test pins the resulting role of every field. -pub const CHECK_ARTIFACT_CONFIG_IDENTITY_VERSION: u32 = 2; +pub const CHECK_ARTIFACT_CONFIG_IDENTITY_VERSION: u32 = 3; /// How one `ripr.toml` field participates in the check-artifact identity gate. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -596,6 +761,7 @@ impl RiprConfig { mode: _, include_unchanged_tests: _, production_like_targets, + test_harnesses, } = analysis; let OraclePolicy { snapshot_strength, @@ -684,6 +850,14 @@ impl RiprConfig { )), note: "the production-like opt-in changes which files are production subjects (#3283)", }, + ConfigIdentityField { + name: "analysis.test_harnesses", + role: ConfigIdentityRole::FindingAffecting, + // Canonical registration encoding, sorted and count-prefixed: + // injective, so distinct registration sets never collide. + value: Some(canonical_test_harnesses_identity(test_harnesses)), + note: "harness registrations change source-role classification and the test denominator (#3532)", + }, ConfigIdentityField { name: "oracles.snapshot_strength", role: ConfigIdentityRole::FindingAffecting, diff --git a/crates/ripr/src/config/tests.rs b/crates/ripr/src/config/tests.rs index f75a9820d22..fddfcdfad25 100644 --- a/crates/ripr/src/config/tests.rs +++ b/crates/ripr/src/config/tests.rs @@ -966,6 +966,7 @@ fn check_artifact_identity_fields_classify_every_config_field() -> Result<(), St let finding_affecting = [ "languages.rust.generated_file_patterns", "analysis.production_like_targets", + "analysis.test_harnesses", "oracles.broad_error_strength", "oracles.mock_expectation_strength", "oracles.snapshot_strength", @@ -1159,6 +1160,7 @@ proptest! { mode, include_unchanged_tests, production_like_targets: None, + test_harnesses: None, }), oracles: Some(RawOraclePolicy { snapshot_strength, @@ -1304,3 +1306,122 @@ fn parse_config_rejects_absolute_production_like_target() -> Result<(), String> } Ok(()) } + +fn parse_test_harnesses(toml_text: &str) -> Result, String> { + let raw = toml::from_str::(toml_text).map_err(|error| error.to_string())?; + RiprConfig::from_raw(raw).map(|config| config.analysis.test_harnesses) +} + +/// The named parse error a registration config must produce; `Err` when it +/// unexpectedly parsed. +fn harness_parse_error(toml_text: &str) -> Result { + match parse_test_harnesses(toml_text) { + Err(error) => Ok(error), + Ok(_) => Err("harness registrations must fail closed".to_string()), + } +} + +#[test] +fn parse_config_reads_exact_harness_registrations() -> Result<(), String> { + // #3532: both supported families parse with exact identities and join + // the check-artifact identity as FindingAffecting. + let config_text = r#" +[analysis] +[[analysis.test_harnesses]] +registration_id = "mimic-suite" +target = "tests/price_mimic.rs" +kind = "custom_harness" +adapter = "libtest_mimic_v1" +marker = "libtest_mimic" + +[[analysis.test_harnesses]] +registration_id = "contract-tests" +target = "crates/pricing/tests/api.rs" +kind = "registered_attribute" +adapter = "exact_attribute_v1" +marker = "myco::contract_test" +"#; + let registrations = parse_test_harnesses(config_text)?; + assert_eq!(registrations.len(), 2); + assert_eq!(registrations[0].registration_id, "mimic-suite"); + assert_eq!( + registrations[0].target, + std::path::PathBuf::from("tests/price_mimic.rs") + ); + assert_eq!(registrations[0].kind, TestHarnessKind::CustomHarnessTarget); + assert_eq!(registrations[0].adapter, TestHarnessAdapter::LibtestMimicV1); + assert_eq!(registrations[0].marker, "libtest_mimic"); + assert_eq!(registrations[1].marker, "myco::contract_test"); + + let identity = RiprConfig::from_raw( + toml::from_str::(config_text).map_err(|error| error.to_string())?, + )? + .check_artifact_identity_fields(); + let field = identity + .iter() + .find(|field| field.name == "analysis.test_harnesses") + .ok_or("identity must classify test_harnesses")?; + assert_eq!(field.role, ConfigIdentityRole::FindingAffecting); + assert!(field.value.is_some()); + Ok(()) +} + +#[test] +fn parse_config_rejects_unknown_harness_adapter_version() -> Result<(), String> { + // Unknown adapter/schema versions fail closed at parse time. + let error = harness_parse_error( + "[[analysis.test_harnesses]]\nregistration_id = 'x'\ntarget = 'tests/a.rs'\nkind = 'custom_harness'\nadapter = 'libtest_mimic_v9'\nmarker = 'libtest_mimic'\n", + )?; + assert!( + error.contains("libtest_mimic_v9") && error.contains("unknown"), + "the error must name the rejected value: {error}" + ); + Ok(()) +} + +#[test] +fn parse_config_rejects_harness_kind_adapter_mismatch() -> Result<(), String> { + let error = harness_parse_error( + "[[analysis.test_harnesses]]\nregistration_id = 'x'\ntarget = 'tests/a.rs'\nkind = 'registered_attribute'\nadapter = 'libtest_mimic_v1'\nmarker = 'contract_test'\n", + )?; + assert!(error.contains("does not support kind"), "{error}"); + Ok(()) +} + +#[test] +fn parse_config_rejects_harness_root_escape_and_lookalike_marker() -> Result<(), String> { + // Root escape fails closed through the shared relative-path rule. + let escape_error = harness_parse_error( + "[[analysis.test_harnesses]]\nregistration_id = 'x'\ntarget = '../outside/mimic.rs'\nkind = 'custom_harness'\nadapter = 'libtest_mimic_v1'\nmarker = 'libtest_mimic'\n", + )?; + assert!(escape_error.contains("target"), "{escape_error}"); + + // A lookalike wildcard marker never parses: registration is exact. + let marker_error = harness_parse_error( + "[[analysis.test_harnesses]]\nregistration_id = 'x'\ntarget = 'tests/a.rs'\nkind = 'registered_attribute'\nadapter = 'exact_attribute_v1'\nmarker = 'myco::contract_*'\n", + )?; + assert!( + marker_error.contains("exact identifier path"), + "{marker_error}" + ); + Ok(()) +} + +#[test] +fn parse_config_rejects_conflicting_harness_registrations() -> Result<(), String> { + // Duplicate registration ids are non-clean. + let id_error = harness_parse_error( + "[[analysis.test_harnesses]]\nregistration_id = 'same'\ntarget = 'tests/a.rs'\nkind = 'custom_harness'\nadapter = 'libtest_mimic_v1'\nmarker = 'libtest_mimic'\n\n[[analysis.test_harnesses]]\nregistration_id = 'same'\ntarget = 'tests/b.rs'\nkind = 'custom_harness'\nadapter = 'libtest_mimic_v1'\nmarker = 'libtest_mimic'\n", + )?; + assert!(id_error.contains("registered twice"), "{id_error}"); + + // Two registrations claiming the same target are non-clean. + let target_error = harness_parse_error( + "[[analysis.test_harnesses]]\nregistration_id = 'one'\ntarget = 'tests/a.rs'\nkind = 'custom_harness'\nadapter = 'libtest_mimic_v1'\nmarker = 'libtest_mimic'\n\n[[analysis.test_harnesses]]\nregistration_id = 'two'\ntarget = 'tests/a.rs'\nkind = 'custom_harness'\nadapter = 'libtest_mimic_v1'\nmarker = 'libtest_mimic'\n", + )?; + assert!( + target_error.contains("claimed by two registrations"), + "{target_error}" + ); + Ok(()) +} diff --git a/crates/ripr/src/lsp/diagnostics.rs b/crates/ripr/src/lsp/diagnostics.rs index 5b29781fcbd..e212d42a001 100644 --- a/crates/ripr/src/lsp/diagnostics.rs +++ b/crates/ripr/src/lsp/diagnostics.rs @@ -2288,6 +2288,12 @@ fn partition_out_of_scope_test_file_findings( .map(|finding| finding.probe.location.file.as_path()), ); context.production_like_targets = config.analysis().production_like_targets().clone(); + context.harness_targets = config + .analysis() + .test_harnesses() + .iter() + .map(|registration| registration.target.clone()) + .collect(); let mut scoped = Vec::with_capacity(findings.len()); let mut out_of_scope = 0usize; for finding in findings { diff --git a/crates/ripr/src/output/badge/tests.rs b/crates/ripr/src/output/badge/tests.rs index c181a2c3d84..4e8866c04b0 100644 --- a/crates/ripr/src/output/badge/tests.rs +++ b/crates/ripr/src/output/badge/tests.rs @@ -92,6 +92,7 @@ fn related_test(name: &str, file: &str, line: usize) -> RelatedTest { fn check_output(findings: Vec) -> CheckOutput { let defaults = CheckInput::default(); CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -1645,6 +1646,7 @@ fn check_output_with_preview_advisory( ) -> CheckOutput { let defaults = CheckInput::default(); CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, diff --git a/crates/ripr/src/output/diff_report.rs b/crates/ripr/src/output/diff_report.rs index b60f2a9ce5d..690beee7cf5 100644 --- a/crates/ripr/src/output/diff_report.rs +++ b/crates/ripr/src/output/diff_report.rs @@ -460,6 +460,7 @@ mod tests { fn diff_report_preserves_diff_complete_full_repo_limited_status() -> Result<(), String> { let report = build_diff_report( &CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -532,6 +533,7 @@ mod tests { )?; let report = build_diff_report( &CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -661,6 +663,7 @@ mod tests { use crate::analysis::PreviewLanguageAdvisory; let report = build_diff_report( &CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -715,6 +718,7 @@ mod tests { fn diff_report_omits_preview_languages_for_pure_rust_scope() -> Result<(), String> { let report = build_diff_report( &CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, diff --git a/crates/ripr/src/output/github.rs b/crates/ripr/src/output/github.rs index 310799fd9f9..128e8baceda 100644 --- a/crates/ripr/src/output/github.rs +++ b/crates/ripr/src/output/github.rs @@ -288,6 +288,7 @@ mod tests { #[test] fn render_reports_empty_findings_as_notice() { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -353,6 +354,7 @@ mod tests { #[test] fn render_uses_warning_for_exposed_and_default_message_without_stop_reason() { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -421,6 +423,7 @@ mod tests { #[test] fn render_uses_warning_annotation_for_warning_severity_findings() { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -690,6 +693,7 @@ mod tests { fn output_with_unknown_finding() -> CheckOutput { CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -973,6 +977,7 @@ mod tests { #[test] fn render_normalizes_backslash_location_path_to_forward_slash() { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, diff --git a/crates/ripr/src/output/human.rs b/crates/ripr/src/output/human.rs index fd043d538e3..6affab08fb4 100644 --- a/crates/ripr/src/output/human.rs +++ b/crates/ripr/src/output/human.rs @@ -556,6 +556,7 @@ mod tests { #[test] fn render_includes_summary_counts_and_empty_findings_message() { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -597,6 +598,7 @@ mod tests { let finding = sample_finding(); let finding_id = finding.id.clone(); let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -630,6 +632,7 @@ mod tests { #[test] fn render_replaces_hidden_block_with_more_when_nothing_is_omitted() { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -672,6 +675,7 @@ mod tests { findings.push(finding); } let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -705,6 +709,7 @@ mod tests { #[test] fn render_omits_language_breakdown_for_rust_only_run() { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -741,6 +746,7 @@ mod tests { #[test] fn render_emits_language_breakdown_when_non_rust_files_counted() { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -789,6 +795,7 @@ mod tests { }) .collect::>(); let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -837,6 +844,7 @@ mod tests { Some("Add the missing discriminator assertion.".to_string()); let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -870,6 +878,7 @@ mod tests { #[test] fn bounded_human_output_reports_missing_scope_as_start_here_state() { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -904,6 +913,7 @@ mod tests { .evidence .push("suggested_verify_command: npm test -- pricing".to_string()); let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -1206,6 +1216,7 @@ mod tests { fn single_finding_output(finding: Finding) -> CheckOutput { CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -1302,6 +1313,7 @@ mod tests { .push("suggested_verify_command: npm test -- pricing".to_string()); let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -1339,6 +1351,7 @@ mod tests { second.id = "second".to_string(); second.probe.location.line = 8; let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -1375,6 +1388,7 @@ mod tests { let finding_id = finding.id.clone(); let location = finding.probe.location.file.display().to_string(); let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -1422,6 +1436,7 @@ mod tests { let finding = sample_finding(); let finding_id = finding.id.clone(); let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -1461,6 +1476,7 @@ mod tests { #[test] fn human_output_discloses_limited_partial_scope_run_state() -> Result<(), String> { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -1530,6 +1546,7 @@ mod tests { // terminal verbatim (#2142 review): the display is escaped while the // raw path stays on the scope record. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2272,6 +2289,7 @@ mod tests { #[test] fn render_emits_preview_disclosure_when_typescript_files_in_scope() { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2312,6 +2330,7 @@ mod tests { #[test] fn render_emits_preview_disclosure_when_python_files_in_scope() { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2348,6 +2367,7 @@ mod tests { #[test] fn render_omits_preview_disclosure_for_pure_rust_scope() { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2380,6 +2400,7 @@ mod tests { fn render_preview_disclosure_count_matches_advisory_file_count() { // The file_count in the advisory must appear verbatim in the disclosure line. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2415,6 +2436,7 @@ mod tests { // is NOT enabled. The empty result must be broken by a disclosure that // says the files were not analyzed. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2472,6 +2494,7 @@ mod tests { // hardcoded string. This covers the Python path; Perl is covered by // render_emits_singular_perl_disclosure_when_adapter_disabled. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2550,6 +2573,7 @@ mod tests { // The cardinal case: bare `ripr check` produces an empty result. // `no_scope_provided: true` must emit the guidance note. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2598,6 +2622,7 @@ mod tests { // `no_scope_provided: false` must NOT emit the guidance — the result // is honest: that diff really had no probes. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2633,6 +2658,7 @@ mod tests { // the disclosure uses the approved phrasing ("does NOT mean your changed // behavior is covered") rather than any runtime claim. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2669,6 +2695,7 @@ mod tests { // --format repo-exposure-md for a full-repo scan, NOT --mode fast. // --mode is a speed tier on the diff path; it does NOT provide scope. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2703,6 +2730,7 @@ mod tests { fn render_emits_all_no_path_disclosure_when_all_findings_are_no_path() { // Primary case: findings exist but none are exposed/weak/reachable. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2753,6 +2781,7 @@ mod tests { fn render_emits_all_no_path_disclosure_for_infection_unknown_findings() { // Also fires for infection_unknown / propagation_unknown / static_unknown classes. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2800,6 +2829,7 @@ mod tests { let mut duplicate_finding = unknown_finding(); duplicate_finding.related_tests.push(related_test); let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2854,6 +2884,7 @@ mod tests { let mut finding = unknown_finding(); finding.ripr.reach.state = StageState::Yes; let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2888,6 +2919,7 @@ mod tests { // If any finding is exposed, the per-finding output carries the signal. // Do NOT emit the all-no-path note. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2921,6 +2953,7 @@ mod tests { #[test] fn render_omits_all_no_path_disclosure_when_weakly_exposed_finding_exists() { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2955,6 +2988,7 @@ mod tests { // Zero findings is a different case (handled by no-probes message). // The all-no-path disclosure must NOT fire here. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -2983,6 +3017,7 @@ mod tests { fn render_all_no_path_disclosure_uses_finding_count_not_probe_count() { // The count shown must be the no-path/unknown total (= findings), not probes. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -3017,6 +3052,7 @@ mod tests { fn render_all_no_path_disclosure_uses_conservative_static_language() { // Verify the disclosure does not use forbidden mutation-testing vocabulary. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, diff --git a/crates/ripr/src/output/json/mod.rs b/crates/ripr/src/output/json/mod.rs index 318c7c4de31..789854cf707 100644 --- a/crates/ripr/src/output/json/mod.rs +++ b/crates/ripr/src/output/json/mod.rs @@ -386,6 +386,7 @@ mod tests { #[test] fn render_adds_presentation_text_finding_alignment_when_supported() -> Result<(), String> { let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -488,6 +489,7 @@ mod tests { relation_confidence: None, }; let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -622,6 +624,7 @@ mod tests { relation_confidence: None, }; let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -1368,6 +1371,7 @@ mod tests { fn sample_output(base: Option) -> CheckOutput { CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -1502,6 +1506,7 @@ mod tests { .collect(); let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -1551,6 +1556,7 @@ mod tests { // When no_scope_provided=true the JSON output must include the // scope_disclosures additive field with scope_status=no_scope_provided. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -1608,6 +1614,7 @@ mod tests { // When no_scope_provided=false (scope was provided) the scope_disclosures // field must be absent — this is a real analyzed-empty result. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, @@ -1644,6 +1651,7 @@ mod tests { // --format repo-exposure-md and NOT --mode fast. // --mode is a speed tier; --format repo-exposure-md is the real full-repo scope. let output = CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, diff --git a/crates/ripr/src/output/json/report.rs b/crates/ripr/src/output/json/report.rs index 388fb6f76d6..a3f569496c2 100644 --- a/crates/ripr/src/output/json/report.rs +++ b/crates/ripr/src/output/json/report.rs @@ -318,6 +318,94 @@ pub(crate) fn render_with_config(output: &CheckOutput, config: &RiprConfig) -> S } else { out.push('\n'); } + // Additive advisory field — emitted only when the repository registered + // test harnesses (#3532, `[analysis.test_harnesses]`) and the run + // carried harness facts. Absent otherwise, so repositories without + // registrations keep byte-identical output. Every entry exposes the + // harness kind, adapter generation, provenance, subject identity, and + // selector capability (always unexecuted — passive analysis never runs + // a harness), plus typed limitations, without reconstruction. + if !output.harness_projections.is_empty() { + out.push_str(",\n \"test_harnesses\": [\n"); + for (idx, projection) in output.harness_projections.iter().enumerate() { + out.push_str(" {\n"); + field( + &mut out, + 3, + "registration_id", + &projection.registration_id, + true, + ); + field(&mut out, 3, "harness_kind", &projection.harness_kind, true); + field(&mut out, 3, "adapter", &projection.adapter, true); + field(&mut out, 3, "marker", &projection.marker, true); + field( + &mut out, + 3, + "target", + &projection.target.to_string_lossy().replace('\\', "/"), + true, + ); + field(&mut out, 3, "provenance", &projection.provenance, true); + if projection.subjects.is_empty() { + out.push_str(" \"subjects\": []"); + } else { + out.push_str(" \"subjects\": [\n"); + for (sidx, subject) in projection.subjects.iter().enumerate() { + out.push_str(" {\n"); + field(&mut out, 5, "name", &subject.name, true); + field( + &mut out, + 5, + "file", + &subject.file.to_string_lossy().replace('\\', "/"), + true, + ); + number_field(&mut out, 5, "start_line", subject.start_line, true); + number_field(&mut out, 5, "end_line", subject.end_line, true); + field(&mut out, 5, "selector", subject.selector.as_str(), true); + field(&mut out, 5, "claim", subject.claim.as_str(), false); + out.push_str(" }"); + if sidx + 1 != projection.subjects.len() { + out.push(','); + } + out.push('\n'); + } + out.push_str(" ]"); + } + out.push_str(",\n"); + if projection.limitations.is_empty() { + out.push_str(" \"limitations\": []\n"); + } else { + out.push_str(" \"limitations\": [\n"); + for (lidx, limitation) in projection.limitations.iter().enumerate() { + out.push_str(" {\n"); + field(&mut out, 5, "code", &limitation.code, true); + field( + &mut out, + 5, + "file", + &limitation.file.to_string_lossy().replace('\\', "/"), + true, + ); + number_field(&mut out, 5, "line", limitation.line, true); + field(&mut out, 5, "detail", &limitation.detail, false); + out.push_str(" }"); + if lidx + 1 != projection.limitations.len() { + out.push(','); + } + out.push('\n'); + } + out.push_str(" ]\n"); + } + out.push_str(" }"); + if idx + 1 != output.harness_projections.len() { + out.push(','); + } + out.push('\n'); + } + out.push_str(" ]"); + } out.push_str("}\n"); out } @@ -1409,3 +1497,115 @@ mod provenance_tests { Ok(()) } } + +#[cfg(test)] +mod harness_projection_tests { + use super::*; + use crate::analysis::harness_projection::{ + HarnessLimitationFact, HarnessSelectorCapability, HarnessSubjectClaim, HarnessSubjectFact, + TestHarnessProjection, + }; + use crate::app::Mode; + use crate::domain::Summary; + + type TestResult = Result<(), Box>; + + fn output_with(projections: Vec) -> CheckOutput { + CheckOutput { + harness_projections: projections, + schema_version: "0.2".to_string(), + tool: "ripr".to_string(), + mode: Mode::Draft, + root: std::path::PathBuf::from("repo"), + base: Some("origin/main".to_string()), + analysis_outcome: None, + summary: Summary::default(), + findings: Vec::new(), + preview_language_advisories: Vec::new(), + language_runs: Vec::new(), + no_scope_provided: false, + unanalyzed_working_tree: false, + suppression: None, + partial_scope: None, + } + } + + fn subject(name: &str) -> HarnessSubjectFact { + HarnessSubjectFact { + registration_id: "mimic-suite".to_string(), + harness_kind: "custom_harness".to_string(), + adapter: "libtest_mimic_v1".to_string(), + marker: "libtest_mimic".to_string(), + name: name.to_string(), + file: std::path::PathBuf::from("tests/price_mimic.rs"), + start_line: 9, + end_line: 9, + body: "Trial::test(...)".to_string(), + calls: Vec::new(), + assertions: Vec::new(), + literals: Vec::new(), + selector: HarnessSelectorCapability::NamedUnexecuted, + claim: HarnessSubjectClaim::NamedInvocation, + provenance: "ripr.toml [analysis.test_harnesses]".to_string(), + } + } + + fn parse(rendered: &str) -> Result { + serde_json::from_str(rendered) + } + + #[test] + fn absent_without_registrations() -> TestResult { + let rendered = render_with_config(&output_with(Vec::new()), &RiprConfig::default()); + let value = parse(&rendered)?; + assert!(value.get("test_harnesses").is_none()); + Ok(()) + } + + #[test] + fn present_with_kind_provenance_subject_and_selector() -> TestResult { + let projection = TestHarnessProjection { + registration_id: "mimic-suite".to_string(), + harness_kind: "custom_harness".to_string(), + adapter: "libtest_mimic_v1".to_string(), + marker: "libtest_mimic".to_string(), + target: std::path::PathBuf::from("tests/price_mimic.rs"), + provenance: "ripr.toml [analysis.test_harnesses]".to_string(), + subjects: vec![subject("alpha_parses")], + limitations: vec![HarnessLimitationFact { + registration_id: "mimic-suite".to_string(), + code: "dynamic_trial_name".to_string(), + file: std::path::PathBuf::from("tests/price_mimic.rs"), + line: 17, + detail: "trial name is not a simple string literal".to_string(), + }], + }; + let rendered = render_with_config(&output_with(vec![projection]), &RiprConfig::default()); + let value = parse(&rendered)?; + let harness = value + .get("test_harnesses") + .and_then(|entry| entry.as_array()) + .ok_or("test_harnesses array missing")?; + assert_eq!(harness.len(), 1); + let entry = &harness[0]; + assert_eq!(entry["registration_id"], "mimic-suite"); + assert_eq!(entry["harness_kind"], "custom_harness"); + assert_eq!(entry["adapter"], "libtest_mimic_v1"); + assert_eq!(entry["marker"], "libtest_mimic"); + assert_eq!(entry["target"], "tests/price_mimic.rs"); + assert_eq!(entry["provenance"], "ripr.toml [analysis.test_harnesses]"); + let subjects = entry["subjects"] + .as_array() + .ok_or("subjects array missing")?; + assert_eq!(subjects.len(), 1); + assert_eq!(subjects[0]["name"], "alpha_parses"); + assert_eq!(subjects[0]["selector"], "named_unexecuted"); + assert_eq!(subjects[0]["claim"], "named_invocation"); + let limitations = entry["limitations"] + .as_array() + .ok_or("limitations array missing")?; + assert_eq!(limitations[0]["code"], "dynamic_trial_name"); + assert_eq!(limitations[0]["line"], 17); + Ok(()) + } +} diff --git a/crates/ripr/src/output/next_step.rs b/crates/ripr/src/output/next_step.rs index c75e89f5dd0..2fdde85d4bc 100644 --- a/crates/ripr/src/output/next_step.rs +++ b/crates/ripr/src/output/next_step.rs @@ -184,6 +184,7 @@ mod tests { fn check_output_for(finding: Finding) -> CheckOutput { CheckOutput { + harness_projections: Vec::new(), schema_version: "0.2".to_string(), tool: "ripr".to_string(), mode: Mode::Fast, diff --git a/crates/ripr/src/output/render.rs b/crates/ripr/src/output/render.rs index d69ee4bd7d9..8e8a5656f53 100644 --- a/crates/ripr/src/output/render.rs +++ b/crates/ripr/src/output/render.rs @@ -925,6 +925,7 @@ mod tests { fn check_output_with(findings: Vec) -> CheckOutput { CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, diff --git a/crates/ripr/src/output/sarif.rs b/crates/ripr/src/output/sarif.rs index fc0732984c7..555fe1a380f 100644 --- a/crates/ripr/src/output/sarif.rs +++ b/crates/ripr/src/output/sarif.rs @@ -1681,6 +1681,7 @@ weakly_gripped = "note" fn sample_output() -> CheckOutput { CheckOutput { + harness_projections: Vec::new(), schema_version: "0.1".to_string(), tool: "ripr".to_string(), mode: Mode::Draft, diff --git a/docs/OUTPUT_SCHEMA.md b/docs/OUTPUT_SCHEMA.md index e10c42627f5..e56b471b64b 100644 --- a/docs/OUTPUT_SCHEMA.md +++ b/docs/OUTPUT_SCHEMA.md @@ -1325,6 +1325,69 @@ analyzed under advisory preview support that may be incomplete (`enabled == true`). In neither case is an empty result a Rust-grade clean result. +### `test_harnesses` (top-level additive advisory, #3532) + +Added in schema `0.2` as an additive optional top-level array. Emitted only when +the repository registered test harnesses (`[analysis.test_harnesses]` in +`ripr.toml`) and the run's analysis carried harness facts. Absent for +repositories without registrations, so their output is byte-identical to the +pre-#3532 shape. Does not bump `schema_version`. + +Example — one registered `harness = false` custom target with one exact trial +subject and one dynamic-name limitation: + +```json +"test_harnesses": [ + { + "registration_id": "mimic-suite", + "harness_kind": "custom_harness", + "adapter": "libtest_mimic_v1", + "marker": "libtest_mimic", + "target": "tests/price_mimic.rs", + "provenance": "ripr.toml [analysis.test_harnesses]", + "subjects": [ + { + "name": "alpha_parses", + "file": "tests/price_mimic.rs", + "start_line": 9, + "end_line": 9, + "selector": "named_unexecuted", + "claim": "named_invocation" + } + ], + "limitations": [ + { + "code": "dynamic_trial_name", + "file": "tests/price_mimic.rs", + "line": 17, + "detail": "trial name is not a simple string literal; generated names remain unresolved" + } + ] + } +] +``` + +- `registration_id` — the stable identifier from the registration +- `harness_kind` — `custom_harness` or `registered_attribute` +- `adapter` — adapter generation, e.g. `libtest_mimic_v1`, `exact_attribute_v1` +- `marker` — the exact source marker the adapter matched (crate or attribute path) +- `target` — the exact registered target file (workspace-relative, forward-slashed) +- `provenance` — where the authority came from (registration channel) +- `subjects[].name` — stable subject identity (trial name or test fn name) +- `subjects[].selector` — `named_unexecuted` when a selector route is known; + a known route is never a selector that ran — passive analysis never starts + Cargo or a harness +- `subjects[].claim` — `named_invocation` (the invocation is one source-level + subject; generated cases are not enumerated) or `named_function` (the + function is one executable test) +- `limitations[]` — typed shapes the registration saw but could not classify + (`dynamic_trial_name`, `dynamic_trial_registration`, `ambiguous_import`, + `unanchored_trial_path`, `unresolved_marker_import`, `duplicate_subject`, + `parse_unavailable`) + +An absent `test_harnesses` array means the repository has no harness +registrations; it is never a claim that custom harnesses do not exist. + ### `scope_disclosures` (top-level additive advisory, RIPR-SPEC-0083) Added as an additive optional top-level array. Emitted only when `ripr check` diff --git a/docs/specs/RIPR-SPEC-0153-rust-source-role.md b/docs/specs/RIPR-SPEC-0153-rust-source-role.md index 505d88c1f95..44de5550695 100644 --- a/docs/specs/RIPR-SPEC-0153-rust-source-role.md +++ b/docs/specs/RIPR-SPEC-0153-rust-source-role.md @@ -136,8 +136,12 @@ classification, and absolute-path rejection. - No cache-generation bump: the workspace cache key hashes the `ripr.toml` text, and the fact/classification schemas are unchanged by this slice (`FunctionFact.is_test` semantics untouched). -- No generated-file or custom-harness classification (`UnknownRole` - reserved, test-only until a real producer exists). +- Custom-harness classification now exists only through the explicit + repository-governed registry (`[analysis.test_harnesses]`, #3532): + exact registrations authorize evidence role, adapter-established + subjects, and typed limitations; nothing is inferred from filenames, + imports, macro suffixes, or function names. Generated-file + classification without a real producer remains deferred. ## Implementation Mapping diff --git a/policy/no-panic-allowlist.toml b/policy/no-panic-allowlist.toml index 0fac391c7dc..d15796836c0 100644 --- a/policy/no-panic-allowlist.toml +++ b/policy/no-panic-allowlist.toml @@ -371,7 +371,7 @@ expires = "2027-06-30" kind = "method_call" container = "analyzes_simple_predicate_gap" callee = "unwrap" -receiver_fingerprint = "run_analysis(&AnalysisOptions { root: root.clone(), base: None, diff_file: Some(root.join(\"diff.patch\")), mode: AnalysisMode::Draft, include_unchanged_tests: true, resolve_tsconfig_paths: false, perl_facts_path: None, git_timeout: None, git_candidate: None, resolved_subject_identity: None, production_like_targets: Default::default(), })" +receiver_fingerprint = "run_analysis(&AnalysisOptions { root: root.clone(), base: None, diff_file: Some(root.join(\"diff.patch\")), mode: AnalysisMode::Draft, include_unchanged_tests: true, resolve_tsconfig_paths: false, perl_facts_path: None, git_timeout: None, git_candidate: None, resolved_subject_identity: None, production_like_targets: Default::default(), test_harnesses: Vec::new(), })" [allow.last_seen] line = 327 @@ -390,7 +390,7 @@ expires = "2027-06-30" kind = "method_call" container = "analyzes_simple_predicate_gap" callee = "unwrap" -receiver_fingerprint = "run_analysis(&AnalysisOptions { root: root.clone(), base: None, diff_file: Some(root.join(\"diff.patch\")), mode: AnalysisMode::Instant, include_unchanged_tests: true, resolve_tsconfig_paths: false, perl_facts_path: None, git_timeout: None, git_candidate: None, resolved_subject_identity: None, production_like_targets: Default::default(), })" +receiver_fingerprint = "run_analysis(&AnalysisOptions { root: root.clone(), base: None, diff_file: Some(root.join(\"diff.patch\")), mode: AnalysisMode::Instant, include_unchanged_tests: true, resolve_tsconfig_paths: false, perl_facts_path: None, git_timeout: None, git_candidate: None, resolved_subject_identity: None, production_like_targets: Default::default(), test_harnesses: Vec::new(), })" [allow.last_seen] line = 345 diff --git a/policy/public_api.txt b/policy/public_api.txt index f647408f6b9..259b2f02e96 100644 --- a/policy/public_api.txt +++ b/policy/public_api.txt @@ -194,6 +194,9 @@ pub use ripr::config::ConfigSeverity pub use ripr::config::LspDiagnosticProfile pub use ripr::config::OraclePolicy pub use ripr::config::PerlConfig +pub use ripr::config::TestHarnessAdapter +pub use ripr::config::TestHarnessKind +pub use ripr::config::TestHarnessRegistration pub use ripr::config::RiprConfig pub use ripr::config::SeverityConfig pub use ripr::config::TypescriptConfig From b1cfa283117309e772bcbdba685b4d394ce33a5d Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Sun, 30 Aug 2026 20:55:57 -0400 Subject: [PATCH 02/33] fix(analysis): preserve harness cache exports after rebase --- crates/ripr/src/analysis/facts/mod.rs | 8 +++++--- crates/ripr/src/analysis/rust_index.rs | 1 - 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/ripr/src/analysis/facts/mod.rs b/crates/ripr/src/analysis/facts/mod.rs index d1545ae272b..3f2b45d6371 100644 --- a/crates/ripr/src/analysis/facts/mod.rs +++ b/crates/ripr/src/analysis/facts/mod.rs @@ -7,6 +7,9 @@ mod parameterized_tests; mod role_composition; mod test_styles; +#[cfg(test)] +pub(crate) use build::build_index_from_loaded_files_with_cache; + use std::path::{Path, PathBuf}; use crate::config::TestHarnessRegistration; @@ -57,9 +60,8 @@ pub use model::{ ModuleDeclarationFact, ModulePathTarget, OracleFact, ProbeShapeFact, ResolvedIncludeParent, ReturnFact, RustIncludeLimitation, RustIndex, SourceRoleProvenance, SourceRoleProvenanceEdge, SourceRoleProvenanceEdgeKind, TestFact, TestSummary, - CallFact, FileFacts, FunctionFact, FunctionSourceRole, FunctionSummary, HarnessLimitationFact, - HarnessSelectorCapability, HarnessSubjectClaim, HarnessSubjectFact, LiteralFact, OracleFact, - ProbeShapeFact, ReturnFact, RustIncludeLimitation, RustIndex, TestFact, TestSummary, + HarnessLimitationFact, + HarnessSelectorCapability, HarnessSubjectClaim, HarnessSubjectFact, }; #[cfg(test)] pub(crate) use model::{WorkspaceFileAuthority, WorkspaceRootAuthority}; diff --git a/crates/ripr/src/analysis/rust_index.rs b/crates/ripr/src/analysis/rust_index.rs index 84d87f7509e..f7456cb7c2d 100644 --- a/crates/ripr/src/analysis/rust_index.rs +++ b/crates/ripr/src/analysis/rust_index.rs @@ -18,7 +18,6 @@ pub(crate) use super::extract::{ unwrap_err_bound_variables, }; use super::facts::ModulePathTarget; -pub(crate) use super::facts::build_index_from_loaded_files_with_cache; pub(crate) use super::facts::build_index_from_loaded_files_with_cache_and_test_harnesses; #[cfg(test)] pub use super::facts::{CallFact, LiteralFact, ReturnFact}; From e060ed9d008065f786fae9a1931a8c950b6ee480 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 01:50:27 -0400 Subject: [PATCH 03/33] test(fixtures): refresh harness identity receipt pins --- .../unchanged-after-attempt/after.repo-exposure.json | 6 +++--- .../unchanged-after-attempt/agent-receipt.json | 6 +++--- .../unchanged-after-attempt/agent-verify.json | 4 ++-- .../unchanged-after-attempt/before.repo-exposure.json | 6 +++--- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/after.repo-exposure.json b/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/after.repo-exposure.json index 6c0363b12fe..69b93681b20 100644 --- a/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/after.repo-exposure.json +++ b/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/after.repo-exposure.json @@ -4,13 +4,13 @@ "base_revision": null, "command": "ripr check --format repo-exposure-json", "format": "repo-exposure-json", - "input_identity": "input:v3:fnv1a64:279f227b14c46e0b", + "input_identity": "input:v3:fnv1a64:6019807aeb8b9ee6", "mode": "draft", "profile": "draft", "worktree": "dirty" }, "canonicalization": "raw_json_placeholder_v1", - "content_sha256": "sha256:5c8faf85b702ef2f1556bcbca7c25ebe42c0f62ad1fe1213a0198d26ed1987a9", + "content_sha256": "sha256:b35c84811002ddb61802a12824b601880f2a140b2cb41c2c6c1bf3c287d6232d", "kind": "repo_exposure", "producer": { "tool": "ripr", @@ -21,7 +21,7 @@ "root": "." }, "schema_version": "1", - "snapshot_identity": "snapshot:input:v3:fnv1a64:279f227b14c46e0b;revision:8a00693e680c8ad5172d5191bbb08484cbd5e300" + "snapshot_identity": "snapshot:input:v3:fnv1a64:6019807aeb8b9ee6;revision:8a00693e680c8ad5172d5191bbb08484cbd5e300" }, "metrics": { "activation_unknown": 0, diff --git a/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/agent-receipt.json b/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/agent-receipt.json index 77feca0f5d8..ff75acbae06 100644 --- a/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/agent-receipt.json +++ b/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/agent-receipt.json @@ -10,12 +10,12 @@ "provenance": { "after_artifact": { "path": "fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/after.repo-exposure.json", - "sha256": "sha256:74653bca0203fc65fc314dbd6c73960a4bcd4e9040c810f007437f8315c29afb" + "sha256": "sha256:0ad63daaaeddabf035a662c25ee0a68360e8458ebdc05f1bb83cbbf45555e2d6" }, "after_class": "weakly_gripped", "before_artifact": { "path": "fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/before.repo-exposure.json", - "sha256": "sha256:74653bca0203fc65fc314dbd6c73960a4bcd4e9040c810f007437f8315c29afb" + "sha256": "sha256:0ad63daaaeddabf035a662c25ee0a68360e8458ebdc05f1bb83cbbf45555e2d6" }, "before_class": "weakly_gripped", "command_template_version": "0.1", @@ -32,7 +32,7 @@ "seam_id": "67fc764ba37d77bd", "verify_artifact": { "path": "fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/agent-verify.json", - "sha256": "sha256:b763473050e70ced5991f016e78323856a0ea221c5bbe84b339d22eb042480af" + "sha256": "sha256:5adc9afcc2e8b0ca9e7519f1ea2c3b2da393bacd6316a37df794f78a81153c78" }, "workflow_artifact": null }, diff --git a/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/agent-verify.json b/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/agent-verify.json index 988ec09785a..357cfa85bb6 100644 --- a/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/agent-verify.json +++ b/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/agent-verify.json @@ -3,9 +3,9 @@ "changed_seams": [], "inputs": { "after": "fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/after.repo-exposure.json", - "after_content_sha256": "sha256:5c8faf85b702ef2f1556bcbca7c25ebe42c0f62ad1fe1213a0198d26ed1987a9", + "after_content_sha256": "sha256:b35c84811002ddb61802a12824b601880f2a140b2cb41c2c6c1bf3c287d6232d", "before": "fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/before.repo-exposure.json", - "before_content_sha256": "sha256:5c8faf85b702ef2f1556bcbca7c25ebe42c0f62ad1fe1213a0198d26ed1987a9" + "before_content_sha256": "sha256:b35c84811002ddb61802a12824b601880f2a140b2cb41c2c6c1bf3c287d6232d" }, "new_gaps": [], "resolved_gaps": [], diff --git a/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/before.repo-exposure.json b/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/before.repo-exposure.json index 6c0363b12fe..69b93681b20 100644 --- a/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/before.repo-exposure.json +++ b/fixtures/boundary_gap/expected/first-useful-action/unchanged-after-attempt/before.repo-exposure.json @@ -4,13 +4,13 @@ "base_revision": null, "command": "ripr check --format repo-exposure-json", "format": "repo-exposure-json", - "input_identity": "input:v3:fnv1a64:279f227b14c46e0b", + "input_identity": "input:v3:fnv1a64:6019807aeb8b9ee6", "mode": "draft", "profile": "draft", "worktree": "dirty" }, "canonicalization": "raw_json_placeholder_v1", - "content_sha256": "sha256:5c8faf85b702ef2f1556bcbca7c25ebe42c0f62ad1fe1213a0198d26ed1987a9", + "content_sha256": "sha256:b35c84811002ddb61802a12824b601880f2a140b2cb41c2c6c1bf3c287d6232d", "kind": "repo_exposure", "producer": { "tool": "ripr", @@ -21,7 +21,7 @@ "root": "." }, "schema_version": "1", - "snapshot_identity": "snapshot:input:v3:fnv1a64:279f227b14c46e0b;revision:8a00693e680c8ad5172d5191bbb08484cbd5e300" + "snapshot_identity": "snapshot:input:v3:fnv1a64:6019807aeb8b9ee6;revision:8a00693e680c8ad5172d5191bbb08484cbd5e300" }, "metrics": { "activation_unknown": 0, From f5136b569dd5a867b8fdad02fb45836e07877968 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 02:06:48 -0400 Subject: [PATCH 04/33] fix(analysis): preserve composed roles in cached test facade --- crates/ripr/src/analysis/facts/mod.rs | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/ripr/src/analysis/facts/mod.rs b/crates/ripr/src/analysis/facts/mod.rs index 3f2b45d6371..9031799010d 100644 --- a/crates/ripr/src/analysis/facts/mod.rs +++ b/crates/ripr/src/analysis/facts/mod.rs @@ -7,9 +7,6 @@ mod parameterized_tests; mod role_composition; mod test_styles; -#[cfg(test)] -pub(crate) use build::build_index_from_loaded_files_with_cache; - use std::path::{Path, PathBuf}; use crate::config::TestHarnessRegistration; @@ -53,15 +50,26 @@ pub(crate) fn build_index_from_loaded_files_with_cache_and_test_harnesses( Ok(cached) } +/// Test-only compatibility facade for the cache path without harness +/// registrations. Keep the same post-parse normalization and contextual +/// role composition as the production index builder; callers that need the +/// registry use the explicit sibling above. +#[cfg(test)] +pub(crate) fn build_index_from_loaded_files_with_cache( + root: &Path, + files: &[(PathBuf, Vec)], +) -> Result { + build_index_from_loaded_files_with_cache_and_test_harnesses(root, files, &[]) +} + // Keep compilation-unit rebasing available at the facts facade for index consumers. pub(crate) use includes::compilation_unit_path_from_parents; pub use model::{ - CallFact, FileFacts, FunctionFact, FunctionSourceRole, FunctionSummary, LiteralFact, + CallFact, FileFacts, FunctionFact, FunctionSourceRole, FunctionSummary, HarnessLimitationFact, + HarnessSelectorCapability, HarnessSubjectClaim, HarnessSubjectFact, LiteralFact, ModuleDeclarationFact, ModulePathTarget, OracleFact, ProbeShapeFact, ResolvedIncludeParent, ReturnFact, RustIncludeLimitation, RustIndex, SourceRoleProvenance, SourceRoleProvenanceEdge, SourceRoleProvenanceEdgeKind, TestFact, TestSummary, - HarnessLimitationFact, - HarnessSelectorCapability, HarnessSubjectClaim, HarnessSubjectFact, }; #[cfg(test)] pub(crate) use model::{WorkspaceFileAuthority, WorkspaceRootAuthority}; From 195097cf2cbf00ccc5d9e6f40d7fc34ecb85d0d1 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 02:40:56 -0400 Subject: [PATCH 05/33] fix(analysis): harden registered harness evidence --- .ripr/traceability.toml | 5 + .../src/analysis/facts/harness_registry.rs | 162 ++++++++++++++++-- .../analysis/facts/harness_registry/tests.rs | 93 +++++++++- crates/ripr/src/analysis/facts/mod.rs | 36 +++- crates/ripr/src/analysis/language/rust.rs | 6 +- crates/ripr/src/analysis/rust_index.rs | 9 +- crates/ripr/src/analysis/seam_inventory.rs | 3 +- schemas/ripr/check.schema.json | 60 ++++++- 8 files changed, 348 insertions(+), 26 deletions(-) diff --git a/.ripr/traceability.toml b/.ripr/traceability.toml index 4494459486d..bad471569c1 100644 --- a/.ripr/traceability.toml +++ b/.ripr/traceability.toml @@ -8257,6 +8257,8 @@ tests = [ "crates/ripr/src/analysis/language/rust.rs::tests::diff_analysis_confirms_declared_test_targets_but_not_unconfirmed_names", "crates/ripr/src/analysis/language/rust.rs::tests::diff_analysis_opt_in_restores_production_like_analysis", "crates/ripr/src/config/tests.rs::parse_config_reads_production_like_targets", + "crates/ripr/src/analysis/facts/harness_registry/tests.rs", + "crates/ripr/src/output/json/report.rs::harness_projection_tests", ] fixtures = [] code = [ @@ -8266,6 +8268,9 @@ code = [ "crates/ripr/src/analysis/seam_inventory.rs", "crates/ripr/src/config.rs", "crates/ripr/src/config/model.rs", + "crates/ripr/src/analysis/facts/harness_registry.rs", + "crates/ripr/src/analysis/harness_projection.rs", + "crates/ripr/src/output/json/report.rs", ] outputs = [] metrics = [ diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index bef411adce5..9298dd06714 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -33,6 +33,7 @@ use super::test_styles::normalized_test_attribute_path as normalized_attribute_p use super::{ HarnessLimitationFact, HarnessSelectorCapability, HarnessSubjectClaim, HarnessSubjectFact, }; +use crate::analysis::extract::extract_assertions; use crate::analysis::rust_index::{ OracleFact, classify_assertion, extract_call_facts, extract_identifier_tokens, extract_literal_facts, @@ -52,6 +53,7 @@ use std::path::Path; pub(super) fn apply_registrations( index: &mut RustIndex, registrations: &[TestHarnessRegistration], + production_like_targets: &std::collections::BTreeSet, ) { if registrations.is_empty() { return; @@ -68,6 +70,9 @@ pub(super) fn apply_registrations( let source = facts.source.clone(); match (registration.kind, registration.adapter) { (TestHarnessKind::CustomHarnessTarget, TestHarnessAdapter::LibtestMimicV1) => { + if production_like_targets.contains(®istration.target) { + continue; + } apply_libtest_mimic_target( index, registration, @@ -77,6 +82,9 @@ pub(super) fn apply_registrations( ) } (TestHarnessKind::RegisteredAttribute, TestHarnessAdapter::ExactAttributeV1) => { + if production_like_targets.contains(®istration.target) { + continue; + } apply_registered_attribute( index, registration, @@ -230,6 +238,13 @@ fn apply_libtest_mimic_target( "trial name `{name}` is registered more than once; conflicting subject claims fail closed" ), }); + subjects.retain(|subject| { + !(subject.registration_id == registration.registration_id && subject.name == name) + }); + remove_file_test(index, &target, &name); + index + .tests + .retain(|test| !(test.file == target && test.name == name)); continue; } // The subject span runs from the trial path to the balanced @@ -237,14 +252,40 @@ fn apply_libtest_mimic_target( let Some(end_offset) = balanced_call_end(&tokens, matched.open_paren_index) else { continue; }; + let callback = match trial_callback_name(&tokens, matched.name_token_index) { + Some(callback_name) => match unique_callback_function(index, &target, &callback_name) { + Some(function) => Some(function), + None => { + limitations.push(HarnessLimitationFact { + registration_id: registration.registration_id.clone(), + code: "unresolved_trial_callback".to_string(), + file: target.clone(), + line, + detail: format!( + "trial callback `{callback_name}` is not a unique function item in the registered target; subject evidence remains unresolved" + ), + }); + continue; + } + }, + None => None, + }; let start: TextSize = tokens[position].text_range().start(); let start_line = line_index.line(start); let end_line = line_index.line_for_range_end(TextSize::new(end_offset)); let body = slice_text(source, start, TextSize::new(end_offset)); - let calls = extract_call_facts(&body, start_line); - let literals = extract_literal_facts(&body, start_line); - let assertions = - parser_oracles_for_node_tokens(&tokens, matched.name_token_index, start_line); + let (calls, literals, assertions) = match callback.as_ref() { + Some(function) => ( + function.calls.clone(), + function.literals.clone(), + extract_assertions(&function.body, function.start_line), + ), + None => ( + extract_call_facts(&body, start_line), + extract_literal_facts(&body, start_line), + parser_oracles_for_node_tokens(&tokens, matched.name_token_index, &line_index), + ), + }; let subject = HarnessSubjectFact { registration_id: registration.registration_id.clone(), harness_kind: registration.kind.as_str().to_string(), @@ -316,6 +357,9 @@ fn match_trial_path( } for qualified in [false, true] { + if qualified && !qualified_path_starts_at_boundary(tokens, position) { + continue; + } let mut segments: Vec<&str> = if qualified { marker.split("::").collect() } else { @@ -349,12 +393,72 @@ fn match_trial_path( None } +fn qualified_path_starts_at_boundary( + tokens: &[ra_ap_syntax::SyntaxToken], + position: usize, +) -> bool { + let Some(previous) = position.checked_sub(1).and_then(|index| tokens.get(index)) else { + return true; + }; + let prefix_end = if previous.kind() == ra_ap_syntax::SyntaxKind::COLON2 { + position.saturating_sub(2) + } else if previous.kind() == ra_ap_syntax::SyntaxKind::COLON + && tokens + .get(position.saturating_sub(2)) + .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::COLON) + { + position.saturating_sub(3) + } else { + return true; + }; + // Permit an explicitly rooted `::marker::Trial` path, but reject + // `other::marker::Trial`: the configured marker must own the complete + // qualified path rather than merely appear as a suffix. + tokens + .get(prefix_end) + .is_none_or(|token| token.kind() != ra_ap_syntax::SyntaxKind::IDENT) +} + struct TrialPathMatch { qualified: bool, name_token_index: usize, open_paren_index: usize, } +fn trial_callback_name( + tokens: &[ra_ap_syntax::SyntaxToken], + name_token_index: usize, +) -> Option { + let mut index = name_token_index + 1; + while let Some(token) = tokens.get(index) { + if token.kind() == ra_ap_syntax::SyntaxKind::COMMA { + return tokens + .get(index + 1) + .filter(|callback| callback.kind() == ra_ap_syntax::SyntaxKind::IDENT) + .map(|callback| callback.text().to_string()); + } + if token.kind() == ra_ap_syntax::SyntaxKind::R_PAREN { + return None; + } + index += 1; + } + None +} + +fn unique_callback_function(index: &RustIndex, target: &Path, name: &str) -> Option { + let mut matches = index + .files + .get(target)? + .functions + .iter() + .filter(|function| { + function.name == name && function.source_role == FunctionSourceRole::HarnessHelper + }) + .cloned(); + let function = matches.next()?; + matches.next().is_none().then_some(function) +} + /// Offset just past the `)` balancing the `(` at `open_paren_index`, /// bounded to the token stream. `None` (unbalanced) means the span is not /// provable and the match is skipped. @@ -383,12 +487,11 @@ fn balanced_call_end(tokens: &[ra_ap_syntax::SyntaxToken], open_paren_index: usi fn parser_oracles_for_node_tokens( tokens: &[ra_ap_syntax::SyntaxToken], name_token_index: usize, - start_line: usize, + line_index: &LineIndex, ) -> Vec { let mut assertions = Vec::new(); let mut depth: usize = 1; let mut index = name_token_index + 1; - let line_offset = start_line.saturating_sub(1); while index < tokens.len() && depth > 0 { let token = &tokens[index]; match token.kind() { @@ -396,17 +499,37 @@ fn parser_oracles_for_node_tokens( ra_ap_syntax::SyntaxKind::R_PAREN => depth = depth.saturating_sub(1), ra_ap_syntax::SyntaxKind::IDENT => { let name = token.text(); - if !is_assertion_macro_name(name) { + let next = tokens.get(index + 1); + let is_macro_invocation = is_assertion_macro_name(name) + && next.is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::BANG) + && tokens.get(index + 2).is_some_and(|token| { + matches!( + token.kind(), + ra_ap_syntax::SyntaxKind::L_PAREN + | ra_ap_syntax::SyntaxKind::L_CURLY + | ra_ap_syntax::SyntaxKind::L_BRACK + ) + }); + let is_fallible_call = matches!(name, "unwrap" | "expect") + && index >= 1 + && tokens[index - 1].kind() == ra_ap_syntax::SyntaxKind::DOT + && next.is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::L_PAREN); + if !is_macro_invocation && !is_fallible_call { index += 1; continue; } // assert!(..) / assert_eq!(..) — the bang and token tree // follow; the assertion text is the macro invocation. - let mut text = name.to_string(); + let mut text = if is_fallible_call { + format!(".{name}(") + } else { + name.to_string() + }; let mut cursor = index + 1; - if tokens - .get(cursor) - .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::BANG) + if is_macro_invocation + && tokens + .get(cursor) + .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::BANG) { text.push('!'); cursor += 1; @@ -428,10 +551,14 @@ fn parser_oracles_for_node_tokens( } text.push(')'); } + } else if is_fallible_call { + // The method name itself is sufficient for the shared + // classifier to establish a smoke oracle. Keep the + // argument body out of this small structural witness. } let classification = classify_assertion(&text); assertions.push(OracleFact { - line: line_offset + 1, + line: line_index.line(token.text_range().start()), kind: classification.kind, strength: classification.strength, observed_tokens: extract_identifier_tokens(&text), @@ -617,6 +744,12 @@ fn push_file_test(index: &mut RustIndex, target: &Path, test: TestFact) { } } +fn remove_file_test(index: &mut RustIndex, target: &Path, name: &str) { + if let Some(facts) = index.files.get_mut(target) { + facts.tests.retain(|test| test.name != name); + } +} + /// Demote every function in a registered `harness = false` target to the /// evidence-only helper role and drop the target's executable /// `TestFact`s. With `harness = false` the libtest harness never @@ -782,9 +915,8 @@ enum TrialBindingResolution { fn resolve_trial_binding(bindings: &BTreeSet, marker: &str) -> TrialBindingResolution { let anchored_full = format!("{marker}::Trial"); - let matches_marker = |binding: &String| { - binding == &anchored_full || binding.ends_with(&format!("::{anchored_full}")) - }; + let matches_marker = + |binding: &String| binding == &anchored_full || binding == &format!("::{anchored_full}"); let anchored = bindings.iter().any(matches_marker); let conflicting = bindings .iter() diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs index 26a3357dde4..14525bbdf4a 100644 --- a/crates/ripr/src/analysis/facts/harness_registry/tests.rs +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -6,6 +6,7 @@ use super::*; use crate::analysis::facts::build_index_with_test_harnesses; +use std::collections::BTreeSet; use std::fs; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; @@ -311,7 +312,7 @@ fn trials() -> Vec { } #[test] -fn duplicate_trial_names_name_the_conflict_and_stay_one_subject() +fn duplicate_trial_names_name_the_conflict_and_remove_both_subjects() -> Result<(), Box> { let root = temp_dir("duplicate-trials")?; write_workspace( @@ -333,7 +334,7 @@ fn trials() -> Vec { let files = [PathBuf::from("tests/duplicates.rs")]; let registrations = [custom_target_registration("tests/duplicates.rs")]; let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; - assert_eq!(index.harness_subjects.len(), 1); + assert_eq!(index.harness_subjects.len(), 0); assert!( index .harness_limitations @@ -343,6 +344,42 @@ fn trials() -> Vec { "{:?}", index.harness_limitations ); + assert!( + index.tests.iter().all(|test| test.name != "same_name"), + "a duplicate subject must not leave an executable test fact" + ); + Ok(()) +} + +#[test] +fn production_like_target_precedence_survives_harness_registration() +-> Result<(), Box> { + let root = temp_dir("production-like-precedence")?; + write_workspace( + &root, + &[( + "tests/mimic.rs", + "use libtest_mimic::Trial;\nfn helper() -> i32 { 1 }\nTrial::test(\"one\", || Ok(()));\n", + )], + )?; + let target = PathBuf::from("tests/mimic.rs"); + let registrations = [custom_target_registration("tests/mimic.rs")]; + let mut production_like = BTreeSet::new(); + production_like.insert(target.clone()); + let index = + crate::analysis::facts::build_index_with_test_harnesses_and_production_like_targets( + &root.0, + &[target], + ®istrations, + &production_like, + )?; + let helper = index + .functions + .iter() + .find(|function| function.name == "helper") + .ok_or("missing helper")?; + assert_eq!(helper.source_role, FunctionSourceRole::Production); + assert!(index.harness_subjects.is_empty()); Ok(()) } @@ -353,7 +390,7 @@ fn fully_qualified_trial_calls_match_the_marker_path() -> Result<(), Box Vec {\n vec![libtest_mimic::Trial::test(\"qualified_case\", || Ok(()))]\n}\n", + "fn trials() -> Vec {\n vec![libtest_mimic::Trial::test(\"qualified_case\", || Ok(())), other::libtest_mimic::Trial::test(\"suffix_lookalike\", || Ok(()))]\n}\n", )], )?; let files = [PathBuf::from("tests/qualified.rs")]; @@ -370,6 +407,56 @@ fn fully_qualified_trial_calls_match_the_marker_path() -> Result<(), Box Result<(), Box> { + let root = temp_dir("trial-oracles")?; + write_workspace( + &root, + &[( + "tests/oracles.rs", + "use libtest_mimic::Trial;\nfn trials() -> Vec {\n vec![Trial::test(\"oracle_case\", || {\n let snapshot_value = 1;\n let result = Some(snapshot_value).unwrap();\n assert_eq!(result, 1);\n result.expect(\"present\");\n Ok(())\n })]\n}\n", + )], + )?; + let index = build_index_with_test_harnesses( + &root.0, + &[PathBuf::from("tests/oracles.rs")], + &[custom_target_registration("tests/oracles.rs")], + )?; + let subject = index + .harness_subjects + .iter() + .find(|subject| subject.name == "oracle_case") + .ok_or("missing oracle subject")?; + assert_eq!(subject.assertions.len(), 3); + assert!( + subject + .assertions + .iter() + .any(|oracle| oracle.text == "unwrap" || oracle.text == ".unwrap(") + ); + assert!( + subject + .assertions + .iter() + .any(|oracle| oracle.text == ".expect(") + ); + assert!( + subject + .assertions + .iter() + .any(|oracle| oracle.text.starts_with("assert_eq!")) + ); + assert!( + subject + .assertions + .iter() + .map(|oracle| oracle.line) + .any(|line| line > subject.start_line) + ); + Ok(()) +} + #[test] fn registered_attribute_promotes_exact_matches_only() -> Result<(), Box> { let root = temp_dir("registered-attribute")?; diff --git a/crates/ripr/src/analysis/facts/mod.rs b/crates/ripr/src/analysis/facts/mod.rs index 9031799010d..a4ce1bfbeee 100644 --- a/crates/ripr/src/analysis/facts/mod.rs +++ b/crates/ripr/src/analysis/facts/mod.rs @@ -23,6 +23,20 @@ pub fn build_index_with_test_harnesses( root: &Path, files: &[PathBuf], registrations: &[TestHarnessRegistration], +) -> Result { + build_index_with_test_harnesses_and_production_like_targets( + root, + files, + registrations, + &std::collections::BTreeSet::new(), + ) +} + +pub fn build_index_with_test_harnesses_and_production_like_targets( + root: &Path, + files: &[PathBuf], + registrations: &[TestHarnessRegistration], + production_like_targets: &std::collections::BTreeSet, ) -> Result { let mut index = build::build_index(root, files)?; parameterized_tests::promote_explicit_test_case_functions(&mut index); @@ -33,7 +47,7 @@ pub fn build_index_with_test_harnesses( // evidence-only `CfgTestModule`, never the reverse. The workspace root // anchors crate-root identity for default module resolution. role_composition::compose_index_source_roles(&mut index, root); - harness_registry::apply_registrations(&mut index, registrations); + harness_registry::apply_registrations(&mut index, registrations, production_like_targets); Ok(index) } @@ -41,12 +55,30 @@ pub(crate) fn build_index_from_loaded_files_with_cache_and_test_harnesses( root: &Path, files: &[(PathBuf, Vec)], registrations: &[TestHarnessRegistration], +) -> Result { + build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( + root, + files, + registrations, + &std::collections::BTreeSet::new(), + ) +} + +pub(crate) fn build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( + root: &Path, + files: &[(PathBuf, Vec)], + registrations: &[TestHarnessRegistration], + production_like_targets: &std::collections::BTreeSet, ) -> Result { let mut cached = build::build_index_from_loaded_files_with_cache(root, files)?; parameterized_tests::promote_explicit_test_case_functions(&mut cached.index); test_styles::normalize_index_test_styles(&mut cached.index); role_composition::compose_index_source_roles(&mut cached.index, root); - harness_registry::apply_registrations(&mut cached.index, registrations); + harness_registry::apply_registrations( + &mut cached.index, + registrations, + production_like_targets, + ); Ok(cached) } diff --git a/crates/ripr/src/analysis/language/rust.rs b/crates/ripr/src/analysis/language/rust.rs index e960906d448..0675242aff8 100644 --- a/crates/ripr/src/analysis/language/rust.rs +++ b/crates/ripr/src/analysis/language/rust.rs @@ -1608,10 +1608,11 @@ impl RustAdapter { Ok((file.clone(), bytes)) }) .collect::, String>>()?; - let cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &options.root, &loaded_files, &options.test_harnesses, + &options.production_like_targets, )?; let mut index = cached.index; if let Some(disclosure) = rust_index::include_resolution_disclosure(&index) { @@ -1849,10 +1850,11 @@ impl RustAdapter { Ok((file.clone(), bytes)) }) .collect::, String>>()?; - let cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &options.root, &loaded_rust_files, &options.test_harnesses, + &options.production_like_targets, )?; let mut index = cached.index; if let Some(disclosure) = rust_index::lexical_fallback_disclosure(&index) { diff --git a/crates/ripr/src/analysis/rust_index.rs b/crates/ripr/src/analysis/rust_index.rs index f7456cb7c2d..8b75992d8de 100644 --- a/crates/ripr/src/analysis/rust_index.rs +++ b/crates/ripr/src/analysis/rust_index.rs @@ -18,12 +18,17 @@ pub(crate) use super::extract::{ unwrap_err_bound_variables, }; use super::facts::ModulePathTarget; -pub(crate) use super::facts::build_index_from_loaded_files_with_cache_and_test_harnesses; +#[cfg(test)] +pub use super::facts::build_index_with_test_harnesses; #[cfg(test)] pub use super::facts::{CallFact, LiteralFact, ReturnFact}; pub use super::facts::{ FileFacts, FunctionFact, FunctionSummary, OracleFact, ProbeShapeFact, RustIndex, TestFact, - TestSummary, build_index, build_index_with_test_harnesses, + TestSummary, build_index, build_index_with_test_harnesses_and_production_like_targets, +}; +pub(crate) use super::facts::{ + build_index_from_loaded_files_with_cache_and_test_harnesses, + build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets, }; #[cfg(test)] use super::syntax::LexicalRustSyntaxAdapter; diff --git a/crates/ripr/src/analysis/seam_inventory.rs b/crates/ripr/src/analysis/seam_inventory.rs index 7d92718b3e3..e4c069f0759 100644 --- a/crates/ripr/src/analysis/seam_inventory.rs +++ b/crates/ripr/src/analysis/seam_inventory.rs @@ -86,10 +86,11 @@ pub(crate) fn inventory_seams_at_with_config( // Index the full set so `find_owner_function` can resolve owners // even when the seam appears in a file the production filter // includes but tests reference. - let index = rust_index::build_index_with_test_harnesses( + let index = rust_index::build_index_with_test_harnesses_and_production_like_targets( root, &rust_files, harness_registrations(config), + config.analysis().production_like_targets(), )?; Ok(inventory_seams_from_index(&production_files, &index)) } diff --git a/schemas/ripr/check.schema.json b/schemas/ripr/check.schema.json index 0ff3d98db4d..4eca2642a20 100644 --- a/schemas/ripr/check.schema.json +++ b/schemas/ripr/check.schema.json @@ -44,7 +44,11 @@ "type": "array", "items": { "$ref": "#/$defs/preview_language" } }, - "finding_alignment": { "$ref": "#/$defs/finding_alignment" } + "finding_alignment": { "$ref": "#/$defs/finding_alignment" }, + "test_harnesses": { + "type": "array", + "items": { "$ref": "#/$defs/test_harness_projection" } + } }, "$defs": { "nullable_string": { "type": ["string", "null"] }, @@ -449,6 +453,60 @@ "presentation_text": { "type": ["object", "null"] }, "config_policy": { "type": ["object", "null"] } } + }, + "test_harness_projection": { + "type": "object", + "additionalProperties": false, + "required": [ + "registration_id", + "harness_kind", + "adapter", + "marker", + "target", + "provenance", + "subjects", + "limitations" + ], + "properties": { + "registration_id": { "type": "string", "minLength": 1 }, + "harness_kind": { "type": "string", "minLength": 1 }, + "adapter": { "type": "string", "minLength": 1 }, + "marker": { "type": "string", "minLength": 1 }, + "target": { "type": "string", "minLength": 1 }, + "provenance": { "type": "string", "minLength": 1 }, + "subjects": { + "type": "array", + "items": { "$ref": "#/$defs/test_harness_subject" } + }, + "limitations": { + "type": "array", + "items": { "$ref": "#/$defs/test_harness_limitation" } + } + } + }, + "test_harness_subject": { + "type": "object", + "additionalProperties": false, + "required": ["name", "file", "start_line", "end_line", "selector", "claim"], + "properties": { + "name": { "type": "string", "minLength": 1 }, + "file": { "type": "string", "minLength": 1 }, + "start_line": { "type": "integer", "minimum": 1 }, + "end_line": { "type": "integer", "minimum": 1 }, + "selector": { "type": "string", "minLength": 1 }, + "claim": { "type": "string", "minLength": 1 } + } + }, + "test_harness_limitation": { + "type": "object", + "additionalProperties": false, + "required": ["code", "file", "line", "detail"], + "properties": { + "code": { "type": "string", "minLength": 1 }, + "file": { "type": "string", "minLength": 1 }, + "line": { "type": "integer", "minimum": 1 }, + "detail": { "type": "string", "minLength": 1 } + } } } } From c0a94301fe9feeb363feecb5f2477f567e53cf16 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 03:06:33 -0400 Subject: [PATCH 06/33] fix(analysis): close remaining harness review gaps --- .../src/analysis/facts/harness_registry.rs | 11 +++- crates/ripr/src/analysis/facts/mod.rs | 1 + crates/ripr/src/analysis/rust_index.rs | 7 +-- crates/ripr/src/analysis/seam_inventory.rs | 21 ++++--- crates/ripr/src/config.rs | 57 +++++++++++++++++++ crates/ripr/src/config/tests.rs | 10 ++++ 6 files changed, 93 insertions(+), 14 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index 9298dd06714..091ec31171f 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -432,8 +432,17 @@ fn trial_callback_name( let mut index = name_token_index + 1; while let Some(token) = tokens.get(index) { if token.kind() == ra_ap_syntax::SyntaxKind::COMMA { + let mut callback_index = index + 1; + while tokens.get(callback_index).is_some_and(|callback| { + matches!( + callback.kind(), + ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT + ) + }) { + callback_index += 1; + } return tokens - .get(index + 1) + .get(callback_index) .filter(|callback| callback.kind() == ra_ap_syntax::SyntaxKind::IDENT) .map(|callback| callback.text().to_string()); } diff --git a/crates/ripr/src/analysis/facts/mod.rs b/crates/ripr/src/analysis/facts/mod.rs index a4ce1bfbeee..6df24896f60 100644 --- a/crates/ripr/src/analysis/facts/mod.rs +++ b/crates/ripr/src/analysis/facts/mod.rs @@ -51,6 +51,7 @@ pub fn build_index_with_test_harnesses_and_production_like_targets( Ok(index) } +#[cfg(test)] pub(crate) fn build_index_from_loaded_files_with_cache_and_test_harnesses( root: &Path, files: &[(PathBuf, Vec)], diff --git a/crates/ripr/src/analysis/rust_index.rs b/crates/ripr/src/analysis/rust_index.rs index 8b75992d8de..3de08b0899f 100644 --- a/crates/ripr/src/analysis/rust_index.rs +++ b/crates/ripr/src/analysis/rust_index.rs @@ -18,18 +18,13 @@ pub(crate) use super::extract::{ unwrap_err_bound_variables, }; use super::facts::ModulePathTarget; -#[cfg(test)] -pub use super::facts::build_index_with_test_harnesses; +pub(crate) use super::facts::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets; #[cfg(test)] pub use super::facts::{CallFact, LiteralFact, ReturnFact}; pub use super::facts::{ FileFacts, FunctionFact, FunctionSummary, OracleFact, ProbeShapeFact, RustIndex, TestFact, TestSummary, build_index, build_index_with_test_harnesses_and_production_like_targets, }; -pub(crate) use super::facts::{ - build_index_from_loaded_files_with_cache_and_test_harnesses, - build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets, -}; #[cfg(test)] use super::syntax::LexicalRustSyntaxAdapter; pub use super::syntax::{RaRustSyntaxAdapter, RustSyntaxAdapter, SyntaxNodeFact, TextRange}; diff --git a/crates/ripr/src/analysis/seam_inventory.rs b/crates/ripr/src/analysis/seam_inventory.rs index e4c069f0759..2972978a3c5 100644 --- a/crates/ripr/src/analysis/seam_inventory.rs +++ b/crates/ripr/src/analysis/seam_inventory.rs @@ -402,10 +402,11 @@ pub(crate) fn inventory_classified_seams_uncached_with_config( trace_latency_phase("filter_production_files", "ok", filter_started.elapsed()); let index_started = Instant::now(); - let mut index = match rust_index::build_index_with_test_harnesses( + let mut index = match rust_index::build_index_with_test_harnesses_and_production_like_targets( root, &rust_files, harness_registrations(config), + config.analysis().production_like_targets(), ) { Ok(index) => { trace_latency_phase("build_index", "ok", index_started.elapsed()); @@ -577,10 +578,11 @@ fn inventory_seam_grip_class_counts_uncached_with_config( .cloned() .collect(); - let mut index = rust_index::build_index_with_test_harnesses( + let mut index = rust_index::build_index_with_test_harnesses_and_production_like_targets( root, &rust_files, harness_registrations(config), + config.analysis().production_like_targets(), )?; rust_index::apply_oracle_policy(&mut index, config.oracles()); let seams = inventory_seams_from_index(&production_files, &index); @@ -609,10 +611,11 @@ fn inventory_compact_classified_seams_from_state_with_config( ), Duration::ZERO, ); - let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &state.workspace_root, &state.files, harness_registrations(config), + config.analysis().production_like_targets(), )?; cancellation::checkpoint()?; trace_latency_phase( @@ -655,10 +658,11 @@ fn inventory_classified_seams_from_state_with_config( ), Duration::ZERO, ); - let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &state.workspace_root, &state.files, harness_registrations(config), + config.analysis().production_like_targets(), )?; trace_latency_phase( "file_fact_cache", @@ -727,10 +731,11 @@ pub(crate) fn inventory_changed_test_classified_seams_at_with_config_node( let state = collect_workspace_state(root, config)?; let workspace_cache_key = state.cache_key(); let changed_test = normalized_inventory_path(changed_test); - let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &state.workspace_root, &state.files, harness_registrations(config), + config.analysis().production_like_targets(), )?; rust_index::apply_oracle_policy(&mut cached.index, config.oracles()); @@ -850,10 +855,11 @@ pub(crate) fn inventory_diff_scoped_classified_seams_at_with_config( ), Duration::ZERO, ); - let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &state.workspace_root, &state.files, harness_registrations(config), + config.analysis().production_like_targets(), )?; trace_latency_phase( "file_fact_cache", @@ -1085,10 +1091,11 @@ fn inventory_seam_grip_class_counts_from_state_with_config( ), Duration::ZERO, ); - let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &state.workspace_root, &state.files, harness_registrations(config), + config.analysis().production_like_targets(), )?; trace_latency_phase( "file_fact_cache", diff --git a/crates/ripr/src/config.rs b/crates/ripr/src/config.rs index dd56bc65f51..d6effd54a11 100644 --- a/crates/ripr/src/config.rs +++ b/crates/ripr/src/config.rs @@ -922,9 +922,66 @@ fn marker_path_is_exact(marker: &str) -> bool { let mut characters = segment.chars(); matches!(characters.next(), Some(first) if first.is_ascii_alphabetic() || first == '_') && characters.all(|rest| rest.is_ascii_alphanumeric() || rest == '_') + && !is_reserved_rust_identifier(segment) }) } +fn is_reserved_rust_identifier(identifier: &str) -> bool { + matches!( + identifier, + "as" | "break" + | "const" + | "continue" + | "crate" + | "else" + | "enum" + | "extern" + | "false" + | "fn" + | "for" + | "if" + | "impl" + | "in" + | "let" + | "loop" + | "match" + | "mod" + | "move" + | "mut" + | "pub" + | "ref" + | "return" + | "self" + | "Self" + | "static" + | "struct" + | "super" + | "trait" + | "true" + | "type" + | "unsafe" + | "use" + | "where" + | "while" + | "async" + | "await" + | "dyn" + | "abstract" + | "become" + | "box" + | "do" + | "final" + | "macro" + | "override" + | "priv" + | "typeof" + | "unsized" + | "virtual" + | "yield" + | "try" + ) +} + #[cfg(test)] mod tests; diff --git a/crates/ripr/src/config/tests.rs b/crates/ripr/src/config/tests.rs index fddfcdfad25..9572dd666a4 100644 --- a/crates/ripr/src/config/tests.rs +++ b/crates/ripr/src/config/tests.rs @@ -1404,6 +1404,16 @@ fn parse_config_rejects_harness_root_escape_and_lookalike_marker() -> Result<(), marker_error.contains("exact identifier path"), "{marker_error}" ); + + for marker in ["fn", "myco::match"] { + let reserved_error = harness_parse_error(&format!( + "[[analysis.test_harnesses]]\nregistration_id = 'x'\ntarget = 'tests/a.rs'\nkind = 'registered_attribute'\nadapter = 'exact_attribute_v1'\nmarker = '{marker}'\n" + ))?; + assert!( + reserved_error.contains("exact identifier path"), + "{reserved_error}" + ); + } Ok(()) } From fd2bc98fea89f5ed6d489ac3361eb4d1740d385f Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 03:36:34 -0400 Subject: [PATCH 07/33] fix(analysis): preserve current path association guards --- .../src/analysis/classify/related_tests.rs | 6 --- crates/ripr/src/analysis/rust_index.rs | 33 +----------- .../test_grip_evidence/related_tests.rs | 3 +- .../src/analysis/test_grip_evidence/tests.rs | 53 +------------------ 4 files changed, 5 insertions(+), 90 deletions(-) diff --git a/crates/ripr/src/analysis/classify/related_tests.rs b/crates/ripr/src/analysis/classify/related_tests.rs index 75a09e3d58a..3b180aaa3f3 100644 --- a/crates/ripr/src/analysis/classify/related_tests.rs +++ b/crates/ripr/src/analysis/classify/related_tests.rs @@ -974,16 +974,10 @@ mod tests { fn given_non_utf8_stems_when_classify_extracts_then_lossy_collision_fails_closed() { use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; - // Two distinct non-UTF-8 leaf names share one lossy rendering; - // deriving stems through lossy conversion would fabricate - // file-name affinity between unrelated entities, so extraction - // must fail closed instead (#3599). let first = Path::new(OsStr::from_bytes(b"crates/app/src/pricing_\xff.rs")); let second = Path::new(OsStr::from_bytes(b"crates/app/src/pricing_\xfe.rs")); assert_eq!(normalized_file_stem(first), ""); assert_eq!(normalized_file_stem(second), ""); - // Valid-UTF-8 stems are unchanged, including dotfiles and - // `./`-prefixed forms that `normalize_path` trims. assert_eq!(normalized_file_stem(Path::new("src/config.rs")), "config"); assert_eq!(normalized_file_stem(Path::new("./src/config.rs")), "config"); } diff --git a/crates/ripr/src/analysis/rust_index.rs b/crates/ripr/src/analysis/rust_index.rs index 3de08b0899f..8286407a031 100644 --- a/crates/ripr/src/analysis/rust_index.rs +++ b/crates/ripr/src/analysis/rust_index.rs @@ -188,16 +188,6 @@ pub fn find_owner_function<'a>( if let Some(summary) = index.files.get(file) { return owner_in(summary); } - // Repo seams normalize their file identity to `/` separators - // (#3469 family) while index keys keep the producing host's - // separators. On the opposite-separator host the component-wise - // lookup above misses (`src\pricing.rs` is a single component on - // Linux), so fall back to matching normalized key forms. The scan - // only runs after the direct lookup missed, so native-separator - // inputs keep the exact-lookup cost. Non-UTF-8 paths fail closed: - // lossy replacement characters can collapse distinct names into - // one form and attribute the wrong owner, so neither side of the - // comparison may pass through lossy conversion. let target = file.to_str()?.replace('\\', "/"); index .files @@ -209,16 +199,6 @@ pub fn find_owner_function<'a>( .and_then(owner_in) } -/// `/`-separated display form of a path, independent of the host's -/// native separator. Used by [`is_test_file`] to judge the normalized -/// form; lossy text is safe here because replacement characters can -/// never become separators. The [`find_owner_function`] fallback does -/// NOT use this helper — identity attribution must not pass through -/// lossy conversion. -fn normalize_display(path: &Path) -> String { - path.to_string_lossy().replace('\\', "/") -} - pub fn changed_nodes_for_lines( index: &RustIndex, file: &Path, @@ -240,7 +220,7 @@ pub fn changed_nodes_for_lines( } pub(crate) fn is_test_file(path: &Path) -> bool { - let normalized = normalize_display(path); + let normalized = path.to_string_lossy().replace('\\', "/"); normalized == "tests" || normalized.starts_with("tests/") || normalized.contains("/tests/") } @@ -252,15 +232,10 @@ mod tests { fn find_owner_function_resolves_normalized_seam_paths() { let facts = summarize_file( PathBuf::from("src\\pricing.rs"), - "fn apply_discount(amount: i32, threshold: i32) -> i32 { \ - if amount >= threshold { amount - 10 } else { amount } }\n" - .to_string(), + "fn apply_discount(amount: i32, threshold: i32) -> i32 { amount }\n".to_string(), ); let mut index = RustIndex::default(); index.files.insert(PathBuf::from("src\\pricing.rs"), facts); - // Repo seams carry `/`-normalized file identity; on Linux this is - // not component-equal to the `\`-separator index key, so the - // direct lookup misses and the normalized fallback must resolve. let owner = find_owner_function(&index, Path::new("src/pricing.rs"), 1); assert_eq!(owner.map(|f| f.name.as_str()), Some("apply_discount")); } @@ -271,7 +246,6 @@ mod tests { assert!(is_test_file(Path::new("tests/pricing_test.rs"))); assert!(is_test_file(Path::new("crates\\demo\\tests\\main.rs"))); assert!(!is_test_file(Path::new("src\\pricing.rs"))); - // A `tests`-prefixed sibling directory name stays production. assert!(!is_test_file(Path::new("testing\\pricing.rs"))); } @@ -289,9 +263,6 @@ mod tests { PathBuf::from(OsStr::from_bytes(b"src/pricing_\xff.rs")), facts, ); - // A query whose lossy rendering collides with the indexed key - // must not attribute the owner through lossy text: the fallback - // requires valid UTF-8 on both sides. let colliding = Path::new(OsStr::from_bytes(b"src\\pricing_\xfe.rs")); assert_eq!( find_owner_function(&index, colliding, 1).map(|f| f.name.as_str()), diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs index b90397b10a7..3bba96eee96 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs @@ -774,8 +774,7 @@ pub(super) fn normalize_path(path: &Path) -> String { /// makes [`std::path::Path::file_stem`] treat an entire relative path as /// one file name, so same-test-file lookups miss on exactly one host. /// Non-UTF-8 paths fail closed: lossy replacement characters could -/// collapse distinct file names into one stem and fabricate a -/// same-test-file relation (the #3545 `cross_host_stem` guard). +/// collapse distinct file names and fabricate a same-test-file relation. pub(super) fn normalized_file_stem(path: &Path) -> String { let Some(text) = path.to_str() else { return String::new(); diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index 10f4e42a230..199b768ffdb 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -10233,18 +10233,7 @@ fn given_same_module_test_without_direct_call_when_related_tests_are_ranked_then #[test] fn given_foreign_separator_paths_when_grip_associates_then_same_test_file_still_matches() -> Result<(), String> { - // #3469: a path carrying the other platform's separator (facts - // materialized on Windows, analyzed on Linux, or vice versa) broke - // the SameTestFile relation in two stacked places: the owner lookup - // compared the seam's `/`-normalized file identity against raw - // host-separator index keys (`Path` component equality only - // absorbs this on `\`-native hosts), and both association stems - // were derived with the host-native `Path::file_stem`. Every - // separator combination must associate; the test body stays free - // of owner/discriminator identifiers so SameTestFile is the only - // reason that can fire. - let prod_src = "pub fn apply_discount(amount: i32, threshold: i32) -> i32 \ - { if amount >= threshold { amount - 10 } else { amount } }\n"; + let prod_src = "pub fn apply_discount(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; let test_src = "#[test] fn bounds_smoke() { assert_eq!(1, 1); }\n"; let combinations = [ ("src/pricing.rs", "tests/pricing_test.rs"), @@ -10264,59 +10253,21 @@ fn given_foreign_separator_paths_when_grip_associates_then_same_test_file_still_ .find(|s| s.kind() == SeamKind::PredicateBoundary) .ok_or_else(|| "predicate seam present".to_string())?; let evidence = evidence_for_seam(predicate, &index); - let context = CompactGripContext::new(&index); - let owner_fn = crate::analysis::rust_index::find_owner_function( - &index, - predicate.file(), - predicate.display_line(), - ); - let ctx_tests: Vec = context - .tests - .iter() - .map(|t| t.test.file.to_string_lossy().to_string()) - .collect(); assert!( evidence .related_tests .iter() - .any(|grip| grip.relation_reason == RelationReason::SameTestFile), - "same-test-file association must hold for owner `{owner_path}` / test \ - `{test_path}`; got {:?} | diag: index_files={:?} index_tests={} \ - ctx_tests={ctx_tests:?} stem_keys={:?} seam_file={:?} seam_line={} \ - owner={owner_fn:?} owner_stem_norm={:?} owner_stem_native={:?} \ - test_stem_norm={:?} test_stem_native={:?}", - evidence.related_tests, - index.files.keys().collect::>(), - index.tests.len(), - context.tests_by_file_stem.keys().collect::>(), - predicate.file(), - predicate.display_line(), - normalized_file_stem_to_string(Path::new(owner_path)), - Path::new(owner_path) - .file_stem() - .map(|s| s.to_string_lossy().to_string()), - normalized_file_stem_to_string(Path::new(test_path)), - Path::new(test_path) - .file_stem() - .map(|s| s.to_string_lossy().to_string()), + .any(|grip| { grip.relation_reason == RelationReason::SameTestFile }) ); } Ok(()) } -fn normalized_file_stem_to_string(path: &Path) -> String { - super::related_tests::normalized_file_stem(path) -} - #[test] #[cfg(unix)] fn given_non_utf8_stems_when_grip_associates_then_lossy_collision_fails_closed() { use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; - // Two distinct non-UTF-8 names can share one lossy rendering; - // deriving stems through lossy conversion would fabricate a - // same-test-file relation between unrelated entities, so stem - // extraction must fail closed instead. let first = Path::new(OsStr::from_bytes(b"tests/pricing_\xff.rs")); let second = Path::new(OsStr::from_bytes(b"tests/pricing_\xfe.rs")); assert_eq!(normalized_file_stem(first), ""); From dc0c9fb96e7ab096336a1731639c46ae742c2c85 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 03:38:31 -0400 Subject: [PATCH 08/33] ci(ripr): align PR evidence budget with harness capability --- .github/workflows/rust-gates.yml | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/.github/workflows/rust-gates.yml b/.github/workflows/rust-gates.yml index 1a5b74ec887..0308a019579 100644 --- a/.github/workflows/rust-gates.yml +++ b/.github/workflows/rust-gates.yml @@ -173,12 +173,15 @@ jobs: HEAD_SHA: ${{ github.event.pull_request.head.sha }} GITHUB_PR_LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }} RIPR_REVIEW_COMMENTS_TIMEOUT_SECS: "60" - # Raised from the 2000 default as the PR #3592 decision artifact; the variable is documented in docs/CONFIGURATION.md. - RIPR_MAX_DIFF_CHANGED_RUST_LINES: "3000" + # Raised from the 2000 default as the PR #3592 decision artifact, then + # to 3500 for #3532 (3,222-line capability diff); the variable is + # documented in docs/CONFIGURATION.md. + RIPR_MAX_DIFF_CHANGED_RUST_LINES: "3500" # Match the raised max limit: the partial-budget clamp bounds against - # the effective limit, so without this a 2001-3000-line PR passes the - # hard guard but still lands in gate-ineligible limited_partial_scope. - RIPR_PARTIAL_DIFF_LINE_BUDGET: "3000" + # the effective limit, so without this a PR above the default passes + # the hard guard but still lands in gate-ineligible + # limited_partial_scope. + RIPR_PARTIAL_DIFF_LINE_BUDGET: "3500" # Large analyzer PRs need more than the 120s default for the # evidence producer's ripr check subprocess. RIPR_PR_EVIDENCE_TIMEOUT_SECS: "600" From fd7b5a31e43232d0a41294c806a82356c71f956a Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 03:46:03 -0400 Subject: [PATCH 09/33] fix(analysis): retain rebased path guard context --- .../src/analysis/classify/related_tests.rs | 6 ++++ crates/ripr/src/analysis/rust_index.rs | 33 +++++++++++++++++-- .../test_grip_evidence/related_tests.rs | 3 +- .../src/analysis/test_grip_evidence/tests.rs | 27 +++++++++++++-- 4 files changed, 64 insertions(+), 5 deletions(-) diff --git a/crates/ripr/src/analysis/classify/related_tests.rs b/crates/ripr/src/analysis/classify/related_tests.rs index 3b180aaa3f3..75a09e3d58a 100644 --- a/crates/ripr/src/analysis/classify/related_tests.rs +++ b/crates/ripr/src/analysis/classify/related_tests.rs @@ -974,10 +974,16 @@ mod tests { fn given_non_utf8_stems_when_classify_extracts_then_lossy_collision_fails_closed() { use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; + // Two distinct non-UTF-8 leaf names share one lossy rendering; + // deriving stems through lossy conversion would fabricate + // file-name affinity between unrelated entities, so extraction + // must fail closed instead (#3599). let first = Path::new(OsStr::from_bytes(b"crates/app/src/pricing_\xff.rs")); let second = Path::new(OsStr::from_bytes(b"crates/app/src/pricing_\xfe.rs")); assert_eq!(normalized_file_stem(first), ""); assert_eq!(normalized_file_stem(second), ""); + // Valid-UTF-8 stems are unchanged, including dotfiles and + // `./`-prefixed forms that `normalize_path` trims. assert_eq!(normalized_file_stem(Path::new("src/config.rs")), "config"); assert_eq!(normalized_file_stem(Path::new("./src/config.rs")), "config"); } diff --git a/crates/ripr/src/analysis/rust_index.rs b/crates/ripr/src/analysis/rust_index.rs index 8286407a031..c7470525ff4 100644 --- a/crates/ripr/src/analysis/rust_index.rs +++ b/crates/ripr/src/analysis/rust_index.rs @@ -188,6 +188,16 @@ pub fn find_owner_function<'a>( if let Some(summary) = index.files.get(file) { return owner_in(summary); } + // Repo seams normalize their file identity to `/` separators + // (#3469 family) while index keys keep the producing host's + // separators. On the opposite-separator host the component-wise + // lookup above misses (`src\pricing.rs` is a single component on + // Linux), so fall back to matching normalized key forms. The scan + // only runs after the direct lookup missed, so native-separator + // inputs keep the exact-lookup cost. Non-UTF-8 paths fail closed: + // lossy replacement characters can collapse distinct names onto + // one form and attribute the wrong owner, so neither side of the + // comparison may pass through lossy conversion. let target = file.to_str()?.replace('\\', "/"); index .files @@ -199,6 +209,16 @@ pub fn find_owner_function<'a>( .and_then(owner_in) } +/// `/`-separated display form of a path, independent of the host's +/// native separator. Used by [`is_test_file`] to judge the normalized +/// form; lossy text is safe here because replacement characters can +/// never become separators. The [`find_owner_function`] fallback does +/// NOT use this helper — identity attribution must not pass through +/// lossy conversion. +fn normalize_display(path: &Path) -> String { + path.to_string_lossy().replace('\\', "/") +} + pub fn changed_nodes_for_lines( index: &RustIndex, file: &Path, @@ -220,7 +240,7 @@ pub fn changed_nodes_for_lines( } pub(crate) fn is_test_file(path: &Path) -> bool { - let normalized = path.to_string_lossy().replace('\\', "/"); + let normalized = normalize_display(path); normalized == "tests" || normalized.starts_with("tests/") || normalized.contains("/tests/") } @@ -232,10 +252,15 @@ mod tests { fn find_owner_function_resolves_normalized_seam_paths() { let facts = summarize_file( PathBuf::from("src\\pricing.rs"), - "fn apply_discount(amount: i32, threshold: i32) -> i32 { amount }\n".to_string(), + "fn apply_discount(amount: i32, threshold: i32) -> i32 { \ + if amount >= threshold { amount - 10 } else { amount } }\n" + .to_string(), ); let mut index = RustIndex::default(); index.files.insert(PathBuf::from("src\\pricing.rs"), facts); + // Repo seams carry `/`-normalized file identity; on Linux this is + // not component-equal to the `\\`-separator index key, so the + // direct lookup misses and the normalized fallback must resolve. let owner = find_owner_function(&index, Path::new("src/pricing.rs"), 1); assert_eq!(owner.map(|f| f.name.as_str()), Some("apply_discount")); } @@ -246,6 +271,7 @@ mod tests { assert!(is_test_file(Path::new("tests/pricing_test.rs"))); assert!(is_test_file(Path::new("crates\\demo\\tests\\main.rs"))); assert!(!is_test_file(Path::new("src\\pricing.rs"))); + // A `tests`-prefixed sibling directory name stays production. assert!(!is_test_file(Path::new("testing\\pricing.rs"))); } @@ -263,6 +289,9 @@ mod tests { PathBuf::from(OsStr::from_bytes(b"src/pricing_\xff.rs")), facts, ); + // A query whose lossy rendering collides with the indexed key + // must not attribute the owner through lossy text: the fallback + // requires valid UTF-8 on both sides. let colliding = Path::new(OsStr::from_bytes(b"src\\pricing_\xfe.rs")); assert_eq!( find_owner_function(&index, colliding, 1).map(|f| f.name.as_str()), diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs index 3bba96eee96..03097014ce6 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs @@ -774,7 +774,8 @@ pub(super) fn normalize_path(path: &Path) -> String { /// makes [`std::path::Path::file_stem`] treat an entire relative path as /// one file name, so same-test-file lookups miss on exactly one host. /// Non-UTF-8 paths fail closed: lossy replacement characters could -/// collapse distinct file names and fabricate a same-test-file relation. +/// collapse distinct file names and fabricate a +/// same-test-file relation (the #3545 `cross_host_stem` guard). pub(super) fn normalized_file_stem(path: &Path) -> String { let Some(text) = path.to_str() else { return String::new(); diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index 199b768ffdb..968ae94b0d1 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -10233,7 +10233,14 @@ fn given_same_module_test_without_direct_call_when_related_tests_are_ranked_then #[test] fn given_foreign_separator_paths_when_grip_associates_then_same_test_file_still_matches() -> Result<(), String> { - let prod_src = "pub fn apply_discount(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + // #3469: a path carrying the other platform's separator (facts + // materialized on Windows, analyzed on Linux, or vice versa) broke + // the SameTestFile relation in two stacked places: the owner lookup + // compared the seam's `/`-normalized file identity against raw + // host-separator index keys, and both association stems were derived + // with the host-native `Path::file_stem`. + let prod_src = "pub fn apply_discount(amount: i32, threshold: i32) -> i32 \ + { if amount >= threshold { amount - 10 } else { amount } }\n"; let test_src = "#[test] fn bounds_smoke() { assert_eq!(1, 1); }\n"; let combinations = [ ("src/pricing.rs", "tests/pricing_test.rs"), @@ -10253,11 +10260,26 @@ fn given_foreign_separator_paths_when_grip_associates_then_same_test_file_still_ .find(|s| s.kind() == SeamKind::PredicateBoundary) .ok_or_else(|| "predicate seam present".to_string())?; let evidence = evidence_for_seam(predicate, &index); + let context = CompactGripContext::new(&index); + let owner_fn = crate::analysis::rust_index::find_owner_function( + &index, + predicate.file(), + predicate.display_line(), + ); assert!( evidence .related_tests .iter() - .any(|grip| { grip.relation_reason == RelationReason::SameTestFile }) + .any(|grip| grip.relation_reason == RelationReason::SameTestFile), + "same-test-file association must hold for owner `{owner_path}` / test \ + `{test_path}`; got {:?} | index_files={:?} index_tests={} \ + ctx_tests={:?} stem_keys={:?} seam_file={:?} seam_line={} owner={owner_fn:?}", + evidence.related_tests, + index.files.keys().collect::>(), + index.tests.len(), + context.tests_by_file_stem.keys().collect::>(), + predicate.file(), + predicate.display_line(), ); } Ok(()) @@ -10270,6 +10292,7 @@ fn given_non_utf8_stems_when_grip_associates_then_lossy_collision_fails_closed() use std::os::unix::ffi::OsStrExt; let first = Path::new(OsStr::from_bytes(b"tests/pricing_\xff.rs")); let second = Path::new(OsStr::from_bytes(b"tests/pricing_\xfe.rs")); + // Two distinct non-UTF-8 names must never collide through lossy text. assert_eq!(normalized_file_stem(first), ""); assert_eq!(normalized_file_stem(second), ""); } From cad74bb1fd612fb9e19b9998deaf84f635ce6eb8 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 03:52:55 -0400 Subject: [PATCH 10/33] test(analysis): restore path-association diagnostics --- crates/ripr/src/analysis/test_grip_evidence/tests.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index 968ae94b0d1..b6fec350c8f 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -10266,6 +10266,11 @@ fn given_foreign_separator_paths_when_grip_associates_then_same_test_file_still_ predicate.file(), predicate.display_line(), ); + let ctx_tests: Vec = context + .tests + .iter() + .map(|t| t.test.file.to_string_lossy().to_string()) + .collect(); assert!( evidence .related_tests @@ -10277,6 +10282,7 @@ fn given_foreign_separator_paths_when_grip_associates_then_same_test_file_still_ evidence.related_tests, index.files.keys().collect::>(), index.tests.len(), + ctx_tests, context.tests_by_file_stem.keys().collect::>(), predicate.file(), predicate.display_line(), From ee8d0c7a5581a7143189828ede72f16840d8ec0b Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 04:47:16 -0400 Subject: [PATCH 11/33] fix(analysis): preserve qualified harness callback evidence --- .../src/analysis/extract/oracles/arguments.rs | 25 ++- .../src/analysis/extract/oracles/patterns.rs | 4 +- .../src/analysis/facts/harness_registry.rs | 145 ++++++++++++++---- .../analysis/facts/harness_registry/tests.rs | 92 +++++++++++ 4 files changed, 228 insertions(+), 38 deletions(-) diff --git a/crates/ripr/src/analysis/extract/oracles/arguments.rs b/crates/ripr/src/analysis/extract/oracles/arguments.rs index c1a04c2d3b5..031537a876b 100644 --- a/crates/ripr/src/analysis/extract/oracles/arguments.rs +++ b/crates/ripr/src/analysis/extract/oracles/arguments.rs @@ -25,7 +25,7 @@ fn macro_invocation_arguments(line: &str, macro_name: &str) -> Option Option { if open != b'(' { return None; } - let mut depth = 0i32; + let mut delimiters = Vec::new(); let mut in_string = false; let mut escaped = false; let mut content_start = None; @@ -57,15 +57,24 @@ fn delimited_contents_at(text: &str, open_index: usize) -> Option { } match ch { '"' => in_string = true, - '(' => { - depth += 1; - if depth == 1 { + '(' | '[' | '{' => { + delimiters.push(ch); + if delimiters.len() == 1 { content_start = Some(index + ch.len_utf8()); } } - ')' => { - depth -= 1; - if depth == 0 { + ')' | ']' | '}' => { + let opening = delimiters.pop()?; + let expected = match opening { + '(' => ')', + '[' => ']', + '{' => '}', + _ => return None, + }; + if ch != expected { + return None; + } + if delimiters.is_empty() { let start = content_start?; return Some(text[start..index].to_string()); } diff --git a/crates/ripr/src/analysis/extract/oracles/patterns.rs b/crates/ripr/src/analysis/extract/oracles/patterns.rs index 7284eb77a31..9fd9969ccd5 100644 --- a/crates/ripr/src/analysis/extract/oracles/patterns.rs +++ b/crates/ripr/src/analysis/extract/oracles/patterns.rs @@ -266,7 +266,9 @@ pub(super) fn is_broad_error_assertion(line: &str) -> bool { } pub(super) fn is_whole_object_equality_assertion(line: &str) -> bool { - (line.contains("assert_eq!") || line.contains("assert_ne!")) && line.contains('{') + (line.contains("assert_eq!") || line.contains("assert_ne!")) + && equality_assertion_arguments(line) + .is_some_and(|arguments| arguments.get(1).is_some_and(|right| right.contains('{'))) } pub(super) fn is_duplicative_equality_assertion(line: &str) -> bool { diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index 091ec31171f..cf2dc6729d2 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -265,7 +265,7 @@ fn apply_libtest_mimic_target( "trial callback `{callback_name}` is not a unique function item in the registered target; subject evidence remains unresolved" ), }); - continue; + None } }, None => None, @@ -441,10 +441,52 @@ fn trial_callback_name( }) { callback_index += 1; } - return tokens - .get(callback_index) - .filter(|callback| callback.kind() == ra_ap_syntax::SyntaxKind::IDENT) - .map(|callback| callback.text().to_string()); + let first = tokens.get(callback_index)?; + if first.kind() != ra_ap_syntax::SyntaxKind::IDENT { + return None; + } + let mut callback = first.text().to_string(); + callback_index += 1; + loop { + while tokens.get(callback_index).is_some_and(|token| { + matches!( + token.kind(), + ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT + ) + }) { + callback_index += 1; + } + let separator_width = match tokens.get(callback_index).map(|token| token.kind()) { + Some(ra_ap_syntax::SyntaxKind::COLON2) => Some(1), + Some(ra_ap_syntax::SyntaxKind::COLON) + if tokens.get(callback_index + 1).is_some_and(|token| { + token.kind() == ra_ap_syntax::SyntaxKind::COLON + }) => + { + Some(2) + } + _ => None, + }; + let Some(separator_width) = separator_width else { + break; + }; + callback_index += separator_width; + while tokens.get(callback_index).is_some_and(|token| { + matches!( + token.kind(), + ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT + ) + }) { + callback_index += 1; + } + let segment = tokens + .get(callback_index) + .filter(|token| token.kind() == ra_ap_syntax::SyntaxKind::IDENT)?; + callback.push_str("::"); + callback.push_str(segment.text()); + callback_index += 1; + } + return Some(callback); } if token.kind() == ra_ap_syntax::SyntaxKind::R_PAREN { return None; @@ -455,6 +497,10 @@ fn trial_callback_name( } fn unique_callback_function(index: &RustIndex, target: &Path, name: &str) -> Option { + let name = match name.rsplit("::").next() { + Some(name) => name, + None => name, + }; let mut matches = index .files .get(target)? @@ -509,16 +555,34 @@ fn parser_oracles_for_node_tokens( ra_ap_syntax::SyntaxKind::IDENT => { let name = token.text(); let next = tokens.get(index + 1); - let is_macro_invocation = is_assertion_macro_name(name) + let macro_open_index = if is_assertion_macro_name(name) && next.is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::BANG) - && tokens.get(index + 2).is_some_and(|token| { + { + let mut open_index = index + 2; + while tokens.get(open_index).is_some_and(|token| { matches!( token.kind(), - ra_ap_syntax::SyntaxKind::L_PAREN - | ra_ap_syntax::SyntaxKind::L_CURLY - | ra_ap_syntax::SyntaxKind::L_BRACK + ra_ap_syntax::SyntaxKind::WHITESPACE + | ra_ap_syntax::SyntaxKind::COMMENT ) - }); + }) { + open_index += 1; + } + tokens + .get(open_index) + .is_some_and(|token| { + matches!( + token.kind(), + ra_ap_syntax::SyntaxKind::L_PAREN + | ra_ap_syntax::SyntaxKind::L_CURLY + | ra_ap_syntax::SyntaxKind::L_BRACK + ) + }) + .then_some(open_index) + } else { + None + }; + let is_macro_invocation = macro_open_index.is_some(); let is_fallible_call = matches!(name, "unwrap" | "expect") && index >= 1 && tokens[index - 1].kind() == ra_ap_syntax::SyntaxKind::DOT @@ -541,24 +605,11 @@ fn parser_oracles_for_node_tokens( .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::BANG) { text.push('!'); - cursor += 1; - if tokens - .get(cursor) - .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::L_PAREN) - { - let mut macro_depth = 1; - cursor += 1; - while cursor < tokens.len() && macro_depth > 0 { - let inner = &tokens[cursor]; - match inner.kind() { - ra_ap_syntax::SyntaxKind::L_PAREN => macro_depth += 1, - ra_ap_syntax::SyntaxKind::R_PAREN => macro_depth -= 1, - _ => {} - } - text.push_str(inner.text()); - cursor += 1; - } - text.push(')'); + if let Some(open_index) = macro_open_index { + cursor = open_index; + } + if let Some(tree_text) = macro_token_tree_text(tokens, cursor) { + text.push_str(&tree_text); } } else if is_fallible_call { // The method name itself is sufficient for the shared @@ -582,6 +633,42 @@ fn parser_oracles_for_node_tokens( assertions } +fn macro_token_tree_text( + tokens: &[ra_ap_syntax::SyntaxToken], + open_index: usize, +) -> Option { + let mut delimiters = Vec::new(); + let mut text = String::new(); + for token in tokens.iter().skip(open_index) { + let kind = token.kind(); + match kind { + ra_ap_syntax::SyntaxKind::L_PAREN + | ra_ap_syntax::SyntaxKind::L_CURLY + | ra_ap_syntax::SyntaxKind::L_BRACK => delimiters.push(kind), + ra_ap_syntax::SyntaxKind::R_PAREN + | ra_ap_syntax::SyntaxKind::R_CURLY + | ra_ap_syntax::SyntaxKind::R_BRACK => { + let opening = delimiters.pop()?; + let expected = match opening { + ra_ap_syntax::SyntaxKind::L_PAREN => ra_ap_syntax::SyntaxKind::R_PAREN, + ra_ap_syntax::SyntaxKind::L_CURLY => ra_ap_syntax::SyntaxKind::R_CURLY, + ra_ap_syntax::SyntaxKind::L_BRACK => ra_ap_syntax::SyntaxKind::R_BRACK, + _ => return None, + }; + if kind != expected { + return None; + } + } + _ => {} + } + text.push_str(token.text()); + if delimiters.is_empty() { + return Some(text); + } + } + None +} + fn is_assertion_macro_name(name: &str) -> bool { matches!( name, diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs index 14525bbdf4a..c73ddbf28fd 100644 --- a/crates/ripr/src/analysis/facts/harness_registry/tests.rs +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -6,6 +6,7 @@ use super::*; use crate::analysis::facts::build_index_with_test_harnesses; +use crate::domain::OracleKind; use std::collections::BTreeSet; use std::fs; use std::path::PathBuf; @@ -457,6 +458,97 @@ fn trial_oracles_require_real_macros_and_preserve_source_lines() Ok(()) } +#[test] +fn qualified_trial_callbacks_keep_subjects_and_resolve_terminal_function_names() +-> Result<(), Box> { + let root = temp_dir("qualified-callbacks")?; + write_workspace( + &root, + &[( + "tests/callbacks.rs", + r#" +use libtest_mimic::Trial; +fn check() { + assert_eq!(1, 1); +} +fn trials() -> Vec { + vec![ + Trial::test("resolved_callback", callbacks::check), + Trial::test("unresolved_callback", missing::callback), + ] +} +"#, + )], + )?; + let index = build_index_with_test_harnesses( + &root.0, + &[PathBuf::from("tests/callbacks.rs")], + &[custom_target_registration("tests/callbacks.rs")], + )?; + assert_eq!(index.harness_subjects.len(), 2); + let resolved = index + .harness_subjects + .iter() + .find(|subject| subject.name == "resolved_callback") + .ok_or("missing resolved callback subject")?; + assert!( + resolved + .assertions + .iter() + .any(|oracle| oracle.text.starts_with("assert_eq!")) + ); + assert!(index.harness_limitations.iter().any(|limitation| { + limitation.code == "unresolved_trial_callback" + && limitation.detail.contains("missing::callback") + })); + Ok(()) +} + +#[test] +fn trial_oracles_preserve_brace_and_bracket_macro_delimiters() +-> Result<(), Box> { + let root = temp_dir("delimited-oracles")?; + write_workspace( + &root, + &[( + "tests/delimiters.rs", + r#" +use libtest_mimic::Trial; +fn trials() -> Vec { + vec![Trial::test("delimiters", || { + let result = 1; + assert_eq! { result, 1 }; + assert_eq! [result, 1]; + Ok(()) + })] +} +"#, + )], + )?; + let index = build_index_with_test_harnesses( + &root.0, + &[PathBuf::from("tests/delimiters.rs")], + &[custom_target_registration("tests/delimiters.rs")], + )?; + let subject = index + .harness_subjects + .iter() + .find(|subject| subject.name == "delimiters") + .ok_or("missing delimiter subject")?; + assert_eq!(subject.assertions.len(), 2); + assert!(subject.assertions.iter().any(|oracle| { + oracle.kind == OracleKind::ExactValue + && oracle.text.contains("{") + && oracle.text.contains("}") + })); + assert!(subject.assertions.iter().any(|oracle| { + oracle.kind == OracleKind::ExactValue + && oracle.text.contains("[") + && oracle.text.contains("]") + })); + Ok(()) +} + #[test] fn registered_attribute_promotes_exact_matches_only() -> Result<(), Box> { let root = temp_dir("registered-attribute")?; From 925df4ec8f77834546871644b5e7bf69ea7f7bb5 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 05:03:12 -0400 Subject: [PATCH 12/33] test(analysis): cover delimited harness assertions --- crates/ripr/src/analysis/extract/oracles/arguments.rs | 2 +- crates/ripr/src/analysis/facts/harness_registry/tests.rs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/ripr/src/analysis/extract/oracles/arguments.rs b/crates/ripr/src/analysis/extract/oracles/arguments.rs index 031537a876b..9cbdc5540ce 100644 --- a/crates/ripr/src/analysis/extract/oracles/arguments.rs +++ b/crates/ripr/src/analysis/extract/oracles/arguments.rs @@ -36,7 +36,7 @@ fn macro_invocation_arguments(line: &str, macro_name: &str) -> Option Option { let open = text.as_bytes().get(open_index).copied()?; - if open != b'(' { + if !matches!(open, b'(' | b'[' | b'{') { return None; } let mut delimiters = Vec::new(); diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs index c73ddbf28fd..53d8bea0159 100644 --- a/crates/ripr/src/analysis/facts/harness_registry/tests.rs +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -517,8 +517,8 @@ use libtest_mimic::Trial; fn trials() -> Vec { vec![Trial::test("delimiters", || { let result = 1; - assert_eq! { result, 1 }; - assert_eq! [result, 1]; + assert_eq! { result, Config { field: 1 } }; + assert_eq! [result, Config { field: 1 }]; Ok(()) })] } @@ -537,12 +537,12 @@ fn trials() -> Vec { .ok_or("missing delimiter subject")?; assert_eq!(subject.assertions.len(), 2); assert!(subject.assertions.iter().any(|oracle| { - oracle.kind == OracleKind::ExactValue + oracle.kind == OracleKind::WholeObjectEquality && oracle.text.contains("{") && oracle.text.contains("}") })); assert!(subject.assertions.iter().any(|oracle| { - oracle.kind == OracleKind::ExactValue + oracle.kind == OracleKind::WholeObjectEquality && oracle.text.contains("[") && oracle.text.contains("]") })); From 2046160b24a68ed198ca0eac432cd6f803b935b4 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Sun, 30 Aug 2026 20:55:57 -0400 Subject: [PATCH 13/33] fix(analysis): preserve harness cache exports after rebase --- crates/ripr/src/analysis/facts/mod.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/ripr/src/analysis/facts/mod.rs b/crates/ripr/src/analysis/facts/mod.rs index 1074132c1df..d4238768f11 100644 --- a/crates/ripr/src/analysis/facts/mod.rs +++ b/crates/ripr/src/analysis/facts/mod.rs @@ -7,6 +7,9 @@ mod parameterized_tests; mod role_composition; mod test_styles; +#[cfg(test)] +pub(crate) use build::build_index_from_loaded_files_with_cache; + use std::path::{Path, PathBuf}; use crate::config::TestHarnessRegistration; @@ -76,6 +79,8 @@ pub use model::{ ModuleDeclarationFact, ModulePathTarget, OracleFact, ProbeShapeFact, ResolvedIncludeParent, ReturnFact, RustIncludeLimitation, RustIndex, SourceRoleProvenance, SourceRoleProvenanceEdge, SourceRoleProvenanceEdgeKind, TestFact, TestSummary, + HarnessLimitationFact, + HarnessSelectorCapability, HarnessSubjectClaim, HarnessSubjectFact, }; #[cfg(test)] pub(crate) use model::{WorkspaceFileAuthority, WorkspaceRootAuthority}; From 5574ccbb762bf250ea897e841f292ca599237a3e Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 02:06:48 -0400 Subject: [PATCH 14/33] fix(analysis): preserve composed roles in cached test facade --- crates/ripr/src/analysis/facts/mod.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/crates/ripr/src/analysis/facts/mod.rs b/crates/ripr/src/analysis/facts/mod.rs index d4238768f11..3fd229059ce 100644 --- a/crates/ripr/src/analysis/facts/mod.rs +++ b/crates/ripr/src/analysis/facts/mod.rs @@ -7,9 +7,6 @@ mod parameterized_tests; mod role_composition; mod test_styles; -#[cfg(test)] -pub(crate) use build::build_index_from_loaded_files_with_cache; - use std::path::{Path, PathBuf}; use crate::config::TestHarnessRegistration; From a1afd002061427f2e8e56d44562883bf1c295f4c Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 02:40:56 -0400 Subject: [PATCH 15/33] fix(analysis): harden registered harness evidence --- .../src/analysis/facts/harness_registry.rs | 166 +++++++++++++++++- .../analysis/facts/harness_registry/tests.rs | 93 +++++++++- crates/ripr/src/analysis/facts/mod.rs | 42 ++++- crates/ripr/src/analysis/language/rust.rs | 6 +- crates/ripr/src/analysis/rust_index.rs | 9 +- crates/ripr/src/analysis/seam_inventory.rs | 3 +- 6 files changed, 295 insertions(+), 24 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index 51adf3c8f67..dcf25af23ef 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -33,6 +33,7 @@ use super::test_styles::normalized_test_attribute_path as normalized_attribute_p use super::{ HarnessLimitationFact, HarnessSelectorCapability, HarnessSubjectClaim, HarnessSubjectFact, }; +use crate::analysis::extract::extract_assertions; use crate::analysis::rust_index::{ OracleFact, classify_assertion, extract_call_facts, extract_identifier_tokens, extract_literal_facts, @@ -52,6 +53,7 @@ use std::path::Path; pub(super) fn apply_registrations( index: &mut RustIndex, registrations: &[TestHarnessRegistration], + production_like_targets: &std::collections::BTreeSet, ) { if registrations.is_empty() { return; @@ -68,6 +70,9 @@ pub(super) fn apply_registrations( let source = facts.source.clone(); match (registration.kind, registration.adapter) { (TestHarnessKind::CustomHarnessTarget, TestHarnessAdapter::LibtestMimicV1) => { + if production_like_targets.contains(®istration.target) { + continue; + } apply_libtest_mimic_target( index, registration, @@ -77,6 +82,9 @@ pub(super) fn apply_registrations( ) } (TestHarnessKind::RegisteredAttribute, TestHarnessAdapter::ExactAttributeV1) => { + if production_like_targets.contains(®istration.target) { + continue; + } apply_registered_attribute( index, registration, @@ -244,6 +252,13 @@ fn apply_libtest_mimic_target( "trial name `{name}` is registered more than once; conflicting subject claims fail closed" ), }); + subjects.retain(|subject| { + !(subject.registration_id == registration.registration_id && subject.name == name) + }); + remove_file_test(index, &target, &name); + index + .tests + .retain(|test| !(test.file == target && test.name == name)); continue; } // The subject span runs from the trial path to the balanced @@ -251,14 +266,40 @@ fn apply_libtest_mimic_target( let Some(end_offset) = balanced_call_end(&tokens, matched.open_paren_index) else { continue; }; + let callback = match trial_callback_name(&tokens, matched.name_token_index) { + Some(callback_name) => match unique_callback_function(index, &target, &callback_name) { + Some(function) => Some(function), + None => { + limitations.push(HarnessLimitationFact { + registration_id: registration.registration_id.clone(), + code: "unresolved_trial_callback".to_string(), + file: target.clone(), + line, + detail: format!( + "trial callback `{callback_name}` is not a unique function item in the registered target; subject evidence remains unresolved" + ), + }); + continue; + } + }, + None => None, + }; let start: TextSize = tokens[position].text_range().start(); let start_line = line_index.line(start); let end_line = line_index.line_for_range_end(TextSize::new(end_offset)); let body = slice_text(source, start, TextSize::new(end_offset)); - let calls = extract_call_facts(&body, start_line); - let literals = extract_literal_facts(&body, start_line); - let assertions = - parser_oracles_for_node_tokens(&tokens, matched.name_token_index, &line_index); + let (calls, literals, assertions) = match callback.as_ref() { + Some(function) => ( + function.calls.clone(), + function.literals.clone(), + extract_assertions(&function.body, function.start_line), + ), + None => ( + extract_call_facts(&body, start_line), + extract_literal_facts(&body, start_line), + parser_oracles_for_node_tokens(&tokens, matched.name_token_index, &line_index), + ), + }; let subject = HarnessSubjectFact { registration_id: registration.registration_id.clone(), harness_kind: registration.kind.as_str().to_string(), @@ -342,7 +383,9 @@ fn match_trial_path( // A bare `Trial` match is only a candidate at a path start; the // inner `Trial` of `other::Trial::test(` is a foreign path and // must not be adopted through an unrelated import binding. - if !qualified && !at_path_start(tokens, position, lone_colon_is_record_field) { + if (!qualified && !at_path_start(tokens, position, lone_colon_is_record_field)) + || (qualified && !qualified_path_starts_at_boundary(tokens, position)) + { continue; } let mut segments: Vec<&str> = if qualified { @@ -392,6 +435,32 @@ fn match_trial_path( None } +fn qualified_path_starts_at_boundary( + tokens: &[ra_ap_syntax::SyntaxToken], + position: usize, +) -> bool { + let Some(previous) = position.checked_sub(1).and_then(|index| tokens.get(index)) else { + return true; + }; + let prefix_end = if previous.kind() == ra_ap_syntax::SyntaxKind::COLON2 { + position.saturating_sub(2) + } else if previous.kind() == ra_ap_syntax::SyntaxKind::COLON + && tokens + .get(position.saturating_sub(2)) + .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::COLON) + { + position.saturating_sub(3) + } else { + return true; + }; + // Permit an explicitly rooted `::marker::Trial` path, but reject + // `other::marker::Trial`: the configured marker must own the complete + // qualified path rather than merely appear as a suffix. + tokens + .get(prefix_end) + .is_none_or(|token| token.kind() != ra_ap_syntax::SyntaxKind::IDENT) +} + struct TrialPathMatch { qualified: bool, name_token_index: usize, @@ -486,6 +555,38 @@ fn previous_significant_is_colon(tokens: &[ra_ap_syntax::SyntaxToken], from: usi ); } false +fn trial_callback_name( + tokens: &[ra_ap_syntax::SyntaxToken], + name_token_index: usize, +) -> Option { + let mut index = name_token_index + 1; + while let Some(token) = tokens.get(index) { + if token.kind() == ra_ap_syntax::SyntaxKind::COMMA { + return tokens + .get(index + 1) + .filter(|callback| callback.kind() == ra_ap_syntax::SyntaxKind::IDENT) + .map(|callback| callback.text().to_string()); + } + if token.kind() == ra_ap_syntax::SyntaxKind::R_PAREN { + return None; + } + index += 1; + } + None +} + +fn unique_callback_function(index: &RustIndex, target: &Path, name: &str) -> Option { + let mut matches = index + .files + .get(target)? + .functions + .iter() + .filter(|function| { + function.name == name && function.source_role == FunctionSourceRole::HarnessHelper + }) + .cloned(); + let function = matches.next()?; + matches.next().is_none().then_some(function) } /// Offset just past the `)` balancing the `(` at `open_paren_index`, @@ -529,6 +630,7 @@ fn parser_oracles_for_node_tokens( ra_ap_syntax::SyntaxKind::R_PAREN => depth = depth.saturating_sub(1), ra_ap_syntax::SyntaxKind::IDENT => { let name = token.text(); +<<<<<<< HEAD // Shared leaf predicate; the bang gate below restores // MacroCall semantics, and the leaf boundary keeps // `snapshot_helper!`-style names out of the oracle set. @@ -559,6 +661,41 @@ fn parser_oracles_for_node_tokens( }; if text.ends_with('(') { let mut macro_depth = 1; +======= + let next = tokens.get(index + 1); + let is_macro_invocation = is_assertion_macro_name(name) + && next.is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::BANG) + && tokens.get(index + 2).is_some_and(|token| { + matches!( + token.kind(), + ra_ap_syntax::SyntaxKind::L_PAREN + | ra_ap_syntax::SyntaxKind::L_CURLY + | ra_ap_syntax::SyntaxKind::L_BRACK + ) + }); + let is_fallible_call = matches!(name, "unwrap" | "expect") + && index >= 1 + && tokens[index - 1].kind() == ra_ap_syntax::SyntaxKind::DOT + && next.is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::L_PAREN); + if !is_macro_invocation && !is_fallible_call { + index += 1; + continue; + } + // assert!(..) / assert_eq!(..) — the bang and token tree + // follow; the assertion text is the macro invocation. + let mut text = if is_fallible_call { + format!(".{name}(") + } else { + name.to_string() + }; + let mut cursor = index + 1; + if is_macro_invocation + && tokens + .get(cursor) + .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::BANG) + { + text.push('!'); +>>>>>>> 195097cf2 (fix(analysis): harden registered harness evidence) cursor += 1; while cursor < tokens.len() && macro_depth > 0 { let inner = &tokens[cursor]; @@ -570,10 +707,18 @@ fn parser_oracles_for_node_tokens( text.push_str(inner.text()); cursor += 1; } + } else if is_fallible_call { + // The method name itself is sufficient for the shared + // classifier to establish a smoke oracle. Keep the + // argument body out of this small structural witness. } let classification = classify_assertion(&text); assertions.push(OracleFact { +<<<<<<< HEAD line: line_index.line(tokens[index].text_range().start()) + 1, +======= + line: line_index.line(token.text_range().start()), +>>>>>>> 195097cf2 (fix(analysis): harden registered harness evidence) kind: classification.kind, strength: classification.strength, observed_tokens: extract_identifier_tokens(&text), @@ -768,6 +913,12 @@ fn push_file_test(index: &mut RustIndex, target: &Path, test: TestFact) { } } +fn remove_file_test(index: &mut RustIndex, target: &Path, name: &str) { + if let Some(facts) = index.files.get_mut(target) { + facts.tests.retain(|test| test.name != name); + } +} + /// Demote every function in a registered `harness = false` target to the /// evidence-only helper role and drop the target's executable /// `TestFact`s. With `harness = false` the libtest harness never @@ -938,9 +1089,8 @@ enum TrialBindingResolution { fn resolve_trial_binding(bindings: &BTreeSet, marker: &str) -> TrialBindingResolution { let anchored_full = format!("{marker}::Trial"); - let matches_marker = |binding: &String| { - binding == &anchored_full || binding.ends_with(&format!("::{anchored_full}")) - }; + let matches_marker = + |binding: &String| binding == &anchored_full || binding == &format!("::{anchored_full}"); let anchored = bindings.iter().any(matches_marker); let conflicting = bindings .iter() diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs index 04c8f276a78..999c64c669e 100644 --- a/crates/ripr/src/analysis/facts/harness_registry/tests.rs +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -6,6 +6,7 @@ use super::*; use crate::analysis::facts::build_index_with_test_harnesses; +use std::collections::BTreeSet; use std::fs; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; @@ -311,7 +312,7 @@ fn trials() -> Vec { } #[test] -fn duplicate_trial_names_name_the_conflict_and_stay_one_subject() +fn duplicate_trial_names_name_the_conflict_and_remove_both_subjects() -> Result<(), Box> { let root = temp_dir("duplicate-trials")?; write_workspace( @@ -333,7 +334,7 @@ fn trials() -> Vec { let files = [PathBuf::from("tests/duplicates.rs")]; let registrations = [custom_target_registration("tests/duplicates.rs")]; let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; - assert_eq!(index.harness_subjects.len(), 1); + assert_eq!(index.harness_subjects.len(), 0); assert!( index .harness_limitations @@ -343,6 +344,42 @@ fn trials() -> Vec { "{:?}", index.harness_limitations ); + assert!( + index.tests.iter().all(|test| test.name != "same_name"), + "a duplicate subject must not leave an executable test fact" + ); + Ok(()) +} + +#[test] +fn production_like_target_precedence_survives_harness_registration() +-> Result<(), Box> { + let root = temp_dir("production-like-precedence")?; + write_workspace( + &root, + &[( + "tests/mimic.rs", + "use libtest_mimic::Trial;\nfn helper() -> i32 { 1 }\nTrial::test(\"one\", || Ok(()));\n", + )], + )?; + let target = PathBuf::from("tests/mimic.rs"); + let registrations = [custom_target_registration("tests/mimic.rs")]; + let mut production_like = BTreeSet::new(); + production_like.insert(target.clone()); + let index = + crate::analysis::facts::build_index_with_test_harnesses_and_production_like_targets( + &root.0, + &[target], + ®istrations, + &production_like, + )?; + let helper = index + .functions + .iter() + .find(|function| function.name == "helper") + .ok_or("missing helper")?; + assert_eq!(helper.source_role, FunctionSourceRole::Production); + assert!(index.harness_subjects.is_empty()); Ok(()) } @@ -353,7 +390,7 @@ fn fully_qualified_trial_calls_match_the_marker_path() -> Result<(), Box Vec {\n vec![libtest_mimic::Trial::test(\"qualified_case\", || Ok(()))]\n}\n", + "fn trials() -> Vec {\n vec![libtest_mimic::Trial::test(\"qualified_case\", || Ok(())), other::libtest_mimic::Trial::test(\"suffix_lookalike\", || Ok(()))]\n}\n", )], )?; let files = [PathBuf::from("tests/qualified.rs")]; @@ -640,6 +677,56 @@ fn trials() -> Vec { Ok(()) } +#[test] +fn trial_oracles_require_real_macros_and_preserve_source_lines() +-> Result<(), Box> { + let root = temp_dir("trial-oracles")?; + write_workspace( + &root, + &[( + "tests/oracles.rs", + "use libtest_mimic::Trial;\nfn trials() -> Vec {\n vec![Trial::test(\"oracle_case\", || {\n let snapshot_value = 1;\n let result = Some(snapshot_value).unwrap();\n assert_eq!(result, 1);\n result.expect(\"present\");\n Ok(())\n })]\n}\n", + )], + )?; + let index = build_index_with_test_harnesses( + &root.0, + &[PathBuf::from("tests/oracles.rs")], + &[custom_target_registration("tests/oracles.rs")], + )?; + let subject = index + .harness_subjects + .iter() + .find(|subject| subject.name == "oracle_case") + .ok_or("missing oracle subject")?; + assert_eq!(subject.assertions.len(), 3); + assert!( + subject + .assertions + .iter() + .any(|oracle| oracle.text == "unwrap" || oracle.text == ".unwrap(") + ); + assert!( + subject + .assertions + .iter() + .any(|oracle| oracle.text == ".expect(") + ); + assert!( + subject + .assertions + .iter() + .any(|oracle| oracle.text.starts_with("assert_eq!")) + ); + assert!( + subject + .assertions + .iter() + .map(|oracle| oracle.line) + .any(|line| line > subject.start_line) + ); + Ok(()) +} + #[test] fn registered_attribute_promotes_exact_matches_only() -> Result<(), Box> { let root = temp_dir("registered-attribute")?; diff --git a/crates/ripr/src/analysis/facts/mod.rs b/crates/ripr/src/analysis/facts/mod.rs index 3fd229059ce..a48f7877734 100644 --- a/crates/ripr/src/analysis/facts/mod.rs +++ b/crates/ripr/src/analysis/facts/mod.rs @@ -23,6 +23,20 @@ pub fn build_index_with_test_harnesses( root: &Path, files: &[PathBuf], registrations: &[TestHarnessRegistration], +) -> Result { + build_index_with_test_harnesses_and_production_like_targets( + root, + files, + registrations, + &std::collections::BTreeSet::new(), + ) +} + +pub fn build_index_with_test_harnesses_and_production_like_targets( + root: &Path, + files: &[PathBuf], + registrations: &[TestHarnessRegistration], + production_like_targets: &std::collections::BTreeSet, ) -> Result { let mut index = build::build_index(root, files)?; parameterized_tests::promote_explicit_test_case_functions(&mut index); @@ -33,10 +47,7 @@ pub fn build_index_with_test_harnesses( // evidence-only `CfgTestModule`, never the reverse. The workspace root // anchors crate-root identity for default module resolution. role_composition::compose_index_source_roles(&mut index, root); - // Explicit harness registrations are the most specific authority, so - // they run after composition and a composed generic grant can never - // overwrite a registered subject's role (#3532). - harness_registry::apply_registrations(&mut index, registrations); + harness_registry::apply_registrations(&mut index, registrations, production_like_targets); Ok(index) } @@ -44,15 +55,30 @@ pub(crate) fn build_index_from_loaded_files_with_cache_and_test_harnesses( root: &Path, files: &[(PathBuf, Vec)], registrations: &[TestHarnessRegistration], +) -> Result { + build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( + root, + files, + registrations, + &std::collections::BTreeSet::new(), + ) +} + +pub(crate) fn build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( + root: &Path, + files: &[(PathBuf, Vec)], + registrations: &[TestHarnessRegistration], + production_like_targets: &std::collections::BTreeSet, ) -> Result { let mut cached = build::build_index_from_loaded_files_with_cache(root, files)?; parameterized_tests::promote_explicit_test_case_functions(&mut cached.index); test_styles::normalize_index_test_styles(&mut cached.index); role_composition::compose_index_source_roles(&mut cached.index, root); - // Explicit harness registrations are the most specific authority, so - // they run after composition and a composed generic grant can never - // overwrite a registered subject's role (#3532). - harness_registry::apply_registrations(&mut cached.index, registrations); + harness_registry::apply_registrations( + &mut cached.index, + registrations, + production_like_targets, + ); Ok(cached) } diff --git a/crates/ripr/src/analysis/language/rust.rs b/crates/ripr/src/analysis/language/rust.rs index a67881bd0c7..dafd7d03627 100644 --- a/crates/ripr/src/analysis/language/rust.rs +++ b/crates/ripr/src/analysis/language/rust.rs @@ -1608,10 +1608,11 @@ impl RustAdapter { Ok((file.clone(), bytes)) }) .collect::, String>>()?; - let cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &options.root, &loaded_files, &options.test_harnesses, + &options.production_like_targets, )?; let mut index = cached.index; if let Some(disclosure) = rust_index::include_resolution_disclosure(&index) { @@ -1851,10 +1852,11 @@ impl RustAdapter { Ok((file.clone(), bytes)) }) .collect::, String>>()?; - let cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &options.root, &loaded_rust_files, &options.test_harnesses, + &options.production_like_targets, )?; let mut index = cached.index; if let Some(disclosure) = rust_index::lexical_fallback_disclosure(&index) { diff --git a/crates/ripr/src/analysis/rust_index.rs b/crates/ripr/src/analysis/rust_index.rs index 53335f4bd40..e6201cebc04 100644 --- a/crates/ripr/src/analysis/rust_index.rs +++ b/crates/ripr/src/analysis/rust_index.rs @@ -18,12 +18,17 @@ pub(crate) use super::extract::{ unwrap_err_bound_variables, }; use super::facts::ModulePathTarget; -pub(crate) use super::facts::build_index_from_loaded_files_with_cache_and_test_harnesses; +#[cfg(test)] +pub use super::facts::build_index_with_test_harnesses; #[cfg(test)] pub use super::facts::{CallFact, LiteralFact, ReturnFact}; pub use super::facts::{ FileFacts, FunctionFact, FunctionSummary, OracleFact, ProbeShapeFact, RustIndex, TestFact, - TestSummary, build_index, build_index_with_test_harnesses, + TestSummary, build_index, build_index_with_test_harnesses_and_production_like_targets, +}; +pub(crate) use super::facts::{ + build_index_from_loaded_files_with_cache_and_test_harnesses, + build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets, }; #[cfg(test)] use super::syntax::LexicalRustSyntaxAdapter; diff --git a/crates/ripr/src/analysis/seam_inventory.rs b/crates/ripr/src/analysis/seam_inventory.rs index 49674b45d53..9cba4432d25 100644 --- a/crates/ripr/src/analysis/seam_inventory.rs +++ b/crates/ripr/src/analysis/seam_inventory.rs @@ -86,10 +86,11 @@ pub(crate) fn inventory_seams_at_with_config( // Index the full set so `find_owner_function` can resolve owners // even when the seam appears in a file the production filter // includes but tests reference. - let index = rust_index::build_index_with_test_harnesses( + let index = rust_index::build_index_with_test_harnesses_and_production_like_targets( root, &rust_files, harness_registrations(config), + config.analysis().production_like_targets(), )?; Ok(inventory_seams_from_index(&production_files, &index)) } From b716147f04baec829c49254a19d36d3bd895d31e Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 03:06:33 -0400 Subject: [PATCH 16/33] fix(analysis): close remaining harness review gaps --- .../src/analysis/facts/harness_registry.rs | 11 +++- crates/ripr/src/analysis/facts/mod.rs | 1 + crates/ripr/src/analysis/rust_index.rs | 7 +-- crates/ripr/src/analysis/seam_inventory.rs | 21 ++++--- crates/ripr/src/config.rs | 57 +++++++++++++++++++ crates/ripr/src/config/tests.rs | 10 ++++ 6 files changed, 93 insertions(+), 14 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index dcf25af23ef..a5de95de36a 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -562,8 +562,17 @@ fn trial_callback_name( let mut index = name_token_index + 1; while let Some(token) = tokens.get(index) { if token.kind() == ra_ap_syntax::SyntaxKind::COMMA { + let mut callback_index = index + 1; + while tokens.get(callback_index).is_some_and(|callback| { + matches!( + callback.kind(), + ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT + ) + }) { + callback_index += 1; + } return tokens - .get(index + 1) + .get(callback_index) .filter(|callback| callback.kind() == ra_ap_syntax::SyntaxKind::IDENT) .map(|callback| callback.text().to_string()); } diff --git a/crates/ripr/src/analysis/facts/mod.rs b/crates/ripr/src/analysis/facts/mod.rs index a48f7877734..30ef7d12314 100644 --- a/crates/ripr/src/analysis/facts/mod.rs +++ b/crates/ripr/src/analysis/facts/mod.rs @@ -51,6 +51,7 @@ pub fn build_index_with_test_harnesses_and_production_like_targets( Ok(index) } +#[cfg(test)] pub(crate) fn build_index_from_loaded_files_with_cache_and_test_harnesses( root: &Path, files: &[(PathBuf, Vec)], diff --git a/crates/ripr/src/analysis/rust_index.rs b/crates/ripr/src/analysis/rust_index.rs index e6201cebc04..c7470525ff4 100644 --- a/crates/ripr/src/analysis/rust_index.rs +++ b/crates/ripr/src/analysis/rust_index.rs @@ -18,18 +18,13 @@ pub(crate) use super::extract::{ unwrap_err_bound_variables, }; use super::facts::ModulePathTarget; -#[cfg(test)] -pub use super::facts::build_index_with_test_harnesses; +pub(crate) use super::facts::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets; #[cfg(test)] pub use super::facts::{CallFact, LiteralFact, ReturnFact}; pub use super::facts::{ FileFacts, FunctionFact, FunctionSummary, OracleFact, ProbeShapeFact, RustIndex, TestFact, TestSummary, build_index, build_index_with_test_harnesses_and_production_like_targets, }; -pub(crate) use super::facts::{ - build_index_from_loaded_files_with_cache_and_test_harnesses, - build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets, -}; #[cfg(test)] use super::syntax::LexicalRustSyntaxAdapter; pub use super::syntax::{RaRustSyntaxAdapter, RustSyntaxAdapter, SyntaxNodeFact, TextRange}; diff --git a/crates/ripr/src/analysis/seam_inventory.rs b/crates/ripr/src/analysis/seam_inventory.rs index 9cba4432d25..216c58d3ea6 100644 --- a/crates/ripr/src/analysis/seam_inventory.rs +++ b/crates/ripr/src/analysis/seam_inventory.rs @@ -402,10 +402,11 @@ pub(crate) fn inventory_classified_seams_uncached_with_config( trace_latency_phase("filter_production_files", "ok", filter_started.elapsed()); let index_started = Instant::now(); - let mut index = match rust_index::build_index_with_test_harnesses( + let mut index = match rust_index::build_index_with_test_harnesses_and_production_like_targets( root, &rust_files, harness_registrations(config), + config.analysis().production_like_targets(), ) { Ok(index) => { trace_latency_phase("build_index", "ok", index_started.elapsed()); @@ -577,10 +578,11 @@ fn inventory_seam_grip_class_counts_uncached_with_config( .cloned() .collect(); - let mut index = rust_index::build_index_with_test_harnesses( + let mut index = rust_index::build_index_with_test_harnesses_and_production_like_targets( root, &rust_files, harness_registrations(config), + config.analysis().production_like_targets(), )?; rust_index::apply_oracle_policy(&mut index, config.oracles()); let seams = inventory_seams_from_index(&production_files, &index); @@ -609,10 +611,11 @@ fn inventory_compact_classified_seams_from_state_with_config( ), Duration::ZERO, ); - let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &state.workspace_root, &state.files, harness_registrations(config), + config.analysis().production_like_targets(), )?; cancellation::checkpoint()?; trace_latency_phase( @@ -655,10 +658,11 @@ fn inventory_classified_seams_from_state_with_config( ), Duration::ZERO, ); - let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &state.workspace_root, &state.files, harness_registrations(config), + config.analysis().production_like_targets(), )?; trace_latency_phase( "file_fact_cache", @@ -727,10 +731,11 @@ pub(crate) fn inventory_changed_test_classified_seams_at_with_config_node( let state = collect_workspace_state(root, config)?; let workspace_cache_key = state.cache_key(); let changed_test = normalized_inventory_path(changed_test); - let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &state.workspace_root, &state.files, harness_registrations(config), + config.analysis().production_like_targets(), )?; rust_index::apply_oracle_policy(&mut cached.index, config.oracles()); @@ -850,10 +855,11 @@ pub(crate) fn inventory_diff_scoped_classified_seams_at_with_config( ), Duration::ZERO, ); - let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &state.workspace_root, &state.files, harness_registrations(config), + config.analysis().production_like_targets(), )?; trace_latency_phase( "file_fact_cache", @@ -1085,10 +1091,11 @@ fn inventory_seam_grip_class_counts_from_state_with_config( ), Duration::ZERO, ); - let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses( + let mut cached = rust_index::build_index_from_loaded_files_with_cache_and_test_harnesses_and_production_like_targets( &state.workspace_root, &state.files, harness_registrations(config), + config.analysis().production_like_targets(), )?; trace_latency_phase( "file_fact_cache", diff --git a/crates/ripr/src/config.rs b/crates/ripr/src/config.rs index 6b1f8b1453c..b01ab6c5ebc 100644 --- a/crates/ripr/src/config.rs +++ b/crates/ripr/src/config.rs @@ -937,9 +937,66 @@ fn marker_path_is_exact(marker: &str) -> bool { let mut characters = segment.chars(); matches!(characters.next(), Some(first) if first.is_ascii_alphabetic() || first == '_') && characters.all(|rest| rest.is_ascii_alphanumeric() || rest == '_') + && !is_reserved_rust_identifier(segment) }) } +fn is_reserved_rust_identifier(identifier: &str) -> bool { + matches!( + identifier, + "as" | "break" + | "const" + | "continue" + | "crate" + | "else" + | "enum" + | "extern" + | "false" + | "fn" + | "for" + | "if" + | "impl" + | "in" + | "let" + | "loop" + | "match" + | "mod" + | "move" + | "mut" + | "pub" + | "ref" + | "return" + | "self" + | "Self" + | "static" + | "struct" + | "super" + | "trait" + | "true" + | "type" + | "unsafe" + | "use" + | "where" + | "while" + | "async" + | "await" + | "dyn" + | "abstract" + | "become" + | "box" + | "do" + | "final" + | "macro" + | "override" + | "priv" + | "typeof" + | "unsized" + | "virtual" + | "yield" + | "try" + ) +} + #[cfg(test)] mod tests; diff --git a/crates/ripr/src/config/tests.rs b/crates/ripr/src/config/tests.rs index ecfa5c5ddde..4b9cf082c00 100644 --- a/crates/ripr/src/config/tests.rs +++ b/crates/ripr/src/config/tests.rs @@ -1434,6 +1434,16 @@ fn parse_config_rejects_harness_root_escape_and_lookalike_marker() -> Result<(), marker_error.contains("exact identifier path"), "{marker_error}" ); + + for marker in ["fn", "myco::match"] { + let reserved_error = harness_parse_error(&format!( + "[[analysis.test_harnesses]]\nregistration_id = 'x'\ntarget = 'tests/a.rs'\nkind = 'registered_attribute'\nadapter = 'exact_attribute_v1'\nmarker = '{marker}'\n" + ))?; + assert!( + reserved_error.contains("exact identifier path"), + "{reserved_error}" + ); + } Ok(()) } From d5503a6362af9f12f33cd1e8ea2187e0957551f3 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 03:36:34 -0400 Subject: [PATCH 17/33] fix(analysis): preserve current path association guards --- .../src/analysis/classify/related_tests.rs | 6 ------ crates/ripr/src/analysis/rust_index.rs | 20 ++----------------- .../src/analysis/test_grip_evidence/tests.rs | 11 ---------- 3 files changed, 2 insertions(+), 35 deletions(-) diff --git a/crates/ripr/src/analysis/classify/related_tests.rs b/crates/ripr/src/analysis/classify/related_tests.rs index 75a09e3d58a..3b180aaa3f3 100644 --- a/crates/ripr/src/analysis/classify/related_tests.rs +++ b/crates/ripr/src/analysis/classify/related_tests.rs @@ -974,16 +974,10 @@ mod tests { fn given_non_utf8_stems_when_classify_extracts_then_lossy_collision_fails_closed() { use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; - // Two distinct non-UTF-8 leaf names share one lossy rendering; - // deriving stems through lossy conversion would fabricate - // file-name affinity between unrelated entities, so extraction - // must fail closed instead (#3599). let first = Path::new(OsStr::from_bytes(b"crates/app/src/pricing_\xff.rs")); let second = Path::new(OsStr::from_bytes(b"crates/app/src/pricing_\xfe.rs")); assert_eq!(normalized_file_stem(first), ""); assert_eq!(normalized_file_stem(second), ""); - // Valid-UTF-8 stems are unchanged, including dotfiles and - // `./`-prefixed forms that `normalize_path` trims. assert_eq!(normalized_file_stem(Path::new("src/config.rs")), "config"); assert_eq!(normalized_file_stem(Path::new("./src/config.rs")), "config"); } diff --git a/crates/ripr/src/analysis/rust_index.rs b/crates/ripr/src/analysis/rust_index.rs index c7470525ff4..c554f579a72 100644 --- a/crates/ripr/src/analysis/rust_index.rs +++ b/crates/ripr/src/analysis/rust_index.rs @@ -209,16 +209,6 @@ pub fn find_owner_function<'a>( .and_then(owner_in) } -/// `/`-separated display form of a path, independent of the host's -/// native separator. Used by [`is_test_file`] to judge the normalized -/// form; lossy text is safe here because replacement characters can -/// never become separators. The [`find_owner_function`] fallback does -/// NOT use this helper — identity attribution must not pass through -/// lossy conversion. -fn normalize_display(path: &Path) -> String { - path.to_string_lossy().replace('\\', "/") -} - pub fn changed_nodes_for_lines( index: &RustIndex, file: &Path, @@ -240,7 +230,7 @@ pub fn changed_nodes_for_lines( } pub(crate) fn is_test_file(path: &Path) -> bool { - let normalized = normalize_display(path); + let normalized = path.to_string_lossy().replace('\\', "/"); normalized == "tests" || normalized.starts_with("tests/") || normalized.contains("/tests/") } @@ -252,9 +242,7 @@ mod tests { fn find_owner_function_resolves_normalized_seam_paths() { let facts = summarize_file( PathBuf::from("src\\pricing.rs"), - "fn apply_discount(amount: i32, threshold: i32) -> i32 { \ - if amount >= threshold { amount - 10 } else { amount } }\n" - .to_string(), + "fn apply_discount(amount: i32, threshold: i32) -> i32 { amount }\n".to_string(), ); let mut index = RustIndex::default(); index.files.insert(PathBuf::from("src\\pricing.rs"), facts); @@ -271,7 +259,6 @@ mod tests { assert!(is_test_file(Path::new("tests/pricing_test.rs"))); assert!(is_test_file(Path::new("crates\\demo\\tests\\main.rs"))); assert!(!is_test_file(Path::new("src\\pricing.rs"))); - // A `tests`-prefixed sibling directory name stays production. assert!(!is_test_file(Path::new("testing\\pricing.rs"))); } @@ -289,9 +276,6 @@ mod tests { PathBuf::from(OsStr::from_bytes(b"src/pricing_\xff.rs")), facts, ); - // A query whose lossy rendering collides with the indexed key - // must not attribute the owner through lossy text: the fallback - // requires valid UTF-8 on both sides. let colliding = Path::new(OsStr::from_bytes(b"src\\pricing_\xfe.rs")); assert_eq!( find_owner_function(&index, colliding, 1).map(|f| f.name.as_str()), diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index b6fec350c8f..33c34eccc18 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -10260,17 +10260,6 @@ fn given_foreign_separator_paths_when_grip_associates_then_same_test_file_still_ .find(|s| s.kind() == SeamKind::PredicateBoundary) .ok_or_else(|| "predicate seam present".to_string())?; let evidence = evidence_for_seam(predicate, &index); - let context = CompactGripContext::new(&index); - let owner_fn = crate::analysis::rust_index::find_owner_function( - &index, - predicate.file(), - predicate.display_line(), - ); - let ctx_tests: Vec = context - .tests - .iter() - .map(|t| t.test.file.to_string_lossy().to_string()) - .collect(); assert!( evidence .related_tests From 21b9630c16760e817d9a21ff4c4cd9bf0c07727c Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 03:46:03 -0400 Subject: [PATCH 18/33] fix(analysis): retain rebased path guard context --- .../src/analysis/classify/related_tests.rs | 6 ++++++ crates/ripr/src/analysis/rust_index.rs | 20 +++++++++++++++++-- .../src/analysis/test_grip_evidence/tests.rs | 6 ++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/ripr/src/analysis/classify/related_tests.rs b/crates/ripr/src/analysis/classify/related_tests.rs index 3b180aaa3f3..75a09e3d58a 100644 --- a/crates/ripr/src/analysis/classify/related_tests.rs +++ b/crates/ripr/src/analysis/classify/related_tests.rs @@ -974,10 +974,16 @@ mod tests { fn given_non_utf8_stems_when_classify_extracts_then_lossy_collision_fails_closed() { use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; + // Two distinct non-UTF-8 leaf names share one lossy rendering; + // deriving stems through lossy conversion would fabricate + // file-name affinity between unrelated entities, so extraction + // must fail closed instead (#3599). let first = Path::new(OsStr::from_bytes(b"crates/app/src/pricing_\xff.rs")); let second = Path::new(OsStr::from_bytes(b"crates/app/src/pricing_\xfe.rs")); assert_eq!(normalized_file_stem(first), ""); assert_eq!(normalized_file_stem(second), ""); + // Valid-UTF-8 stems are unchanged, including dotfiles and + // `./`-prefixed forms that `normalize_path` trims. assert_eq!(normalized_file_stem(Path::new("src/config.rs")), "config"); assert_eq!(normalized_file_stem(Path::new("./src/config.rs")), "config"); } diff --git a/crates/ripr/src/analysis/rust_index.rs b/crates/ripr/src/analysis/rust_index.rs index c554f579a72..c7470525ff4 100644 --- a/crates/ripr/src/analysis/rust_index.rs +++ b/crates/ripr/src/analysis/rust_index.rs @@ -209,6 +209,16 @@ pub fn find_owner_function<'a>( .and_then(owner_in) } +/// `/`-separated display form of a path, independent of the host's +/// native separator. Used by [`is_test_file`] to judge the normalized +/// form; lossy text is safe here because replacement characters can +/// never become separators. The [`find_owner_function`] fallback does +/// NOT use this helper — identity attribution must not pass through +/// lossy conversion. +fn normalize_display(path: &Path) -> String { + path.to_string_lossy().replace('\\', "/") +} + pub fn changed_nodes_for_lines( index: &RustIndex, file: &Path, @@ -230,7 +240,7 @@ pub fn changed_nodes_for_lines( } pub(crate) fn is_test_file(path: &Path) -> bool { - let normalized = path.to_string_lossy().replace('\\', "/"); + let normalized = normalize_display(path); normalized == "tests" || normalized.starts_with("tests/") || normalized.contains("/tests/") } @@ -242,7 +252,9 @@ mod tests { fn find_owner_function_resolves_normalized_seam_paths() { let facts = summarize_file( PathBuf::from("src\\pricing.rs"), - "fn apply_discount(amount: i32, threshold: i32) -> i32 { amount }\n".to_string(), + "fn apply_discount(amount: i32, threshold: i32) -> i32 { \ + if amount >= threshold { amount - 10 } else { amount } }\n" + .to_string(), ); let mut index = RustIndex::default(); index.files.insert(PathBuf::from("src\\pricing.rs"), facts); @@ -259,6 +271,7 @@ mod tests { assert!(is_test_file(Path::new("tests/pricing_test.rs"))); assert!(is_test_file(Path::new("crates\\demo\\tests\\main.rs"))); assert!(!is_test_file(Path::new("src\\pricing.rs"))); + // A `tests`-prefixed sibling directory name stays production. assert!(!is_test_file(Path::new("testing\\pricing.rs"))); } @@ -276,6 +289,9 @@ mod tests { PathBuf::from(OsStr::from_bytes(b"src/pricing_\xff.rs")), facts, ); + // A query whose lossy rendering collides with the indexed key + // must not attribute the owner through lossy text: the fallback + // requires valid UTF-8 on both sides. let colliding = Path::new(OsStr::from_bytes(b"src\\pricing_\xfe.rs")); assert_eq!( find_owner_function(&index, colliding, 1).map(|f| f.name.as_str()), diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index 33c34eccc18..1b8e1b176f4 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -10260,6 +10260,12 @@ fn given_foreign_separator_paths_when_grip_associates_then_same_test_file_still_ .find(|s| s.kind() == SeamKind::PredicateBoundary) .ok_or_else(|| "predicate seam present".to_string())?; let evidence = evidence_for_seam(predicate, &index); + let context = CompactGripContext::new(&index); + let owner_fn = crate::analysis::rust_index::find_owner_function( + &index, + predicate.file(), + predicate.display_line(), + ); assert!( evidence .related_tests From 27936258076ad178ee2032dbba5b37d89c2719c2 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 03:52:55 -0400 Subject: [PATCH 19/33] test(analysis): restore path-association diagnostics --- crates/ripr/src/analysis/test_grip_evidence/tests.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index 1b8e1b176f4..b6fec350c8f 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -10266,6 +10266,11 @@ fn given_foreign_separator_paths_when_grip_associates_then_same_test_file_still_ predicate.file(), predicate.display_line(), ); + let ctx_tests: Vec = context + .tests + .iter() + .map(|t| t.test.file.to_string_lossy().to_string()) + .collect(); assert!( evidence .related_tests From ecf078e99cec15d2e6bfb17fe38903e29011514c Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 04:47:16 -0400 Subject: [PATCH 20/33] fix(analysis): preserve qualified harness callback evidence --- .../src/analysis/facts/harness_registry.rs | 361 +++++++----------- .../analysis/facts/harness_registry/tests.rs | 92 +++++ 2 files changed, 226 insertions(+), 227 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index a5de95de36a..cf2dc6729d2 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -162,20 +162,11 @@ fn apply_libtest_mimic_target( .filter_map(|element| element.into_token()) .collect(); let mut claimed_names = BTreeSet::new(); - // One invocation is one open paren. A qualified path - // (`marker::Trial::test(`) also contains a token-local bare `Trial` - // position; claiming the paren prevents the bare pass from - // re-processing the same call and emitting a false - // duplicate_subject/unanchored_trial_path limitation. - let mut claimed_invocations = BTreeSet::new(); for position in 0..tokens.len() { let Some(matched) = match_trial_path(&tokens, position, ®istration.marker) else { continue; }; - if !claimed_invocations.insert(matched.open_paren_index) { - continue; - } let line = line_index.line(tokens[position].text_range().start()); // Anchoring: the bare `Trial` form needs a top-level import bound // from exactly the marker path; the qualified form carries the @@ -212,11 +203,6 @@ fn apply_libtest_mimic_target( } } - // A `Trial::test` template inside a `macro_rules!` definition is - // not a concrete registration; only a real invocation is. - if inside_macro_rules(tokens[position].parent_ancestors()) { - continue; - } if in_loop(tokens[position].parent_ancestors()) { limitations.push(HarnessLimitationFact { registration_id: registration.registration_id.clone(), @@ -279,7 +265,7 @@ fn apply_libtest_mimic_target( "trial callback `{callback_name}` is not a unique function item in the registered target; subject evidence remains unresolved" ), }); - continue; + None } }, None => None, @@ -370,22 +356,8 @@ fn match_trial_path( } } - // A lone `:` predecessor only continues into a candidate when it is - // a record field (`trials: Trial::test(...)`) - either parsed as one, - // or shaped like one inside a macro's token tree (field name `ident` - // preceded by `{` or `,`). Macro input like `stringify!(trial: - // Trial::test(...))` is inert data and must not adopt the exception. - let lone_colon_is_record_field = tokens[position].parent_ancestors().any(|ancestor| { - ast::RecordExprField::can_cast(ancestor.kind()) - || ast::RecordExprFieldList::can_cast(ancestor.kind()) - }) || preceded_by_record_literal_shape(tokens, position); for qualified in [false, true] { - // A bare `Trial` match is only a candidate at a path start; the - // inner `Trial` of `other::Trial::test(` is a foreign path and - // must not be adopted through an unrelated import binding. - if (!qualified && !at_path_start(tokens, position, lone_colon_is_record_field)) - || (qualified && !qualified_path_starts_at_boundary(tokens, position)) - { + if qualified && !qualified_path_starts_at_boundary(tokens, position) { continue; } let mut segments: Vec<&str> = if qualified { @@ -411,23 +383,9 @@ fn match_trial_path( } } if matched_segments == segments.len() && l_paren(cursor) { - // The name literal need not be adjacent to the paren: - // `Trial::test( "name", …)` is legal, so skip trivia before - // reading the name token. - let mut name_token_index = cursor + 1; - while let Some(token) = tokens.get(name_token_index) { - if matches!( - token.kind(), - ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT - ) { - name_token_index += 1; - } else { - break; - } - } return Some(TrialPathMatch { qualified, - name_token_index, + name_token_index: cursor + 1, open_paren_index: cursor, }); } @@ -467,94 +425,6 @@ struct TrialPathMatch { open_paren_index: usize, } -/// Whether the token at `position` can begin a path: scanning back past -/// trivia, its predecessor must not be a path separator (`other_module -/// :: Trial` must not match at its inner `Trial` token). `::` may reach -/// the scanner as one COLON2 token or as two adjacent COLON tokens, so a -/// single COLON only continues a path when another colon precedes it; a -/// lone `:` is struct-field syntax and a field initializer like -/// `trials: Trial::test(...)` still starts a path. -fn at_path_start( - tokens: &[ra_ap_syntax::SyntaxToken], - position: usize, - lone_colon_is_record_field: bool, -) -> bool { - let mut cursor = position; - while cursor > 0 { - cursor -= 1; - if matches!( - tokens[cursor].kind(), - ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT - ) { - continue; - } - return match tokens[cursor].kind() { - ra_ap_syntax::SyntaxKind::COLON2 => false, - ra_ap_syntax::SyntaxKind::COLON => { - !previous_significant_is_colon(tokens, cursor) && lone_colon_is_record_field - } - _ => true, - }; - } - true -} - -/// Whether a lone-colon candidate at `position` carries the record -/// literal shape inside a macro token tree: `field_ident :` preceded by -/// `{` or `,` (`vec![Suite { trials: Trial::test(...) }]`). A macro -/// input label (`stringify!(trial: ...)`) is preceded by the opening -/// delimiter instead and stays excluded. -fn preceded_by_record_literal_shape(tokens: &[ra_ap_syntax::SyntaxToken], position: usize) -> bool { - let mut cursor = position; - let mut saw_colon = false; - let mut saw_field_ident = false; - while cursor > 0 { - cursor -= 1; - let token = &tokens[cursor]; - if matches!( - token.kind(), - ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT - ) { - continue; - } - if !saw_colon { - if token.kind() != ra_ap_syntax::SyntaxKind::COLON { - return false; - } - saw_colon = true; - continue; - } - if !saw_field_ident { - if token.kind() != ra_ap_syntax::SyntaxKind::IDENT { - return false; - } - saw_field_ident = true; - continue; - } - return matches!( - token.kind(), - ra_ap_syntax::SyntaxKind::L_CURLY | ra_ap_syntax::SyntaxKind::COMMA - ); - } - false -} - -fn previous_significant_is_colon(tokens: &[ra_ap_syntax::SyntaxToken], from: usize) -> bool { - let mut cursor = from; - while cursor > 0 { - cursor -= 1; - if matches!( - tokens[cursor].kind(), - ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT - ) { - continue; - } - return matches!( - tokens[cursor].kind(), - ra_ap_syntax::SyntaxKind::COLON | ra_ap_syntax::SyntaxKind::COLON2 - ); - } - false fn trial_callback_name( tokens: &[ra_ap_syntax::SyntaxToken], name_token_index: usize, @@ -571,10 +441,52 @@ fn trial_callback_name( }) { callback_index += 1; } - return tokens - .get(callback_index) - .filter(|callback| callback.kind() == ra_ap_syntax::SyntaxKind::IDENT) - .map(|callback| callback.text().to_string()); + let first = tokens.get(callback_index)?; + if first.kind() != ra_ap_syntax::SyntaxKind::IDENT { + return None; + } + let mut callback = first.text().to_string(); + callback_index += 1; + loop { + while tokens.get(callback_index).is_some_and(|token| { + matches!( + token.kind(), + ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT + ) + }) { + callback_index += 1; + } + let separator_width = match tokens.get(callback_index).map(|token| token.kind()) { + Some(ra_ap_syntax::SyntaxKind::COLON2) => Some(1), + Some(ra_ap_syntax::SyntaxKind::COLON) + if tokens.get(callback_index + 1).is_some_and(|token| { + token.kind() == ra_ap_syntax::SyntaxKind::COLON + }) => + { + Some(2) + } + _ => None, + }; + let Some(separator_width) = separator_width else { + break; + }; + callback_index += separator_width; + while tokens.get(callback_index).is_some_and(|token| { + matches!( + token.kind(), + ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT + ) + }) { + callback_index += 1; + } + let segment = tokens + .get(callback_index) + .filter(|token| token.kind() == ra_ap_syntax::SyntaxKind::IDENT)?; + callback.push_str("::"); + callback.push_str(segment.text()); + callback_index += 1; + } + return Some(callback); } if token.kind() == ra_ap_syntax::SyntaxKind::R_PAREN { return None; @@ -585,6 +497,10 @@ fn trial_callback_name( } fn unique_callback_function(index: &RustIndex, target: &Path, name: &str) -> Option { + let name = match name.rsplit("::").next() { + Some(name) => name, + None => name, + }; let mut matches = index .files .get(target)? @@ -622,8 +538,7 @@ fn balanced_call_end(tokens: &[ra_ap_syntax::SyntaxToken], open_paren_index: usi /// Assertion evidence for one trial subject: the exact assertion-macro and /// `unwrap`/`expect` tokens inside the registration's own argument span. /// Only tokens between the name argument and the balanced close count, so -/// adjacent code never credits this subject. Each oracle carries the real -/// source line of its invocation. +/// adjacent code never credits this subject. fn parser_oracles_for_node_tokens( tokens: &[ra_ap_syntax::SyntaxToken], name_token_index: usize, @@ -639,49 +554,35 @@ fn parser_oracles_for_node_tokens( ra_ap_syntax::SyntaxKind::R_PAREN => depth = depth.saturating_sub(1), ra_ap_syntax::SyntaxKind::IDENT => { let name = token.text(); -<<<<<<< HEAD - // Shared leaf predicate; the bang gate below restores - // MacroCall semantics, and the leaf boundary keeps - // `snapshot_helper!`-style names out of the oracle set. - if !crate::analysis::syntax::ra::is_assertion_macro_leaf(name) { - index += 1; - continue; - } - // Macro semantics: an assertion is an invocation, so a - // bang must follow the path segment (trivia allowed). A - // plain identifier that merely contains an assertion - // keyword (`let snapshots = …`) never classifies. - let bang_index = match next_significant(tokens, index + 1) { - Some(next) if tokens[next].kind() == ra_ap_syntax::SyntaxKind::BANG => next, - _ => { - index += 1; - continue; - } - }; - // assert!(..) / assert_eq!(..) — the token tree follows; - // the assertion text is the macro invocation. - let mut text = format!("{name}!"); - let mut cursor = match next_significant(tokens, bang_index + 1) { - Some(next) if tokens[next].kind() == ra_ap_syntax::SyntaxKind::L_PAREN => { - text.push('('); - next - } - _ => bang_index + 1, - }; - if text.ends_with('(') { - let mut macro_depth = 1; -======= let next = tokens.get(index + 1); - let is_macro_invocation = is_assertion_macro_name(name) + let macro_open_index = if is_assertion_macro_name(name) && next.is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::BANG) - && tokens.get(index + 2).is_some_and(|token| { + { + let mut open_index = index + 2; + while tokens.get(open_index).is_some_and(|token| { matches!( token.kind(), - ra_ap_syntax::SyntaxKind::L_PAREN - | ra_ap_syntax::SyntaxKind::L_CURLY - | ra_ap_syntax::SyntaxKind::L_BRACK + ra_ap_syntax::SyntaxKind::WHITESPACE + | ra_ap_syntax::SyntaxKind::COMMENT ) - }); + }) { + open_index += 1; + } + tokens + .get(open_index) + .is_some_and(|token| { + matches!( + token.kind(), + ra_ap_syntax::SyntaxKind::L_PAREN + | ra_ap_syntax::SyntaxKind::L_CURLY + | ra_ap_syntax::SyntaxKind::L_BRACK + ) + }) + .then_some(open_index) + } else { + None + }; + let is_macro_invocation = macro_open_index.is_some(); let is_fallible_call = matches!(name, "unwrap" | "expect") && index >= 1 && tokens[index - 1].kind() == ra_ap_syntax::SyntaxKind::DOT @@ -704,17 +605,11 @@ fn parser_oracles_for_node_tokens( .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::BANG) { text.push('!'); ->>>>>>> 195097cf2 (fix(analysis): harden registered harness evidence) - cursor += 1; - while cursor < tokens.len() && macro_depth > 0 { - let inner = &tokens[cursor]; - match inner.kind() { - ra_ap_syntax::SyntaxKind::L_PAREN => macro_depth += 1, - ra_ap_syntax::SyntaxKind::R_PAREN => macro_depth -= 1, - _ => {} - } - text.push_str(inner.text()); - cursor += 1; + if let Some(open_index) = macro_open_index { + cursor = open_index; + } + if let Some(tree_text) = macro_token_tree_text(tokens, cursor) { + text.push_str(&tree_text); } } else if is_fallible_call { // The method name itself is sufficient for the shared @@ -723,20 +618,12 @@ fn parser_oracles_for_node_tokens( } let classification = classify_assertion(&text); assertions.push(OracleFact { -<<<<<<< HEAD - line: line_index.line(tokens[index].text_range().start()) + 1, -======= line: line_index.line(token.text_range().start()), ->>>>>>> 195097cf2 (fix(analysis): harden registered harness evidence) kind: classification.kind, strength: classification.strength, observed_tokens: extract_identifier_tokens(&text), text, }); - // The macro body has been consumed; resuming inside it - // would rescan nested idents as separate top-level - // oracles. - index = cursor.saturating_sub(1); } _ => {} } @@ -746,16 +633,49 @@ fn parser_oracles_for_node_tokens( assertions } -/// Index of the next non-trivia token at or after `from`. -fn next_significant(tokens: &[ra_ap_syntax::SyntaxToken], from: usize) -> Option { - (from..tokens.len()).find(|index| { - !matches!( - tokens[*index].kind(), - ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT - ) - }) +fn macro_token_tree_text( + tokens: &[ra_ap_syntax::SyntaxToken], + open_index: usize, +) -> Option { + let mut delimiters = Vec::new(); + let mut text = String::new(); + for token in tokens.iter().skip(open_index) { + let kind = token.kind(); + match kind { + ra_ap_syntax::SyntaxKind::L_PAREN + | ra_ap_syntax::SyntaxKind::L_CURLY + | ra_ap_syntax::SyntaxKind::L_BRACK => delimiters.push(kind), + ra_ap_syntax::SyntaxKind::R_PAREN + | ra_ap_syntax::SyntaxKind::R_CURLY + | ra_ap_syntax::SyntaxKind::R_BRACK => { + let opening = delimiters.pop()?; + let expected = match opening { + ra_ap_syntax::SyntaxKind::L_PAREN => ra_ap_syntax::SyntaxKind::R_PAREN, + ra_ap_syntax::SyntaxKind::L_CURLY => ra_ap_syntax::SyntaxKind::R_CURLY, + ra_ap_syntax::SyntaxKind::L_BRACK => ra_ap_syntax::SyntaxKind::R_BRACK, + _ => return None, + }; + if kind != expected { + return None; + } + } + _ => {} + } + text.push_str(token.text()); + if delimiters.is_empty() { + return Some(text); + } + } + None } +fn is_assertion_macro_name(name: &str) -> bool { + matches!( + name, + "assert" | "assert_eq" | "assert_ne" | "assert_matches" | "matches" + ) || name.starts_with("insta::assert") + || name.contains("snapshot") +} /// Exact registered test-producing attribute adapter, generation 1 /// (#3532). Promotes functions carrying the exact registered attribute /// path through the shared #3531 role authority. The attribute must @@ -771,20 +691,18 @@ fn apply_registered_attribute( ) { let target = registration.target.clone(); let parse = SourceFile::parse(source, Edition::CURRENT); - if !parse.errors().is_empty() { - // Fail closed: subject promotion over an unparseable target is - // unsound, so nothing beyond the typed limitation is established. + let use_bindings = if parse.errors().is_empty() { + top_level_use_bindings(parse.tree().syntax(), marker_leaf(®istration.marker)) + } else { limitations.push(HarnessLimitationFact { registration_id: registration.registration_id.clone(), code: "parse_unavailable".to_string(), - file: target, + file: target.clone(), line: 1, detail: "the registered attribute target did not parse; no registered subjects were established (fail closed)".to_string(), }); - return; - } - let use_bindings = - top_level_use_bindings(parse.tree().syntax(), marker_leaf(®istration.marker)); + BTreeSet::new() + }; let promoted_functions: Vec<(usize, String, TestFact, HarnessSubjectFact)> = { let Some(facts) = index.files.get(&target) else { return; @@ -979,21 +897,16 @@ fn resolve_registered_attribute( marker: &str, use_bindings: &BTreeSet, ) -> Option { - // Exact full-path spellings win regardless of attribute order: an - // earlier bare spelling must not mask a later exact `#[]`. - for attribute in attrs { - if normalized_attribute_path(attribute).as_deref() == Some(marker) { - return Some(RegisteredAttributeResolution::Matched); - } - } - let (_prefix, name) = marker.rsplit_once("::")?; for attribute in attrs { let Some(path) = normalized_attribute_path(attribute) else { continue; }; if path == marker { - continue; + return Some(RegisteredAttributeResolution::Matched); } + let Some((_prefix, name)) = marker.rsplit_once("::") else { + continue; + }; if path != name { continue; } @@ -1122,12 +1035,6 @@ fn resolve_trial_binding(bindings: &BTreeSet, marker: &str) -> TrialBind /// Whether the ancestor chain of a token sits inside a loop expression — /// the bounded signal for runtime-only trial discovery. Works through /// macro token trees too, because tokens keep their ancestor nodes. -/// Whether the token sits inside a `macro_rules!` definition body: the -/// tokens there are a template, not an executed registration. -fn inside_macro_rules(mut ancestors: impl Iterator) -> bool { - ancestors.any(|ancestor| ast::MacroRules::can_cast(ancestor.kind())) -} - fn in_loop(mut ancestors: impl Iterator) -> bool { ancestors.any(|ancestor| { ast::WhileExpr::can_cast(ancestor.kind()) diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs index 999c64c669e..addb4a9b046 100644 --- a/crates/ripr/src/analysis/facts/harness_registry/tests.rs +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -6,6 +6,7 @@ use super::*; use crate::analysis::facts::build_index_with_test_harnesses; +use crate::domain::OracleKind; use std::collections::BTreeSet; use std::fs; use std::path::PathBuf; @@ -727,6 +728,97 @@ fn trial_oracles_require_real_macros_and_preserve_source_lines() Ok(()) } +#[test] +fn qualified_trial_callbacks_keep_subjects_and_resolve_terminal_function_names() +-> Result<(), Box> { + let root = temp_dir("qualified-callbacks")?; + write_workspace( + &root, + &[( + "tests/callbacks.rs", + r#" +use libtest_mimic::Trial; +fn check() { + assert_eq!(1, 1); +} +fn trials() -> Vec { + vec![ + Trial::test("resolved_callback", callbacks::check), + Trial::test("unresolved_callback", missing::callback), + ] +} +"#, + )], + )?; + let index = build_index_with_test_harnesses( + &root.0, + &[PathBuf::from("tests/callbacks.rs")], + &[custom_target_registration("tests/callbacks.rs")], + )?; + assert_eq!(index.harness_subjects.len(), 2); + let resolved = index + .harness_subjects + .iter() + .find(|subject| subject.name == "resolved_callback") + .ok_or("missing resolved callback subject")?; + assert!( + resolved + .assertions + .iter() + .any(|oracle| oracle.text.starts_with("assert_eq!")) + ); + assert!(index.harness_limitations.iter().any(|limitation| { + limitation.code == "unresolved_trial_callback" + && limitation.detail.contains("missing::callback") + })); + Ok(()) +} + +#[test] +fn trial_oracles_preserve_brace_and_bracket_macro_delimiters() +-> Result<(), Box> { + let root = temp_dir("delimited-oracles")?; + write_workspace( + &root, + &[( + "tests/delimiters.rs", + r#" +use libtest_mimic::Trial; +fn trials() -> Vec { + vec![Trial::test("delimiters", || { + let result = 1; + assert_eq! { result, 1 }; + assert_eq! [result, 1]; + Ok(()) + })] +} +"#, + )], + )?; + let index = build_index_with_test_harnesses( + &root.0, + &[PathBuf::from("tests/delimiters.rs")], + &[custom_target_registration("tests/delimiters.rs")], + )?; + let subject = index + .harness_subjects + .iter() + .find(|subject| subject.name == "delimiters") + .ok_or("missing delimiter subject")?; + assert_eq!(subject.assertions.len(), 2); + assert!(subject.assertions.iter().any(|oracle| { + oracle.kind == OracleKind::ExactValue + && oracle.text.contains("{") + && oracle.text.contains("}") + })); + assert!(subject.assertions.iter().any(|oracle| { + oracle.kind == OracleKind::ExactValue + && oracle.text.contains("[") + && oracle.text.contains("]") + })); + Ok(()) +} + #[test] fn registered_attribute_promotes_exact_matches_only() -> Result<(), Box> { let root = temp_dir("registered-attribute")?; From e7c48d6110a60d128736b44c6673616fbb8a9927 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 05:03:12 -0400 Subject: [PATCH 21/33] test(analysis): cover delimited harness assertions --- crates/ripr/src/analysis/facts/harness_registry/tests.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs index addb4a9b046..6b6810c164d 100644 --- a/crates/ripr/src/analysis/facts/harness_registry/tests.rs +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -787,8 +787,8 @@ use libtest_mimic::Trial; fn trials() -> Vec { vec![Trial::test("delimiters", || { let result = 1; - assert_eq! { result, 1 }; - assert_eq! [result, 1]; + assert_eq! { result, Config { field: 1 } }; + assert_eq! [result, Config { field: 1 }]; Ok(()) })] } @@ -807,12 +807,12 @@ fn trials() -> Vec { .ok_or("missing delimiter subject")?; assert_eq!(subject.assertions.len(), 2); assert!(subject.assertions.iter().any(|oracle| { - oracle.kind == OracleKind::ExactValue + oracle.kind == OracleKind::WholeObjectEquality && oracle.text.contains("{") && oracle.text.contains("}") })); assert!(subject.assertions.iter().any(|oracle| { - oracle.kind == OracleKind::ExactValue + oracle.kind == OracleKind::WholeObjectEquality && oracle.text.contains("[") && oracle.text.contains("]") })); From 1703d79c569512175cfc02788556bfe8efa2502e Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 05:20:25 -0400 Subject: [PATCH 22/33] fix(analysis): restore harness path and oracle boundaries --- .../src/analysis/facts/harness_registry.rs | 41 +++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index cf2dc6729d2..628568cfd2f 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -357,7 +357,9 @@ fn match_trial_path( } for qualified in [false, true] { - if qualified && !qualified_path_starts_at_boundary(tokens, position) { + if (!qualified && !bare_path_starts_at_boundary(tokens, position)) + || (qualified && !qualified_path_starts_at_boundary(tokens, position)) + { continue; } let mut segments: Vec<&str> = if qualified { @@ -393,6 +395,40 @@ fn match_trial_path( None } +fn bare_path_starts_at_boundary(tokens: &[ra_ap_syntax::SyntaxToken], position: usize) -> bool { + let mut cursor = position; + while cursor > 0 { + cursor -= 1; + if matches!( + tokens[cursor].kind(), + ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT + ) { + continue; + } + return match tokens[cursor].kind() { + ra_ap_syntax::SyntaxKind::COLON2 => false, + ra_ap_syntax::SyntaxKind::COLON => { + // A single colon can be a record-field initializer; a + // doubled colon is always a qualified path separator. + let mut previous = cursor; + while previous > 0 { + previous -= 1; + if matches!( + tokens[previous].kind(), + ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT + ) { + continue; + } + return tokens[previous].kind() != ra_ap_syntax::SyntaxKind::COLON; + } + true + } + _ => true, + }; + } + true +} + fn qualified_path_starts_at_boundary( tokens: &[ra_ap_syntax::SyntaxToken], position: usize, @@ -673,8 +709,7 @@ fn is_assertion_macro_name(name: &str) -> bool { matches!( name, "assert" | "assert_eq" | "assert_ne" | "assert_matches" | "matches" - ) || name.starts_with("insta::assert") - || name.contains("snapshot") + ) || name == "assert_snapshot" } /// Exact registered test-producing attribute adapter, generation 1 /// (#3532). Promotes functions carrying the exact registered attribute From 406d6ad2a47bca15b61ec382430df73b7bbe29fe Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 05:20:32 -0400 Subject: [PATCH 23/33] fix(analysis): remove duplicate harness exports --- crates/ripr/src/analysis/facts/mod.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/ripr/src/analysis/facts/mod.rs b/crates/ripr/src/analysis/facts/mod.rs index 30ef7d12314..6df24896f60 100644 --- a/crates/ripr/src/analysis/facts/mod.rs +++ b/crates/ripr/src/analysis/facts/mod.rs @@ -103,8 +103,6 @@ pub use model::{ ModuleDeclarationFact, ModulePathTarget, OracleFact, ProbeShapeFact, ResolvedIncludeParent, ReturnFact, RustIncludeLimitation, RustIndex, SourceRoleProvenance, SourceRoleProvenanceEdge, SourceRoleProvenanceEdgeKind, TestFact, TestSummary, - HarnessLimitationFact, - HarnessSelectorCapability, HarnessSubjectClaim, HarnessSubjectFact, }; #[cfg(test)] pub(crate) use model::{WorkspaceFileAuthority, WorkspaceRootAuthority}; From 83670977207d6734e7706ab39a08182484a1d194 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 05:27:20 -0400 Subject: [PATCH 24/33] fix(analysis): satisfy harness lint gates --- crates/ripr/src/analysis/facts/harness_registry.rs | 5 +---- crates/ripr/src/analysis/facts/mod.rs | 12 ------------ 2 files changed, 1 insertion(+), 16 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index 628568cfd2f..d71171ad4cf 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -706,10 +706,7 @@ fn macro_token_tree_text( } fn is_assertion_macro_name(name: &str) -> bool { - matches!( - name, - "assert" | "assert_eq" | "assert_ne" | "assert_matches" | "matches" - ) || name == "assert_snapshot" + crate::analysis::syntax::ra::is_assertion_macro_leaf(name) } /// Exact registered test-producing attribute adapter, generation 1 /// (#3532). Promotes functions carrying the exact registered attribute diff --git a/crates/ripr/src/analysis/facts/mod.rs b/crates/ripr/src/analysis/facts/mod.rs index 6df24896f60..9dc893ec913 100644 --- a/crates/ripr/src/analysis/facts/mod.rs +++ b/crates/ripr/src/analysis/facts/mod.rs @@ -83,18 +83,6 @@ pub(crate) fn build_index_from_loaded_files_with_cache_and_test_harnesses_and_pr Ok(cached) } -/// Test-only compatibility facade for the cache path without harness -/// registrations. Keep the same post-parse normalization and contextual -/// role composition as the production index builder; callers that need the -/// registry use the explicit sibling above. -#[cfg(test)] -pub(crate) fn build_index_from_loaded_files_with_cache( - root: &Path, - files: &[(PathBuf, Vec)], -) -> Result { - build_index_from_loaded_files_with_cache_and_test_harnesses(root, files, &[]) -} - // Keep compilation-unit rebasing available at the facts facade for index consumers. pub(crate) use includes::compilation_unit_path_from_parents; pub use model::{ From 94bf5442e401548b5876dd228f0bfb5f29e7e1dc Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 05:32:48 -0400 Subject: [PATCH 25/33] fix(analysis): exclude dormant harness templates --- crates/ripr/src/analysis/facts/harness_registry.rs | 7 +++++++ crates/ripr/src/analysis/facts/harness_registry/tests.rs | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index d71171ad4cf..dfffa0429e9 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -213,6 +213,9 @@ fn apply_libtest_mimic_target( }); continue; } + if in_macro_definition(tokens[position].parent_ancestors()) { + continue; + } let Some(name_token) = tokens.get(matched.name_token_index) else { continue; }; @@ -1075,6 +1078,10 @@ fn in_loop(mut ancestors: impl Iterator) -> boo }) } +fn in_macro_definition(mut ancestors: impl Iterator) -> bool { + ancestors.any(|ancestor| ast::MacroRules::can_cast(ancestor.kind())) +} + /// Exact simple string-literal text of one token. Escaped spellings, /// raw strings, and empty names are not demonstrated by this bounded parser and /// stay unresolved (fail closed). diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs index 6b6810c164d..796e68d6abb 100644 --- a/crates/ripr/src/analysis/facts/harness_registry/tests.rs +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -653,8 +653,8 @@ fn dormant_macro_templates_never_become_subjects() -> Result<(), Box { - libtest_mimic::Trial::test($name, || Ok(())) + () => { + libtest_mimic::Trial::test(\"dormant_case\", || Ok(())) }; } From 3629060eaecac3ce985d99cf9cab9724b3540d08 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 05:48:58 -0400 Subject: [PATCH 26/33] fix(analysis): harden harness registration boundaries --- .../src/analysis/facts/harness_registry.rs | 99 +++++++++++-------- 1 file changed, 59 insertions(+), 40 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index dfffa0429e9..89224422b15 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -33,7 +33,6 @@ use super::test_styles::normalized_test_attribute_path as normalized_attribute_p use super::{ HarnessLimitationFact, HarnessSelectorCapability, HarnessSubjectClaim, HarnessSubjectFact, }; -use crate::analysis::extract::extract_assertions; use crate::analysis::rust_index::{ OracleFact, classify_assertion, extract_call_facts, extract_identifier_tokens, extract_literal_facts, @@ -216,7 +215,8 @@ fn apply_libtest_mimic_target( if in_macro_definition(tokens[position].parent_ancestors()) { continue; } - let Some(name_token) = tokens.get(matched.name_token_index) else { + let name_token_index = next_significant(&tokens, matched.name_token_index); + let Some(name_token) = name_token_index.and_then(|index| tokens.get(index)) else { continue; }; let Some(name) = string_literal_token_text(name_token) else { @@ -281,7 +281,15 @@ fn apply_libtest_mimic_target( Some(function) => ( function.calls.clone(), function.literals.clone(), - extract_assertions(&function.body, function.start_line), + parser_oracles_for_function(&function.body, function.start_line).unwrap_or_else( + || { + parser_oracles_for_node_tokens( + &tokens, + name_token_index.unwrap_or(matched.name_token_index), + &line_index, + ) + }, + ), ), None => ( extract_call_facts(&body, start_line), @@ -436,26 +444,44 @@ fn qualified_path_starts_at_boundary( tokens: &[ra_ap_syntax::SyntaxToken], position: usize, ) -> bool { - let Some(previous) = position.checked_sub(1).and_then(|index| tokens.get(index)) else { + let Some(previous_index) = previous_significant(tokens, position) else { return true; }; - let prefix_end = if previous.kind() == ra_ap_syntax::SyntaxKind::COLON2 { - position.saturating_sub(2) + let previous = &tokens[previous_index]; + let separator_start = if previous.kind() == ra_ap_syntax::SyntaxKind::COLON2 { + previous_index } else if previous.kind() == ra_ap_syntax::SyntaxKind::COLON && tokens - .get(position.saturating_sub(2)) + .get(previous_index.saturating_sub(1)) .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::COLON) { - position.saturating_sub(3) + previous_index.saturating_sub(1) } else { return true; }; // Permit an explicitly rooted `::marker::Trial` path, but reject // `other::marker::Trial`: the configured marker must own the complete // qualified path rather than merely appear as a suffix. - tokens - .get(prefix_end) - .is_none_or(|token| token.kind() != ra_ap_syntax::SyntaxKind::IDENT) + previous_significant(tokens, separator_start) + .is_none_or(|index| tokens[index].kind() != ra_ap_syntax::SyntaxKind::IDENT) +} + +fn previous_significant(tokens: &[ra_ap_syntax::SyntaxToken], before: usize) -> Option { + (0..before).rev().find(|index| { + !matches!( + tokens[*index].kind(), + ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT + ) + }) +} + +fn next_significant(tokens: &[ra_ap_syntax::SyntaxToken], from: usize) -> Option { + (from..tokens.len()).find(|index| { + !matches!( + tokens[*index].kind(), + ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT + ) + }) } struct TrialPathMatch { @@ -593,31 +619,26 @@ fn parser_oracles_for_node_tokens( ra_ap_syntax::SyntaxKind::R_PAREN => depth = depth.saturating_sub(1), ra_ap_syntax::SyntaxKind::IDENT => { let name = token.text(); - let next = tokens.get(index + 1); + let bang_index = next_significant(tokens, index + 1); let macro_open_index = if is_assertion_macro_name(name) - && next.is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::BANG) + && bang_index + .and_then(|index| tokens.get(index)) + .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::BANG) { - let mut open_index = index + 2; - while tokens.get(open_index).is_some_and(|token| { - matches!( - token.kind(), - ra_ap_syntax::SyntaxKind::WHITESPACE - | ra_ap_syntax::SyntaxKind::COMMENT - ) - }) { - open_index += 1; - } - tokens - .get(open_index) - .is_some_and(|token| { - matches!( - token.kind(), - ra_ap_syntax::SyntaxKind::L_PAREN - | ra_ap_syntax::SyntaxKind::L_CURLY - | ra_ap_syntax::SyntaxKind::L_BRACK - ) - }) - .then_some(open_index) + bang_index.and_then(|bang_index| { + let open_index = next_significant(tokens, bang_index + 1)?; + tokens + .get(open_index) + .is_some_and(|token| { + matches!( + token.kind(), + ra_ap_syntax::SyntaxKind::L_PAREN + | ra_ap_syntax::SyntaxKind::L_CURLY + | ra_ap_syntax::SyntaxKind::L_BRACK + ) + }) + .then_some(open_index) + }) } else { None }; @@ -625,7 +646,9 @@ fn parser_oracles_for_node_tokens( let is_fallible_call = matches!(name, "unwrap" | "expect") && index >= 1 && tokens[index - 1].kind() == ra_ap_syntax::SyntaxKind::DOT - && next.is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::L_PAREN); + && next_significant(tokens, index + 1) + .and_then(|index| tokens.get(index)) + .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::L_PAREN); if !is_macro_invocation && !is_fallible_call { index += 1; continue; @@ -638,11 +661,7 @@ fn parser_oracles_for_node_tokens( name.to_string() }; let mut cursor = index + 1; - if is_macro_invocation - && tokens - .get(cursor) - .is_some_and(|token| token.kind() == ra_ap_syntax::SyntaxKind::BANG) - { + if is_macro_invocation { text.push('!'); if let Some(open_index) = macro_open_index { cursor = open_index; From 9b0585fb3225773c39fae1a41ec5769484f4e1c8 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 05:57:44 -0400 Subject: [PATCH 27/33] fix(analysis): tighten harness oracle boundaries --- crates/ripr/src/analysis/facts/harness_registry.rs | 9 ++++++--- crates/ripr/src/analysis/facts/harness_registry/tests.rs | 1 + crates/ripr/src/analysis/syntax/ra.rs | 8 ++++---- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index 89224422b15..71d57d2633e 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -166,6 +166,12 @@ fn apply_libtest_mimic_target( let Some(matched) = match_trial_path(&tokens, position, ®istration.marker) else { continue; }; + // Macro definitions are templates, not executable registrations. Do + // this before path/import/loop diagnostics so dormant templates do + // not emit limitations either. + if in_macro_definition(tokens[position].parent_ancestors()) { + continue; + } let line = line_index.line(tokens[position].text_range().start()); // Anchoring: the bare `Trial` form needs a top-level import bound // from exactly the marker path; the qualified form carries the @@ -212,9 +218,6 @@ fn apply_libtest_mimic_target( }); continue; } - if in_macro_definition(tokens[position].parent_ancestors()) { - continue; - } let name_token_index = next_significant(&tokens, matched.name_token_index); let Some(name_token) = name_token_index.and_then(|index| tokens.get(index)) else { continue; diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs index 796e68d6abb..7a0fa065014 100644 --- a/crates/ripr/src/analysis/facts/harness_registry/tests.rs +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -489,6 +489,7 @@ fn snapshot_named_helpers_never_become_oracles_but_snapshot_asserts_do() "fn trials() -> Vec { vec![libtest_mimic::Trial::test(\"leaf_case\", || { snapshot_helper!(); + other_snapshot!(); assert_snapshot!(1); Ok(()) })] diff --git a/crates/ripr/src/analysis/syntax/ra.rs b/crates/ripr/src/analysis/syntax/ra.rs index d22f819dfee..c9a3690c2c1 100644 --- a/crates/ripr/src/analysis/syntax/ra.rs +++ b/crates/ripr/src/analysis/syntax/ra.rs @@ -1064,15 +1064,15 @@ fn extract_parser_oracles( /// Token-local leaf form of [`is_assertion_macro`] for scanners that see /// one path segment at a time: the exact built-in assertion names plus the -/// supported snapshot-macro naming boundary (`*_snapshot`). The +/// supported assertion-snapshot naming boundary (`assert*_snapshot`). The /// source-side `contains("snapshot")` rule is deliberately NOT carried -/// over — a leaf ident like `snapshot_helper` must not classify, while -/// `assert_snapshot` / `assert_json_snapshot` do. +/// over — a leaf ident like `snapshot_helper` or `other_snapshot` must not +/// classify, while `assert_snapshot` / `assert_json_snapshot` do. pub(crate) fn is_assertion_macro_leaf(name: &str) -> bool { matches!( name, "assert" | "assert_eq" | "assert_ne" | "assert_matches" | "matches" - ) || name.ends_with("snapshot") + ) || (name.starts_with("assert") && name.ends_with("snapshot")) } pub(crate) fn is_assertion_macro(macro_name: &str) -> bool { From 94fa00dd48400192c595384ab3e710daa31ee0cf Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 06:33:42 -0400 Subject: [PATCH 28/33] fix(analysis): tighten harness and snapshot boundaries --- .../src/analysis/facts/harness_registry.rs | 58 +++++++++++++++++++ .../analysis/facts/harness_registry/tests.rs | 5 +- crates/ripr/src/analysis/syntax/ra.rs | 2 +- 3 files changed, 63 insertions(+), 2 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index 71d57d2633e..bb384b2d954 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -371,6 +371,9 @@ fn match_trial_path( } for qualified in [false, true] { + if is_data_only_macro_input(tokens, position) { + continue; + } if (!qualified && !bare_path_starts_at_boundary(tokens, position)) || (qualified && !qualified_path_starts_at_boundary(tokens, position)) { @@ -409,6 +412,61 @@ fn match_trial_path( None } +fn is_data_only_macro_input(tokens: &[ra_ap_syntax::SyntaxToken], position: usize) -> bool { + let mut depth = 0usize; + let mut cursor = position; + while cursor > 0 { + cursor -= 1; + let kind = tokens[cursor].kind(); + if matches!( + kind, + ra_ap_syntax::SyntaxKind::R_PAREN + | ra_ap_syntax::SyntaxKind::R_BRACK + | ra_ap_syntax::SyntaxKind::R_CURLY + ) { + depth += 1; + continue; + } + if matches!( + kind, + ra_ap_syntax::SyntaxKind::L_PAREN + | ra_ap_syntax::SyntaxKind::L_BRACK + | ra_ap_syntax::SyntaxKind::L_CURLY + ) { + if depth == 0 { + return false; + } + depth -= 1; + continue; + } + if depth == 0 && kind == ra_ap_syntax::SyntaxKind::BANG { + let mut name = cursor; + while name > 0 { + name -= 1; + if matches!( + tokens[name].kind(), + ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT + ) { + continue; + } + return tokens[name].kind() == ra_ap_syntax::SyntaxKind::IDENT + && matches!( + tokens[name].text(), + "stringify" + | "concat" + | "env" + | "option_env" + | "include" + | "include_bytes" + | "include_str" + ); + } + return false; + } + } + false +} + fn bare_path_starts_at_boundary(tokens: &[ra_ap_syntax::SyntaxToken], position: usize) -> bool { let mut cursor = position; while cursor > 0 { diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs index 7a0fa065014..f839263327d 100644 --- a/crates/ripr/src/analysis/facts/harness_registry/tests.rs +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -490,6 +490,7 @@ fn snapshot_named_helpers_never_become_oracles_but_snapshot_asserts_do() vec![libtest_mimic::Trial::test(\"leaf_case\", || { snapshot_helper!(); other_snapshot!(); + assertsnapshot!(1); assert_snapshot!(1); Ok(()) })] @@ -591,7 +592,9 @@ fn macro_input_data_never_becomes_a_subject() -> Result<(), Box String { + "use libtest_mimic::Trial; + +fn debug() -> String { stringify!(trial: Trial::test(\"ghost_case\", || Ok(()))) } ", diff --git a/crates/ripr/src/analysis/syntax/ra.rs b/crates/ripr/src/analysis/syntax/ra.rs index c9a3690c2c1..2570680ef40 100644 --- a/crates/ripr/src/analysis/syntax/ra.rs +++ b/crates/ripr/src/analysis/syntax/ra.rs @@ -1072,7 +1072,7 @@ pub(crate) fn is_assertion_macro_leaf(name: &str) -> bool { matches!( name, "assert" | "assert_eq" | "assert_ne" | "assert_matches" | "matches" - ) || (name.starts_with("assert") && name.ends_with("snapshot")) + ) || (name.starts_with("assert_") && name.ends_with("snapshot")) } pub(crate) fn is_assertion_macro(macro_name: &str) -> bool { From 272ec06bb632b2e1345e2436bd457871780ee35f Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 06:39:32 -0400 Subject: [PATCH 29/33] fix(analysis): reject data-only harness macro inputs --- .../src/analysis/facts/harness_registry.rs | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index bb384b2d954..63e98803f16 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -434,7 +434,7 @@ fn is_data_only_macro_input(tokens: &[ra_ap_syntax::SyntaxToken], position: usiz | ra_ap_syntax::SyntaxKind::L_CURLY ) { if depth == 0 { - return false; + return data_only_macro_before(tokens, cursor); } depth -= 1; continue; @@ -467,6 +467,41 @@ fn is_data_only_macro_input(tokens: &[ra_ap_syntax::SyntaxToken], position: usiz false } +fn data_only_macro_before(tokens: &[ra_ap_syntax::SyntaxToken], open: usize) -> bool { + let significant = |mut index: usize| { + while index > 0 { + index -= 1; + if !matches!( + tokens[index].kind(), + ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT + ) { + return Some(index); + } + } + None + }; + let Some(bang) = significant(open) else { + return false; + }; + if tokens[bang].kind() != ra_ap_syntax::SyntaxKind::BANG { + return false; + } + let Some(name) = significant(bang) else { + return false; + }; + tokens[name].kind() == ra_ap_syntax::SyntaxKind::IDENT + && matches!( + tokens[name].text(), + "stringify" + | "concat" + | "env" + | "option_env" + | "include" + | "include_bytes" + | "include_str" + ) +} + fn bare_path_starts_at_boundary(tokens: &[ra_ap_syntax::SyntaxToken], position: usize) -> bool { let mut cursor = position; while cursor > 0 { From 8581466bc1c71d126c4e29c4d3df1e680c2d0482 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 06:48:55 -0400 Subject: [PATCH 30/33] fix(analysis): classify macro inputs by syntax ancestry --- .../src/analysis/facts/harness_registry.rs | 126 ++++++------------ .../analysis/facts/harness_registry/tests.rs | 58 ++++++++ 2 files changed, 100 insertions(+), 84 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index 63e98803f16..85584d3253d 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -413,93 +413,51 @@ fn match_trial_path( } fn is_data_only_macro_input(tokens: &[ra_ap_syntax::SyntaxToken], position: usize) -> bool { - let mut depth = 0usize; - let mut cursor = position; - while cursor > 0 { - cursor -= 1; - let kind = tokens[cursor].kind(); - if matches!( - kind, - ra_ap_syntax::SyntaxKind::R_PAREN - | ra_ap_syntax::SyntaxKind::R_BRACK - | ra_ap_syntax::SyntaxKind::R_CURLY - ) { - depth += 1; - continue; - } - if matches!( - kind, - ra_ap_syntax::SyntaxKind::L_PAREN - | ra_ap_syntax::SyntaxKind::L_BRACK - | ra_ap_syntax::SyntaxKind::L_CURLY - ) { - if depth == 0 { - return data_only_macro_before(tokens, cursor); - } - depth -= 1; - continue; - } - if depth == 0 && kind == ra_ap_syntax::SyntaxKind::BANG { - let mut name = cursor; - while name > 0 { - name -= 1; - if matches!( - tokens[name].kind(), - ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT - ) { - continue; - } - return tokens[name].kind() == ra_ap_syntax::SyntaxKind::IDENT - && matches!( - tokens[name].text(), - "stringify" - | "concat" - | "env" - | "option_env" - | "include" - | "include_bytes" - | "include_str" - ); - } - return false; - } - } - false + tokens[position] + .parent_ancestors() + .filter_map(ast::MacroCall::cast) + .any(|macro_call| { + let Some(path) = macro_call.path() else { + return false; + }; + let name = path.syntax().text().to_string().replace(' ', ""); + is_data_only_macro_name(&name) && !data_only_macro_is_shadowed(tokens, &name) + }) } -fn data_only_macro_before(tokens: &[ra_ap_syntax::SyntaxToken], open: usize) -> bool { - let significant = |mut index: usize| { - while index > 0 { - index -= 1; - if !matches!( - tokens[index].kind(), - ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT - ) { - return Some(index); - } - } - None - }; - let Some(bang) = significant(open) else { - return false; - }; - if tokens[bang].kind() != ra_ap_syntax::SyntaxKind::BANG { - return false; - } - let Some(name) = significant(bang) else { - return false; +fn is_data_only_macro_name(name: &str) -> bool { + matches!( + name, + "stringify" | "concat" | "env" | "option_env" | "include" | "include_bytes" | "include_str" + ) +} + +fn data_only_macro_is_shadowed(tokens: &[ra_ap_syntax::SyntaxToken], name: &str) -> bool { + let significant = |index: usize| { + tokens + .iter() + .enumerate() + .skip(index) + .find(|(_, token)| { + !matches!( + token.kind(), + ra_ap_syntax::SyntaxKind::WHITESPACE | ra_ap_syntax::SyntaxKind::COMMENT + ) + }) + .map(|(index, _)| index) }; - tokens[name].kind() == ra_ap_syntax::SyntaxKind::IDENT - && matches!( - tokens[name].text(), - "stringify" - | "concat" - | "env" - | "option_env" - | "include" - | "include_bytes" - | "include_str" - ) + tokens.iter().enumerate().any(|(index, token)| { + if token.text() != "macro_rules" { + return false; + } + let Some(bang) = significant(index + 1) else { + return false; + }; + let Some(declared) = significant(bang + 1) else { + return false; + }; + tokens[bang].kind() == ra_ap_syntax::SyntaxKind::BANG && tokens[declared].text() == name + }) } fn bare_path_starts_at_boundary(tokens: &[ra_ap_syntax::SyntaxToken], position: usize) -> bool { diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs index f839263327d..c35fe81510e 100644 --- a/crates/ripr/src/analysis/facts/harness_registry/tests.rs +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -614,6 +614,64 @@ fn debug() -> String { Ok(()) } +#[test] +fn nested_data_macro_input_never_becomes_a_subject() -> Result<(), Box> { + let root = temp_dir("nested-macro-input-data")?; + write_workspace( + &root, + &[( + "tests/nested_macro_input.rs", + "use libtest_mimic::Trial; + +fn debug() -> String { + stringify!((Trial::test(\"ghost_case\", || Ok(())))) +} +", + )], + )?; + let files = [PathBuf::from("tests/nested_macro_input.rs")]; + let registrations = [custom_target_registration("tests/nested_macro_input.rs")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert!( + index.harness_subjects.is_empty(), + "{:?}", + index.harness_subjects + ); + assert!(index.tests.is_empty(), "{:?}", index.tests); + Ok(()) +} + +#[test] +fn shadowed_data_macro_name_keeps_executable_trial_eligible() +-> Result<(), Box> { + let root = temp_dir("shadowed-data-macro")?; + write_workspace( + &root, + &[( + "tests/shadowed_macro.rs", + "use libtest_mimic::Trial; + +macro_rules! stringify { ($value:expr) => { $value }; } + +fn trials() -> Vec { + stringify!(vec![Trial::test(\"real_case\", || Ok(()))]) +} +", + )], + )?; + let files = [PathBuf::from("tests/shadowed_macro.rs")]; + let registrations = [custom_target_registration("tests/shadowed_macro.rs")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert_eq!( + index.harness_subjects.len(), + 1, + "{:?}", + index.harness_subjects + ); + assert_eq!(index.tests.len(), 1, "{:?}", index.tests); + Ok(()) +} + #[test] fn struct_field_initializers_still_start_trial_paths() -> Result<(), Box> { let root = temp_dir("struct-field-trial")?; From 7fab85b2581369948574c7cfee49837e6f0b30b0 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 14:42:53 -0400 Subject: [PATCH 31/33] fix(analysis): scope harness macro shadowing --- .../src/analysis/facts/harness_registry.rs | 57 +++++++- .../analysis/facts/harness_registry/tests.rs | 128 ++++++++++++++++++ 2 files changed, 181 insertions(+), 4 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index 85584d3253d..6a66b3b4c67 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -421,7 +421,7 @@ fn is_data_only_macro_input(tokens: &[ra_ap_syntax::SyntaxToken], position: usiz return false; }; let name = path.syntax().text().to_string().replace(' ', ""); - is_data_only_macro_name(&name) && !data_only_macro_is_shadowed(tokens, &name) + is_data_only_macro_name(&name) && !data_only_macro_is_shadowed(tokens, position, &name) }) } @@ -432,7 +432,11 @@ fn is_data_only_macro_name(name: &str) -> bool { ) } -fn data_only_macro_is_shadowed(tokens: &[ra_ap_syntax::SyntaxToken], name: &str) -> bool { +fn data_only_macro_is_shadowed( + tokens: &[ra_ap_syntax::SyntaxToken], + invocation_position: usize, + name: &str, +) -> bool { let significant = |index: usize| { tokens .iter() @@ -446,8 +450,11 @@ fn data_only_macro_is_shadowed(tokens: &[ra_ap_syntax::SyntaxToken], name: &str) }) .map(|(index, _)| index) }; + let invocation_scopes = lexical_scopes(tokens[invocation_position].parent_ancestors()); + let invocation_offset = tokens[invocation_position].text_range().start(); + tokens.iter().enumerate().any(|(index, token)| { - if token.text() != "macro_rules" { + if token.text() != "macro_rules" || token.text_range().start() >= invocation_offset { return false; } let Some(bang) = significant(index + 1) else { @@ -456,10 +463,43 @@ fn data_only_macro_is_shadowed(tokens: &[ra_ap_syntax::SyntaxToken], name: &str) let Some(declared) = significant(bang + 1) else { return false; }; - tokens[bang].kind() == ra_ap_syntax::SyntaxKind::BANG && tokens[declared].text() == name + if tokens[bang].kind() != ra_ap_syntax::SyntaxKind::BANG || tokens[declared].text() != name + { + return false; + } + let Some(declaration) = token.parent_ancestors().find_map(ast::MacroRules::cast) else { + return false; + }; + let declaration_scopes = lexical_scopes(declaration.syntax().ancestors()); + declaration_scopes.iter().any(|declaration_scope| { + invocation_scopes + .iter() + .any(|invocation_scope| same_syntax_node(declaration_scope, invocation_scope)) + }) }) } +fn lexical_scopes( + ancestors: impl Iterator, +) -> Vec { + ancestors + .filter(|ancestor| { + matches!( + ancestor.kind(), + ra_ap_syntax::SyntaxKind::ASSOC_ITEM_LIST + | ra_ap_syntax::SyntaxKind::BLOCK_EXPR + | ra_ap_syntax::SyntaxKind::EXTERN_ITEM_LIST + | ra_ap_syntax::SyntaxKind::ITEM_LIST + | ra_ap_syntax::SyntaxKind::SOURCE_FILE + ) + }) + .collect() +} + +fn same_syntax_node(left: &ra_ap_syntax::SyntaxNode, right: &ra_ap_syntax::SyntaxNode) -> bool { + left.kind() == right.kind() && left.text_range() == right.text_range() +} + fn bare_path_starts_at_boundary(tokens: &[ra_ap_syntax::SyntaxToken], position: usize) -> bool { let mut cursor = position; while cursor > 0 { @@ -1005,6 +1045,9 @@ fn resolve_registered_attribute( marker: &str, use_bindings: &BTreeSet, ) -> Option { + // An exact configured path is authoritative regardless of where an + // unresolved bare leaf appears in the attribute list. Scan it first so a + // conservative limitation for one spelling cannot hide a provable match. for attribute in attrs { let Some(path) = normalized_attribute_path(attribute) else { continue; @@ -1012,6 +1055,12 @@ fn resolve_registered_attribute( if path == marker { return Some(RegisteredAttributeResolution::Matched); } + } + + for attribute in attrs { + let Some(path) = normalized_attribute_path(attribute) else { + continue; + }; let Some((_prefix, name)) = marker.rsplit_once("::") else { continue; }; diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs index c35fe81510e..bf8ea054beb 100644 --- a/crates/ripr/src/analysis/facts/harness_registry/tests.rs +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -672,6 +672,68 @@ fn trials() -> Vec { Ok(()) } +#[test] +fn later_data_macro_declaration_does_not_shadow_an_earlier_builtin_input() +-> Result<(), Box> { + let root = temp_dir("later-shadowed-data-macro")?; + write_workspace( + &root, + &[( + "tests/later_shadow.rs", + "use libtest_mimic::Trial; + +fn trials() -> Vec { + stringify!(vec![Trial::test(\"builtin_case\", || Ok(()))]) +} + +macro_rules! stringify { ($value:expr) => { $value }; } +", + )], + )?; + let files = [PathBuf::from("tests/later_shadow.rs")]; + let registrations = [custom_target_registration("tests/later_shadow.rs")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert!( + index.harness_subjects.is_empty(), + "{:?}", + index.harness_subjects + ); + assert!(index.tests.is_empty(), "{:?}", index.tests); + Ok(()) +} + +#[test] +fn sibling_data_macro_declaration_does_not_shadow_a_builtin_input() +-> Result<(), Box> { + let root = temp_dir("sibling-shadowed-data-macro")?; + write_workspace( + &root, + &[( + "tests/sibling_shadow.rs", + "use libtest_mimic::Trial; + +fn trials() -> Vec { + stringify!(vec![Trial::test(\"builtin_case\", || Ok(()))]) +} + +mod sibling { + macro_rules! stringify { ($value:expr) => { $value }; } +} +", + )], + )?; + let files = [PathBuf::from("tests/sibling_shadow.rs")]; + let registrations = [custom_target_registration("tests/sibling_shadow.rs")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert!( + index.harness_subjects.is_empty(), + "{:?}", + index.harness_subjects + ); + assert!(index.tests.is_empty(), "{:?}", index.tests); + Ok(()) +} + #[test] fn struct_field_initializers_still_start_trial_paths() -> Result<(), Box> { let root = temp_dir("struct-field-trial")?; @@ -1075,6 +1137,72 @@ fn bare_attribute_without_marker_import_stays_unclassified() Ok(()) } +#[test] +fn exact_registered_attribute_after_unresolved_bare_attribute_still_matches() +-> Result<(), Box> { + let root = temp_dir("attribute-exact-after-bare")?; + write_workspace( + &root, + &[( + "tests/after_bare.rs", + "#[contract_test] +#[myco::contract_test] +fn exact_after_bare() { + assert_eq!(1, 1); +} +", + )], + )?; + let target = "tests/after_bare.rs"; + let index = build_index_with_test_harnesses( + &root.0, + &[PathBuf::from(target)], + &[attribute_registration(target, "myco::contract_test")], + )?; + assert_eq!( + index + .harness_subjects + .iter() + .map(|subject| subject.name.as_str()) + .collect::>(), + vec!["exact_after_bare"] + ); + Ok(()) +} + +#[test] +fn exact_registered_attribute_before_unresolved_bare_attribute_still_matches() +-> Result<(), Box> { + let root = temp_dir("attribute-exact-before-bare")?; + write_workspace( + &root, + &[( + "tests/before_bare.rs", + "#[myco::contract_test] +#[contract_test] +fn exact_before_bare() { + assert_eq!(1, 1); +} +", + )], + )?; + let target = "tests/before_bare.rs"; + let index = build_index_with_test_harnesses( + &root.0, + &[PathBuf::from(target)], + &[attribute_registration(target, "myco::contract_test")], + )?; + assert_eq!( + index + .harness_subjects + .iter() + .map(|subject| subject.name.as_str()) + .collect::>(), + vec!["exact_before_bare"] + ); + Ok(()) +} + #[test] fn cached_index_applies_registrations_identically() -> Result<(), Box> { let root = temp_dir("cached-harness")?; From 07c17f8202bc9bd5c50190ab96d41bd54ceb624d Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 15:23:00 -0400 Subject: [PATCH 32/33] fix(analysis): tighten macro shadow resolution --- .../src/analysis/facts/harness_registry.rs | 32 ++++++++++---- .../analysis/facts/harness_registry/tests.rs | 42 +++++++++++++++++-- 2 files changed, 62 insertions(+), 12 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index 6a66b3b4c67..6655537625f 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -420,8 +420,11 @@ fn is_data_only_macro_input(tokens: &[ra_ap_syntax::SyntaxToken], position: usiz let Some(path) = macro_call.path() else { return false; }; - let name = path.syntax().text().to_string().replace(' ', ""); - is_data_only_macro_name(&name) && !data_only_macro_is_shadowed(tokens, position, &name) + let path = path.syntax().text().to_string().replace(' ', ""); + let Some(name) = supported_data_only_macro_name(&path) else { + return false; + }; + !data_only_macro_is_shadowed(tokens, position, name) }) } @@ -432,6 +435,16 @@ fn is_data_only_macro_name(name: &str) -> bool { ) } +fn supported_data_only_macro_name(path: &str) -> Option<&str> { + if is_data_only_macro_name(path) { + return Some(path); + } + ["std::", "core::"] + .iter() + .find_map(|prefix| path.strip_prefix(prefix)) + .filter(|name| is_data_only_macro_name(name)) +} + fn data_only_macro_is_shadowed( tokens: &[ra_ap_syntax::SyntaxToken], invocation_position: usize, @@ -470,12 +483,15 @@ fn data_only_macro_is_shadowed( let Some(declaration) = token.parent_ancestors().find_map(ast::MacroRules::cast) else { return false; }; - let declaration_scopes = lexical_scopes(declaration.syntax().ancestors()); - declaration_scopes.iter().any(|declaration_scope| { - invocation_scopes - .iter() - .any(|invocation_scope| same_syntax_node(declaration_scope, invocation_scope)) - }) + let Some(declaration_scope) = lexical_scopes(declaration.syntax().ancestors()) + .into_iter() + .next() + else { + return false; + }; + invocation_scopes + .iter() + .any(|invocation_scope| same_syntax_node(&declaration_scope, invocation_scope)) }) } diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs index bf8ea054beb..55db15bf6fb 100644 --- a/crates/ripr/src/analysis/facts/harness_registry/tests.rs +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -712,13 +712,13 @@ fn sibling_data_macro_declaration_does_not_shadow_a_builtin_input() "tests/sibling_shadow.rs", "use libtest_mimic::Trial; -fn trials() -> Vec { - stringify!(vec![Trial::test(\"builtin_case\", || Ok(()))]) -} - mod sibling { macro_rules! stringify { ($value:expr) => { $value }; } } + +fn trials() -> Vec { + stringify!(vec![Trial::test(\"builtin_case\", || Ok(()))]) +} ", )], )?; @@ -734,6 +734,40 @@ mod sibling { Ok(()) } +#[test] +fn qualified_data_only_macros_accept_std_and_reject_arbitrary_prefixes() +-> Result<(), Box> { + let root = temp_dir("qualified-data-only-macro")?; + write_workspace( + &root, + &[( + "tests/qualified_shadow.rs", + "use libtest_mimic::Trial; + +fn std_builtin() -> Vec { + std::stringify!(vec![Trial::test(\"std_builtin_case\", || Ok(()))]) +} + +fn arbitrary_prefix() -> Vec { + other::stringify!(vec![Trial::test(\"arbitrary_case\", || Ok(()))]) +} +", + )], + )?; + let files = [PathBuf::from("tests/qualified_shadow.rs")]; + let registrations = [custom_target_registration("tests/qualified_shadow.rs")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert_eq!( + index + .harness_subjects + .iter() + .map(|subject| subject.name.as_str()) + .collect::>(), + vec!["arbitrary_case"] + ); + Ok(()) +} + #[test] fn struct_field_initializers_still_start_trial_paths() -> Result<(), Box> { let root = temp_dir("struct-field-trial")?; From dd263346ad4fc419392ed1dcef0af847bcb5735b Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Mon, 31 Aug 2026 15:46:40 -0400 Subject: [PATCH 33/33] fix(analysis): preserve qualified builtin macro identity --- .../src/analysis/facts/harness_registry.rs | 12 ++-- .../analysis/facts/harness_registry/tests.rs | 58 +++++++++++++++++++ 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/crates/ripr/src/analysis/facts/harness_registry.rs b/crates/ripr/src/analysis/facts/harness_registry.rs index 6655537625f..e1b15777c8a 100644 --- a/crates/ripr/src/analysis/facts/harness_registry.rs +++ b/crates/ripr/src/analysis/facts/harness_registry.rs @@ -421,10 +421,10 @@ fn is_data_only_macro_input(tokens: &[ra_ap_syntax::SyntaxToken], position: usiz return false; }; let path = path.syntax().text().to_string().replace(' ', ""); - let Some(name) = supported_data_only_macro_name(&path) else { + let Some((name, shadowable)) = supported_data_only_macro_name(&path) else { return false; }; - !data_only_macro_is_shadowed(tokens, position, name) + !shadowable || !data_only_macro_is_shadowed(tokens, position, name) }) } @@ -435,14 +435,18 @@ fn is_data_only_macro_name(name: &str) -> bool { ) } -fn supported_data_only_macro_name(path: &str) -> Option<&str> { +/// Return the supported data-only macro's terminal name and whether a local +/// `macro_rules!` declaration can shadow this spelling. Qualified standard +/// library paths are fixed built-ins; only their bare spelling is lexical. +fn supported_data_only_macro_name(path: &str) -> Option<(&str, bool)> { if is_data_only_macro_name(path) { - return Some(path); + return Some((path, true)); } ["std::", "core::"] .iter() .find_map(|prefix| path.strip_prefix(prefix)) .filter(|name| is_data_only_macro_name(name)) + .map(|name| (name, false)) } fn data_only_macro_is_shadowed( diff --git a/crates/ripr/src/analysis/facts/harness_registry/tests.rs b/crates/ripr/src/analysis/facts/harness_registry/tests.rs index 55db15bf6fb..56b675c3109 100644 --- a/crates/ripr/src/analysis/facts/harness_registry/tests.rs +++ b/crates/ripr/src/analysis/facts/harness_registry/tests.rs @@ -768,6 +768,64 @@ fn arbitrary_prefix() -> Vec { Ok(()) } +#[test] +fn local_stringify_does_not_shadow_std_stringify() -> Result<(), Box> { + let root = temp_dir("local-before-std-stringify")?; + write_workspace( + &root, + &[( + "tests/std_stringify.rs", + "use libtest_mimic::Trial; + +macro_rules! stringify { ($value:expr) => { $value }; } + +fn trials() -> Vec { + std::stringify!(vec![Trial::test(\"std_builtin_case\", || Ok(()))]) +} +", + )], + )?; + let files = [PathBuf::from("tests/std_stringify.rs")]; + let registrations = [custom_target_registration("tests/std_stringify.rs")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert!( + index.harness_subjects.is_empty(), + "{:?}", + index.harness_subjects + ); + assert!(index.tests.is_empty(), "{:?}", index.tests); + Ok(()) +} + +#[test] +fn local_concat_does_not_shadow_core_concat() -> Result<(), Box> { + let root = temp_dir("local-before-core-concat")?; + write_workspace( + &root, + &[( + "tests/core_concat.rs", + "use libtest_mimic::Trial; + +macro_rules! concat { ($value:expr) => { $value }; } + +fn trials() -> Vec { + core::concat!(vec![Trial::test(\"core_builtin_case\", || Ok(()))]) +} +", + )], + )?; + let files = [PathBuf::from("tests/core_concat.rs")]; + let registrations = [custom_target_registration("tests/core_concat.rs")]; + let index = build_index_with_test_harnesses(&root.0, &files, ®istrations)?; + assert!( + index.harness_subjects.is_empty(), + "{:?}", + index.harness_subjects + ); + assert!(index.tests.is_empty(), "{:?}", index.tests); + Ok(()) +} + #[test] fn struct_field_initializers_still_start_trial_paths() -> Result<(), Box> { let root = temp_dir("struct-field-trial")?;