#[path = "claim_provenance.rs"]
pub mod claim_provenance;
pub use crate::index_lifecycle::guidance::health::*;
pub use crate::index_lifecycle::guidance::reference_read::OutputLimits;
use crate::domain::index::{AdmissionTier, SkipReason, SkippedFile};
#[cfg(test)]
use crate::domain::{CoverageStatus, FileDisposition, FreshnessStatus, RepositoryManifest};
#[cfg(test)]
use crate::live_index::{
ContextBundleFoundView, ContextBundleReferenceView, ContextBundleSectionView,
ContextBundleView, FindReferencesView, HealthStats, ImplBlockSuggestionView, IndexLoadSource,
TypeDependencyView,
};
use crate::live_index::{
FileOutlineView, IndexedFile, LiveIndex, RepoOutlineFileView, RepoOutlineView,
SnapshotVerifyState, search,
};
use crate::protocol::surface_probe::{SurfaceProfile, connection_surface_or_env};
use crate::{cli::hook::HookAdoptionSnapshot, sidecar::StatsSnapshot};
pub use crate::index_lifecycle::guidance::file_search::capability_evidence_line;
pub fn file_outline(index: &LiveIndex, path: &str) -> String {
match index.capture_shared_file(path) {
Some(file) => file_outline_from_indexed_file(file.as_ref()),
None => not_found_file(path),
}
}
pub fn file_outline_from_indexed_file(file: &IndexedFile) -> String {
render_file_outline(&file.relative_path, &file.symbols)
}
fn render_file_outline(relative_path: &str, symbols: &[crate::domain::SymbolRecord]) -> String {
let mut lines = Vec::new();
lines.push(format!("{} ({} symbols)", relative_path, symbols.len()));
for sym in symbols {
let indent = " ".repeat(sym.depth as usize);
let kind_str = sym.kind.to_string();
lines.push(format!(
"{}{:<12} {:<30} {}-{}",
indent,
kind_str,
sym.name,
sym.line_range.0 + 1,
sym.line_range.1 + 1
));
}
lines.join("\n")
}
pub fn collapse_large_test_modules(
text: String,
include_tests: bool,
sections: Option<&[String]>,
) -> String {
crate::index_lifecycle::guidance::read_context::collapse_large_test_modules(
text,
include_tests,
sections,
)
}
pub fn file_outline_view(view: &FileOutlineView) -> String {
render_file_outline(&view.relative_path, &view.symbols)
}
pub use crate::index_lifecycle::guidance::symbol_read::inspect_match_result_view;
#[cfg(test)]
use crate::index_lifecycle::guidance::symbol_read::symbol_kind_name_label;
pub use crate::index_lifecycle::guidance::symbol_read::{
code_slice_from_indexed_file, code_slice_view, symbol_detail, symbol_detail_from_indexed_file,
symbol_detail_view,
};
pub fn search_symbols_result(index: &LiveIndex, query: &str) -> String {
search_symbols_result_with_kind(index, query, None)
}
pub fn search_symbols_result_with_kind(
index: &LiveIndex,
query: &str,
kind_filter: Option<&str>,
) -> String {
let result = search::search_symbols(
index,
query,
kind_filter,
search::ResultLimit::symbol_search_default().get(),
);
search_symbols_result_view(&result, query)
}
pub use crate::index_lifecycle::guidance::search_render::search_symbols_result_view;
pub fn search_text_result(index: &LiveIndex, query: &str) -> String {
search_text_result_with_options(index, Some(query), None, false)
}
pub fn search_text_result_with_options(
index: &LiveIndex,
query: Option<&str>,
terms: Option<&[String]>,
regex: bool,
) -> String {
let result = search::search_text(index, query, terms, regex);
search_text_result_view(
result,
None,
None,
None,
SearchSuggestionContext {
regex,
include_tests: false,
multi_word_literal: !regex
&& query.is_some_and(|q| q.trim().contains(char::is_whitespace)),
},
)
}
pub(crate) use crate::index_lifecycle::guidance::search_render::append_excluded_knowledge_note;
pub use crate::index_lifecycle::guidance::search_render::{
SearchSuggestionContext, search_text_result_view,
};
pub fn file_tree(index: &LiveIndex, path: &str, depth: u32) -> String {
let view = index.capture_repo_outline_view();
file_tree_view(&view.files, path, depth)
}
pub fn file_tree_view(files: &[RepoOutlineFileView], path: &str, depth: u32) -> String {
crate::index_lifecycle::guidance::read_context::file_tree_view(files, path, depth)
}
pub fn file_tree_view_with_skipped(
files: &[RepoOutlineFileView],
skipped: &[SkippedFile],
path: &str,
depth: u32,
) -> String {
crate::index_lifecycle::guidance::read_context::file_tree_view_with_skipped(
files, skipped, path, depth,
)
}
pub fn repo_outline(index: &LiveIndex, project_name: &str) -> String {
let view = index.capture_repo_outline_view();
repo_outline_view(&view, project_name)
}
pub fn repo_outline_view(view: &RepoOutlineView, project_name: &str) -> String {
crate::index_lifecycle::guidance::read_context::repo_outline_view(view, project_name)
}
pub fn health_report(index: &LiveIndex) -> String {
use crate::live_index::IndexState;
let state = index.index_state();
let status = match state {
IndexState::Empty => "Empty",
IndexState::Ready => "Ready",
IndexState::Loading => "Loading",
IndexState::CircuitBreakerTripped { .. } => "Degraded",
};
let stats = index.health_stats();
health_report_from_stats(status, &stats, 0)
}
pub fn health_report_with_watcher(
index: &LiveIndex,
watcher: &crate::watcher::WatcherInfo,
) -> String {
use crate::live_index::IndexState;
let state = index.index_state();
let status = match state {
IndexState::Empty => "Empty",
IndexState::Ready => "Ready",
IndexState::Loading => "Loading",
IndexState::CircuitBreakerTripped { .. } => "Degraded",
};
let stats = index.health_stats_with_watcher(watcher);
health_report_from_stats(status, &stats, 0)
}
fn sidecar_pid_label(status: &crate::sidecar::port_file::SidecarStatus) -> String {
status
.pid
.map(|pid| pid.to_string())
.unwrap_or_else(|| "unknown".to_string())
}
fn sidecar_port_label(status: &crate::sidecar::port_file::SidecarStatus) -> String {
status
.port
.map(|port| port.to_string())
.unwrap_or_else(|| "unknown".to_string())
}
pub(crate) fn format_sidecar_status(status: &crate::sidecar::port_file::SidecarStatus) -> String {
if status.liveness == crate::sidecar::port_file::SidecarLiveness::NoSidecar {
return match status.detail.as_deref() {
Some(detail) => format!("Sidecar: none usable ({detail})"),
None => "Sidecar: none (.symforge/sidecar.* absent)".to_string(),
};
}
let mut line = format!(
"Sidecar: pid={} port={} state={}",
sidecar_pid_label(status),
sidecar_port_label(status),
status.liveness.as_str(),
);
if let Some(detail) = status.detail.as_deref() {
line.push_str(&format!(" ({detail})"));
}
line
}
pub(crate) fn format_sidecar_status_compact(
status: &crate::sidecar::port_file::SidecarStatus,
) -> String {
if status.liveness == crate::sidecar::port_file::SidecarLiveness::NoSidecar {
return match status.detail.as_deref() {
Some(detail) => format!("Sidecar: none usable ({detail})"),
None => "Sidecar: none".to_string(),
};
}
format!(
"Sidecar: {} pid={} port={}",
status.liveness.as_str(),
sidecar_pid_label(status),
sidecar_port_label(status),
)
}
pub fn what_changed_result(index: &LiveIndex, since_ts: i64) -> String {
let view = index.capture_what_changed_timestamp_view();
what_changed_timestamp_view(&view, since_ts)
}
pub use crate::index_lifecycle::guidance::changes::detect_impact_result;
pub(crate) use crate::index_lifecycle::guidance::changes::{
what_changed_paths_result, what_changed_timestamp_view,
};
pub use crate::index_lifecycle::guidance::search_render::search_files_resolve_result_view;
pub fn search_files(index: &LiveIndex, query: &str, limit: usize) -> String {
let view = index.capture_search_files_view(query, limit, None, None);
search_files_result_view(&view)
}
pub use crate::index_lifecycle::guidance::search_render::search_files_result_view;
pub(crate) use crate::index_lifecycle::guidance::file_read::{
ContentSelectionMiss, content_selection, render_file_content_bytes,
};
pub use crate::index_lifecycle::guidance::file_read::{
GET_FILE_CONTENT_MAX_BYTES, append_nul_byte_warning, cap_file_content_output, file_content,
file_content_from_indexed_file, file_content_from_indexed_file_with_context, file_content_view,
not_found_file, not_found_file_match, not_found_symbol, validate_file_syntax_result,
};
pub fn path_outside_repo(path: &str) -> String {
format!(
"Path is outside the repository root: {path}. \
get_file_content only reads files within the indexed repository; \
supply a repo-relative path."
)
}
pub use crate::index_lifecycle::guidance::read_admission_format::content_withheld_by_admission;
pub use crate::index_lifecycle::guidance::read_admission_format::content_withheld_by_path_rule;
pub use crate::index_lifecycle::guidance::read_admission_format::content_withheld_unscanned;
pub use crate::index_lifecycle::guidance::read_admission_format::unverified_since_restore;
use crate::index_lifecycle::guidance::read_context::withheld_listing;
pub fn withheld_not_searched_note(
unverified: &std::collections::BTreeMap<String, String>,
scope: Option<&str>,
) -> Option<String> {
crate::index_lifecycle::guidance::read_context::withheld_not_searched_note(unverified, scope)
}
pub fn project_wide_mutation_refused_unverified(
tool: &str,
unverified: &std::collections::BTreeMap<String, String>,
) -> Option<String> {
let (count, listed) = withheld_listing(unverified, None, 10)?;
Some(format!(
"{tool} refused: {count} files are withheld as unverified since restore, and a \
project-wide change cannot see what they contain: {listed}. A successful re-read \
releases each one; run index_folder to rebuild the project from source, then retry."
))
}
pub fn not_found_file_with_suggestions(path: &str, suggestions: &[String]) -> String {
if suggestions.is_empty() {
format!("File not found: {path}. Use search_files to find the correct path.")
} else {
let top: Vec<&str> = suggestions.iter().take(5).map(|s| s.as_str()).collect();
format!("File not found: {path}. Did you mean: {}?", top.join(", "))
}
}
pub fn not_indexed_skipped_file(
path: &str,
tier: AdmissionTier,
reason: Option<SkipReason>,
size: Option<u64>,
raw_read_available: bool,
) -> String {
let reason_str = reason
.map(|r| r.to_string())
.unwrap_or_else(|| "skipped".to_string());
let size_str = size
.map(crate::index_lifecycle::guidance::read_context::human_size)
.unwrap_or_else(|| "unknown".to_string());
match tier {
AdmissionTier::Normal => {
not_found_file(path)
}
AdmissionTier::MetadataOnly if raw_read_available => format!(
"Not indexed: {path} is Tier 2 (metadata only) — reason: {reason_str}, size {size_str}. \
Use get_file_content for raw reads if you need the contents."
),
AdmissionTier::MetadataOnly => format!(
"Not indexed: {path} is Tier 2 (metadata only) — reason: {reason_str}, size {size_str}. \
Its contents are withheld by the admission policy — get_file_content will refuse this \
file, so read it outside SymForge if you need the raw text."
),
AdmissionTier::HardSkip if raw_read_available => format!(
"Not indexed: {path} is Tier 3 (hard-skipped) — reason: {reason_str}, size {size_str}. \
This file is not parsed or read; get_file_content may still read it raw if it is a \
text file within the repository."
),
AdmissionTier::HardSkip => format!(
"Not indexed: {path} is Tier 3 (hard-skipped) — reason: {reason_str}, size {size_str}. \
This file is not parsed or read, and its contents are withheld by the admission \
policy — get_file_content will refuse this file, so read it outside SymForge if you \
need the raw text."
),
}
}
pub use crate::index_lifecycle::guidance::reference_read::{
find_dependents_compact_view, find_dependents_dot, find_dependents_mermaid,
find_dependents_result, find_dependents_result_view, find_references_compact_view,
find_references_result, find_references_result_view, implementations_result_view,
};
#[cfg(test)]
use crate::index_lifecycle::guidance::source::extract_signature;
pub(crate) use crate::index_lifecycle::guidance::symbol_context::symbol_defined_anywhere;
#[cfg(test)]
use crate::index_lifecycle::guidance::symbol_context::{
apply_verbosity, auto_summarize, format_type_dependencies, heuristic_from_name,
};
pub use crate::index_lifecycle::guidance::symbol_context::{
context_bundle_callees_text, context_bundle_impl_suggestion_tip, context_bundle_result,
context_bundle_result_view, context_bundle_result_view_with_max_tokens,
trace_symbol_result_view,
};
pub use crate::index_lifecycle::guidance::source::{
downgrade_full_completeness_after_truncation, enforce_token_budget,
enforce_token_budget_flagged,
};
pub fn loading_guard_message(cold_bootstrap: bool) -> String {
let wording = if cold_bootstrap {
INITIAL_INDEXING_IN_PROGRESS
} else {
INDEXING_IN_PROGRESS
};
format!("Index is loading... {wording}. Retry the same call shortly.")
}
pub const INDEXING_IN_PROGRESS: &str =
"indexing of this project is in progress and can take a while on large folders";
pub const INITIAL_INDEXING_IN_PROGRESS: &str =
"initial indexing of this project is in progress and can take a while on large folders";
pub const SNAPSHOT_VERIFY_IN_PROGRESS: &str =
"Index is loading: verifying a restored snapshot against disk";
pub fn loading_guard_message_for(state: &SnapshotVerifyState, cold_bootstrap: bool) -> String {
let detail = match state {
SnapshotVerifyState::Pending => "verify=pending".to_string(),
SnapshotVerifyState::Running(progress) => {
format!("verify=running {}", progress.describe())
}
SnapshotVerifyState::NotNeeded
| SnapshotVerifyState::Completed(_)
| SnapshotVerifyState::Failed(_) => {
return loading_guard_message(cold_bootstrap);
}
};
format!(
"{SNAPSHOT_VERIFY_IN_PROGRESS} ({detail}). It re-reads the files that changed \
since the snapshot and publishes them once; restored files stay hidden until it \
completes. `status` and `health` report its progress."
)
}
pub fn empty_index_recovery_hint(profile: SurfaceProfile) -> String {
match profile {
SurfaceProfile::Compact => "Index not loaded. SymForge has no resolvable project \
root. To recover, set SYMFORGE_WORKSPACE_ROOT to the project path in this client's \
MCP config, or run `symforge init` for this harness, then reconnect. \
(SYMFORGE_SURFACE=full exposes the full tool surface for manual indexing.)"
.to_string(),
SurfaceProfile::Full | SurfaceProfile::Meta => {
"Index not loaded. Call index_folder to index a directory.".to_string()
}
}
}
pub fn empty_guard_message() -> String {
empty_index_recovery_hint(connection_surface_or_env())
}
pub fn format_token_savings(snap: &StatsSnapshot) -> String {
let total_saved = snap.read_saved_tokens + snap.edit_saved_tokens + snap.grep_saved_tokens;
let any_fires =
snap.read_fires > 0 || snap.edit_fires > 0 || snap.write_fires > 0 || snap.grep_fires > 0;
if !any_fires {
return String::new();
}
let mut lines = vec!["── Token Savings (this session) ──".to_string()];
if snap.read_fires > 0 {
lines.push(format!(
"Read: {} fires, ~{} tokens saved",
snap.read_fires, snap.read_saved_tokens
));
}
if snap.edit_fires > 0 {
lines.push(format!(
"Edit: {} fires, ~{} tokens saved",
snap.edit_fires, snap.edit_saved_tokens
));
}
if snap.write_fires > 0 {
lines.push(format!("Write: {} fires", snap.write_fires));
}
if snap.grep_fires > 0 {
lines.push(format!(
"Grep: {} fires, ~{} tokens saved",
snap.grep_fires, snap.grep_saved_tokens
));
}
lines.push(format!(
"Total: ~{} tokens saved (vs competent-manual windowed read)",
total_saved
));
lines.join("\n")
}
pub fn format_tool_token_breakdown(details: &[(String, u64, u64)]) -> String {
if details.is_empty() {
return String::new();
}
let total_served: u64 = details.iter().map(|(_, s, _)| s).sum();
let total_saved: u64 = details.iter().map(|(_, _, s)| s).sum();
let total_naive = total_served + total_saved;
let efficiency = if total_served > 0 {
total_naive as f64 / total_served as f64
} else {
1.0
};
let reduction_pct = if total_naive > 0 {
(total_saved as f64 / total_naive as f64 * 100.0) as u64
} else {
0
};
let mut lines = vec![format!(
"\u{2500}\u{2500} Session Efficiency (competent-manual baseline) \u{2500}\u{2500}\nTokens served: {}\nCompetent-manual equivalent: {}\nEfficiency: {:.1}x ({reduction_pct}% reduction vs windowed-read baseline)",
total_served, total_naive, efficiency
)];
lines.push(String::new());
lines.push("\u{2500}\u{2500} Per-Tool Breakdown \u{2500}\u{2500}".to_string());
let max_name = details.iter().map(|(n, _, _)| n.len()).max().unwrap_or(0);
for (name, served, saved) in details.iter().take(10) {
let tool_naive = served + saved;
let tool_eff = if *served > 0 {
format!("{:.1}x", tool_naive as f64 / *served as f64)
} else {
"-".to_string()
};
lines.push(format!(
" {:<width$} {} served, {} saved ({})",
name,
served,
saved,
tool_eff,
width = max_name
));
}
lines.join("\n")
}
pub fn format_tool_call_counts(counts: &[(String, usize)]) -> String {
if counts.is_empty() {
return String::new();
}
let mut lines = vec!["── Tool Call Counts (this session) ──".to_string()];
let max_name_len = counts.iter().map(|(n, _)| n.len()).max().unwrap_or(0);
for (name, count) in counts {
lines.push(format!("{:<width$} {}", name, count, width = max_name_len));
}
lines.join("\n")
}
pub use crate::index_lifecycle::guidance::file_read::COMPETENT_READ_WINDOW_LINES;
pub use crate::index_lifecycle::guidance::file_read::SMALL_FILE_CHAR_THRESHOLD;
pub use crate::index_lifecycle::guidance::read_context::SMALL_FILE_LINE_THRESHOLD;
pub fn whole_file_baseline_chars(raw_chars: usize) -> usize {
raw_chars
}
pub use crate::index_lifecycle::guidance::file_read::competent_manual_baseline_chars;
pub fn indexed_file_line_count(content: &[u8]) -> usize {
crate::index_lifecycle::guidance::read_context::indexed_file_line_count(content)
}
pub fn is_small_indexed_file(content_len: usize, line_count: usize) -> bool {
crate::index_lifecycle::guidance::read_context::is_small_indexed_file(content_len, line_count)
}
pub use crate::index_lifecycle::guidance::file_read::default_read_max_tokens;
pub use crate::index_lifecycle::guidance::file_read::resolve_read_max_tokens;
pub use crate::index_lifecycle::guidance::file_read::estimate_tokens_from_chars;
pub fn saved_tokens_whole_file(response_chars: usize, raw_chars: usize) -> u64 {
crate::index_lifecycle::guidance::read_context::saved_tokens_whole_file(
response_chars,
raw_chars,
)
}
pub fn saved_tokens_vs_competent_manual(response_chars: usize, raw_chars: usize) -> u64 {
crate::index_lifecycle::guidance::read_context::saved_tokens_vs_competent_manual(
response_chars,
raw_chars,
)
}
pub fn estimate_listing_baseline_chars(output_chars: usize) -> usize {
let hits = (output_chars / 80).max(1);
let grep = hits.saturating_mul(120);
let windows = (hits / 5 + 1).saturating_mul(competent_manual_baseline_chars(4000));
grep.saturating_add(windows).max(output_chars)
}
pub fn compact_savings_footer(response_chars: usize, raw_chars: usize) -> String {
crate::index_lifecycle::guidance::read_context::compact_savings_footer(
response_chars,
raw_chars,
)
}
pub use crate::index_lifecycle::guidance::source::format_session_cache_hit_body;
pub use crate::index_lifecycle::guidance::file_read::append_dedup_hint_footer;
pub(crate) fn format_hook_adoption(snap: &HookAdoptionSnapshot) -> String {
if snap.is_empty() {
return String::new();
}
let total = snap.total_attempts();
let routed = snap.total_routed();
let percent = if total == 0 {
0
} else {
((routed as f64 / total as f64) * 100.0).round() as usize
};
let mut lines = vec![
"── Hook Adoption (current session) ──".to_string(),
format!("Owned workflows routed: {routed}/{total} ({percent}%)"),
];
let total_no_sidecar = snap.source_read.no_sidecar
+ snap.source_search.no_sidecar
+ snap.repo_start.no_sidecar
+ snap.prompt_context.no_sidecar
+ snap.post_edit_impact.no_sidecar;
let total_sidecar_error = snap.source_read.sidecar_error
+ snap.source_search.sidecar_error
+ snap.repo_start.sidecar_error
+ snap.prompt_context.sidecar_error
+ snap.post_edit_impact.sidecar_error;
let fail_open_total = snap.total_fail_open();
if fail_open_total > 0 {
lines.push(format!(
"Fail-open outcomes: {fail_open_total} (no sidecar {total_no_sidecar}, sidecar errors {total_sidecar_error})"
));
} else {
lines.push("Fail-open outcomes: 0".to_string());
}
let total_daemon = snap.source_read.daemon_fallback
+ snap.source_search.daemon_fallback
+ snap.repo_start.daemon_fallback
+ snap.prompt_context.daemon_fallback
+ snap.post_edit_impact.daemon_fallback;
if total_daemon > 0 {
lines.push(format!("Daemon fallback routed: {total_daemon}"));
lines.push(
"Daemon fallback counts as routed work: the hook reached the daemon even though the sidecar was unavailable."
.to_string(),
);
}
let mut push_workflow_line =
|label: &str, counts: &crate::cli::hook::WorkflowAdoptionCounts| {
if counts.total() == 0 {
return;
}
let mut parts = vec![format!("routed {}", counts.routed)];
if counts.daemon_fallback > 0 {
parts.push(format!("daemon fallback {}", counts.daemon_fallback));
}
if counts.fail_open() > 0 && counts.no_sidecar > 0 {
parts.push(format!("no sidecar {}", counts.no_sidecar));
}
if counts.fail_open() > 0 && counts.sidecar_error > 0 {
parts.push(format!("sidecar errors {}", counts.sidecar_error));
}
lines.push(format!("{label}: {}", parts.join(", ")));
};
push_workflow_line("Source read", &snap.source_read);
push_workflow_line("Source search", &snap.source_search);
push_workflow_line("Repo start", &snap.repo_start);
push_workflow_line("Prompt context", &snap.prompt_context);
push_workflow_line("Post-edit impact", &snap.post_edit_impact);
if let Some(first) = snap.first_repo_start {
lines.push(format!("First repo start: {}", first.label()));
}
if snap.total_fail_open() > 0
&& snap.total_routed() == 0
&& total_daemon == 0
&& total_sidecar_error == 0
{
lines.push(String::new());
lines.push("⚠ All hook attempts failed open (no sidecar found).".to_string());
lines.push(" Start SymForge as an MCP server or run 'symforge daemon start'.".to_string());
} else if fail_open_total > 0 && total_sidecar_error == 0 {
lines.push(String::new());
lines.push(
"Fail-open here is mostly benign: hooks fired before a sidecar was reachable or on workflows intentionally left pass-through."
.to_string(),
);
} else if total_sidecar_error > 0 {
lines.push(String::new());
lines.push(
"Actionable note: sidecar errors are real routing failures and worth investigating separately from no-sidecar outcomes."
.to_string(),
);
}
lines.join("\n")
}
pub use crate::index_lifecycle::guidance::search_render::{
ExploreResultViewInput, explore_result_view,
};
pub use crate::index_lifecycle::guidance::file_impact::co_changes_result_view;
pub use crate::index_lifecycle::guidance::edit_plan::edit_impact_summary;
pub use crate::index_lifecycle::guidance::edit_body::impact_footer;
pub fn diff_symbols_result_view(
base: &str,
target: &str,
changed_files: &[&str],
repo: &crate::git::GitRepo,
live: &crate::live_index::LiveIndex,
compact: bool,
summary_only: bool,
) -> String {
let view = crate::index_lifecycle::guidance::changes::capture_symbol_diff(
base,
target,
changed_files,
|reference, path| {
if reference.is_empty() {
crate::protocol::read_gate::admit_worktree_text(live, repo, path)
} else {
crate::protocol::read_gate::admit_git_text(live, repo, reference, path)
}
},
);
crate::index_lifecycle::guidance::changes::render_symbol_diff(&view, compact, summary_only)
}
#[cfg(test)]
pub(crate) use crate::index_lifecycle::guidance::symbol_context::extract_declaration_name;
#[cfg(test)]
mod sfb15_tests {
use super::*;
#[test]
fn impact_footer_elides_partner_paths_carrying_classifier_sentinels() {
let footer = impact_footer(
2,
&[
"src/unavailable.rs".to_string(),
"src/protocol/format.rs".to_string(),
],
);
assert!(
!footer.contains("unavailable"),
"footer must not carry a sentinel-bearing partner path: {footer}"
);
assert!(
footer.contains("src/protocol/format.rs"),
"safe partner should remain: {footer}"
);
assert!(footer.starts_with("[impact: 2 dependents"));
let all_filtered = impact_footer(3, &["build/unavailable_state.rs".to_string()]);
assert_eq!(all_filtered, "[impact: 3 dependents]");
}
#[test]
fn explore_result_view_filters_weak_trivial_symbols_and_doc_only_patterns() {
let symbol_hits = vec![
(
"new".to_string(),
"fn".to_string(),
"src/cache/builder.rs".to_string(),
),
(
"TokenCache".to_string(),
"struct".to_string(),
"src/cache/token_cache.rs".to_string(),
),
];
let text_hits = vec![
(
"src/cache/token_cache.rs".to_string(),
"/// Token cache mentions authentication.".to_string(),
1,
),
(
"src/cache/token_cache.rs".to_string(),
"let cache = TokenCache::new();".to_string(),
8,
),
];
let related_files = vec![("src/cache/token_cache.rs".to_string(), 2)];
let symbol_scores = vec![0.20, 0.95];
let output = explore_result_view(ExploreResultViewInput {
label: "cache",
symbol_hits: &symbol_hits,
text_hits: &text_hits,
related_files: &related_files,
enriched_symbols: &[],
symbol_impls: &[],
symbol_deps: &[],
derived_seed_terms: &[],
derived_symbols: &[],
derived_seed_files: &[],
enriched_imports: &[],
symbol_scores: &symbol_scores,
depth: 1,
});
assert!(
!output.contains("fn new"),
"weak trivial symbol should be filtered: {output}"
);
assert!(
output.contains("struct TokenCache"),
"high-signal project symbol should remain visible: {output}"
);
assert!(
output.contains("reason: strong match"),
"visible suggestions should carry concise reason text: {output}"
);
assert!(
!output.contains("/// Token cache"),
"doc-only pattern hit should be filtered from explore guidance: {output}"
);
assert!(
output.contains("let cache = TokenCache::new();"),
"real code pattern should remain visible: {output}"
);
}
#[test]
fn explore_result_view_keeps_trivial_symbol_when_strongly_contextualized() {
let symbol_hits = vec![(
"new".to_string(),
"fn".to_string(),
"src/cache/builder.rs".to_string(),
)];
let symbol_scores = vec![0.92];
let output = explore_result_view(ExploreResultViewInput {
label: "builder",
symbol_hits: &symbol_hits,
text_hits: &[],
related_files: &[],
enriched_symbols: &[],
symbol_impls: &[],
symbol_deps: &[],
derived_seed_terms: &[],
derived_symbols: &[],
derived_seed_files: &[],
enriched_imports: &[],
symbol_scores: &symbol_scores,
depth: 1,
});
assert!(
output.contains("fn new"),
"strongly contextualized trivial symbol should remain visible: {output}"
);
assert!(
output.contains("reason: strong match"),
"kept trivial symbol should explain why it was suggested: {output}"
);
}
}
#[cfg(test)]
mod tests;