From 14b14f6e69782f83d1061321bf1277e6d2d0b2b9 Mon Sep 17 00:00:00 2001 From: "Anaz S. Aji" <12648688+ajianaz@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:15:31 +0000 Subject: [PATCH] refactor: remove the dead code hidden behind allow(dead_code) Closes #790. --- CHANGELOG.md | 1 + docs/cli-reference.md | 2 +- src/commands/agent_config.rs | 48 +--------- src/commands/install.rs | 63 ------------- src/commands/query.rs | 4 +- src/engine/bundling/grouping.rs | 1 - src/engine/bundling/mod.rs | 5 +- src/engine/bundling/types.rs | 1 - src/engine/context/resolver.rs | 16 +--- src/engine/context/types.rs | 5 +- src/engine/diff_parser.rs | 2 +- src/engine/index_bridge.rs | 28 +----- src/engine/language_analyzer.rs | 2 +- src/engine/memory.rs | 4 +- src/engine/postprocess.rs | 2 +- src/engine/profiles.rs | 4 +- src/engine/rules/mod.rs | 8 +- src/engine/secrets_scanner.rs | 7 +- src/engine/security_scanner.rs | 7 +- src/engine/types.rs | 157 +------------------------------- src/error.rs | 21 ----- src/git/diff.rs | 12 --- src/hook/install.rs | 17 ---- src/index/ast.rs | 32 +------ src/index/extract.rs | 41 +-------- src/index/graph.rs | 62 +------------ src/index/mod.rs | 2 - src/index/schema.rs | 2 +- src/index/session.rs | 3 +- src/index/symbols.rs | 3 +- src/main.rs | 5 +- src/mcp/mod.rs | 18 ---- src/mcp/tools.rs | 1 - 33 files changed, 62 insertions(+), 524 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 804943d9..b9141517 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **Dead code removed (#790).** About 500 lines that nothing used are gone, among them the YAML agent-config path, an unused `IssueType` enum, unused graph helpers and five error variants that were never created, and the 60 `#[allow(dead_code)]` attributes that hid them. The compiler now reports unused code again; the few items that are written but not wired in yet carry a narrow, commented allow that points to #792. `cora install --yes` is still accepted but has no effect (`install` never asks questions), and its help says so. - **A README and docs that are easier to read.** The README opens with a diagram of how cora works and a three-command quick start, groups the features (review, code intelligence, agents and CI), tucks upgrade and Gatekeeper details into a collapsed section and shows the timings as a chart next to the table. `docs/usage.md` shows how a review runs and `docs/agent-integration.md` how an agent uses cora, each with a diagram. The four SVG diagrams (`docs/public/diagrams/`) carry their own light and dark colors, a title and a description, and are checked by `tests/docs_drift.rs` (accessible, self-contained, used somewhere, and the chart matches the README table). ### Fixed diff --git a/docs/cli-reference.md b/docs/cli-reference.md index e625691f..6bbd340a 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -47,7 +47,7 @@ Complete command reference for the cora CLI. | `cora install --agents` `"cline,cursor"` | Install specific agents | | `cora install --dry-run` | Show what would be changed | | `cora install --force` | Overwrite existing cora entry | -| `cora install --yes` | Install ALL detected agents (non-interactive) | +| `cora install --yes` | Accepted for compatibility: `cora install` already installs every detected agent without asking | | `cora mcp` | Start the MCP server (22 tools, incl. agent-as-reviewer: `cora.review_prepare`/`review_finalize`, `cora.scan_prepare`/`scan_finalize`; no LLM key needed in cora). See [Review with your agent](./usage#review-with-your-agent-no-llm-setup) | | `claude mcp add cora -- cora mcp` | Register the MCP server with Claude Code (`cora install` only adds its `/cora-review` skill) | | `cora hook install` | Install pre-commit hook | diff --git a/src/commands/agent_config.rs b/src/commands/agent_config.rs index afbedae0..767c1755 100644 --- a/src/commands/agent_config.rs +++ b/src/commands/agent_config.rs @@ -16,8 +16,6 @@ use std::path::Path; pub enum ConfigFormat { Json, Jsonc, - #[allow(dead_code)] - Yaml, } /// The Cora MCP server entry injected into agent configs. @@ -205,7 +203,6 @@ pub fn json_add_cora(config: &mut serde_json::Value) -> Result<()> { } /// Remove the `mcpServers.cora` entry. Returns `true` if it was present. -#[allow(dead_code)] pub fn json_remove_cora(config: &mut serde_json::Value) -> bool { if let Some(servers) = config.get_mut("mcpServers").and_then(|m| m.as_object_mut()) { servers.remove("cora").is_some() @@ -216,21 +213,8 @@ pub fn json_remove_cora(config: &mut serde_json::Value) -> bool { // ─── Public API: YAML ──────────────────────────────────────────────── -/// Read a YAML config file into a `serde_yaml_ng::Value`. -pub fn read_yaml_config(path: &Path) -> Result { - let raw = fs_read(path)?; - let no_bom = strip_bom(&raw); - serde_yaml_ng::from_str(no_bom) - .with_context(|| format!("Failed to parse YAML in {}", path.display())) -} - -/// Write a YAML config. -pub fn write_yaml_config(path: &Path, config: &serde_yaml_ng::Value) -> Result<()> { - let output = serde_yaml_ng::to_string(config)?; - fs_write(path, &output) -} - /// Check whether a YAML config already contains a `mcpServers.cora` entry. +#[cfg(test)] pub fn yaml_has_cora(config: &serde_yaml_ng::Value) -> bool { config .get("mcpServers") @@ -239,6 +223,7 @@ pub fn yaml_has_cora(config: &serde_yaml_ng::Value) -> bool { } /// Insert or overwrite the `mcpServers.cora` entry in a YAML config. +#[cfg(test)] pub fn yaml_add_cora(config: &mut serde_yaml_ng::Value) -> Result<()> { let mapping = config .as_mapping_mut() @@ -267,7 +252,7 @@ pub fn yaml_add_cora(config: &mut serde_yaml_ng::Value) -> Result<()> { } /// Remove the `mcpServers.cora` entry from YAML. Returns `true` if present. -#[allow(dead_code)] +#[cfg(test)] pub fn yaml_remove_cora(config: &mut serde_yaml_ng::Value) -> bool { if let Some(mapping) = config .get_mut("mcpServers") @@ -282,33 +267,6 @@ pub fn yaml_remove_cora(config: &mut serde_yaml_ng::Value) -> bool { // ─── Format-agnostic helpers ───────────────────────────────────────── -/// Read a config file, dispatching on the detected format. -#[allow(dead_code)] -pub fn read_config(path: &Path, format: ConfigFormat) -> Result { - match format { - ConfigFormat::Json | ConfigFormat::Jsonc => read_json_config(path), - ConfigFormat::Yaml => { - let yaml = read_yaml_config(path)?; - // Convert YAML → JSON for a unified return type - let json_str = serde_yaml_ng::to_string(&yaml)?; - Ok(serde_json::from_str(&json_str)?) - } - } -} - -/// Write a config file in the specified format. -#[allow(dead_code)] -pub fn write_config(path: &Path, format: ConfigFormat, config: &serde_json::Value) -> Result<()> { - match format { - ConfigFormat::Json | ConfigFormat::Jsonc => write_json_config(path, config), - ConfigFormat::Yaml => { - let yaml_str = serde_json::to_string(config)?; - let yaml: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_str)?; - write_yaml_config(path, &yaml) - } - } -} - // ─── File I/O wrappers with context ────────────────────────────────── fn fs_read(path: &Path) -> Result { diff --git a/src/commands/install.rs b/src/commands/install.rs index 55491af1..e236b579 100644 --- a/src/commands/install.rs +++ b/src/commands/install.rs @@ -28,9 +28,6 @@ pub struct InstallOptions { pub dry_run: bool, /// Overwrite existing cora entry. pub force: bool, - /// Non-interactive mode. - #[allow(dead_code)] - pub yes: bool, /// Remove cora MCP entry (uninstall mode). pub remove: bool, /// Validate agent configs after install/remove. @@ -192,58 +189,6 @@ fn install_agent(agent: &AgentInfo, opts: &InstallOptions) -> Result { install_json_agent(&agent.config_path, opts.force, opts.dry_run) } } - ConfigFormat::Yaml => { - use super::agent_config; - let mut config = agent_config::read_yaml_config(&agent.config_path)?; - - if opts.remove { - if !agent_config::yaml_has_cora(&config) { - return Ok(format!( - " {} {} — no cora entry found", - "⏭ ".dimmed(), - agent.config_path.display() - )); - } - agent_config::yaml_remove_cora(&mut config); - if opts.dry_run { - Ok(format!( - " {} {} — would remove cora MCP server entry", - "🔍 ".cyan(), - agent.config_path.display() - )) - } else { - agent_config::write_yaml_config(&agent.config_path, &config)?; - Ok(format!( - " {} {} — cora MCP server entry removed", - "✓ ".green(), - agent.config_path.display() - )) - } - } else { - if agent_config::yaml_has_cora(&config) && !opts.force { - return Ok(format!( - " {} {} — cora entry already exists (use --force to overwrite)", - "⏭ ".dimmed(), - agent.config_path.display() - )); - } - agent_config::yaml_add_cora(&mut config)?; - if opts.dry_run { - Ok(format!( - " {} {} — would write cora MCP server entry", - "🔍 ".cyan(), - agent.config_path.display() - )) - } else { - agent_config::write_yaml_config(&agent.config_path, &config)?; - Ok(format!( - " {} {} — cora MCP server entry added", - "✓ ".green(), - agent.config_path.display() - )) - } - } - } } } @@ -426,13 +371,6 @@ pub fn execute_install(opts: &InstallOptions) -> Result { )); } } - ConfigFormat::Yaml => { - lines.push(format!( - " {} {} — skipped (YAML validation not implemented)", - "⏭ ".dimmed(), - agent.config_path.display() - )); - } } } if errors > 0 { @@ -469,7 +407,6 @@ mod tests { agents: None, dry_run: false, force: false, - yes: true, remove: false, validate: false, } diff --git a/src/commands/query.rs b/src/commands/query.rs index 1e20a9a5..35323b87 100644 --- a/src/commands/query.rs +++ b/src/commands/query.rs @@ -411,8 +411,8 @@ mod tests { (conn, pid) } - fn edge(caller: &str, callee: &str, line: u32) -> crate::index::CallEdge { - crate::index::CallEdge { + fn edge(caller: &str, callee: &str, line: u32) -> crate::index::graph::CallEdge { + crate::index::graph::CallEdge { caller: caller.into(), callee: callee.into(), file: "src/main.rs".into(), diff --git a/src/engine/bundling/grouping.rs b/src/engine/bundling/grouping.rs index 01c8658f..52aaa606 100644 --- a/src/engine/bundling/grouping.rs +++ b/src/engine/bundling/grouping.rs @@ -1,4 +1,3 @@ -#[allow(dead_code)] /// Grouping strategies for bundling files into LLM-friendly groups. use std::collections::HashMap; diff --git a/src/engine/bundling/mod.rs b/src/engine/bundling/mod.rs index 98004017..419b93ea 100644 --- a/src/engine/bundling/mod.rs +++ b/src/engine/bundling/mod.rs @@ -1,4 +1,3 @@ -#[allow(dead_code, unused)] /// File bundling engine — groups files into cohesive units for LLM review. /// /// Instead of arbitrary batching by character count alone, the bundling engine @@ -26,8 +25,10 @@ /// // send content to LLM /// } /// ``` +// The grouping engine is not called by review yet (#792). +#[allow(dead_code)] pub mod grouping; +#[allow(dead_code)] pub mod types; -#[allow(dead_code, unused)] pub use types::GroupingStrategy; diff --git a/src/engine/bundling/types.rs b/src/engine/bundling/types.rs index 51ba395c..a0d7a2fb 100644 --- a/src/engine/bundling/types.rs +++ b/src/engine/bundling/types.rs @@ -1,4 +1,3 @@ -#[allow(dead_code)] /// Bundling types — configuration and data structures for file grouping. use serde::{Deserialize, Serialize}; diff --git a/src/engine/context/resolver.rs b/src/engine/context/resolver.rs index e4205f42..1ed26eaa 100644 --- a/src/engine/context/resolver.rs +++ b/src/engine/context/resolver.rs @@ -734,13 +734,6 @@ fn find_fn_in_file_cached( find_pattern_with_body(&content, &pattern, MAX_FN_LINES) } -/// Generic function search (for languages without specific patterns). -#[allow(dead_code)] -fn find_fn_generic(path: &Path, name: &str) -> Option<(u32, u32)> { - let content = std::fs::read_to_string(path).ok()?; - find_pattern_with_body(&content, &format!("fn {name}"), MAX_FN_LINES) -} - /// Cached version of `find_fn_generic`. fn find_fn_generic_cached( path: &Path, @@ -751,13 +744,6 @@ fn find_fn_generic_cached( find_pattern_with_body(&content, &format!("fn {name}"), MAX_FN_LINES) } -/// Find a pattern (like `struct Foo`) and determine its extent. -#[allow(dead_code)] -fn find_pattern_in_file(path: &Path, pattern: &str) -> Option<(u32, u32)> { - let content = std::fs::read_to_string(path).ok()?; - find_pattern_with_body(&content, pattern, MAX_TYPE_LINES) -} - /// Cached version of `find_pattern_in_file`. fn find_pattern_in_file_cached( path: &Path, @@ -907,7 +893,7 @@ fn find_go_package_file(dir: &Path, import_path: &str) -> Option { /// never scanned, and is bounded by [`MAX_CALLER_FILES_SCAN`] files and /// [`MAX_CALLERS_PER_SYMBOL`] call-sites per symbol. Caller slices are tiny /// (the call line + 1 line of context) to stay token-economical. -#[allow(dead_code)] +#[cfg(test)] fn resolve_callers( defs: &[DefinedSymbol], config: &ContextConfig, diff --git a/src/engine/context/types.rs b/src/engine/context/types.rs index dccae4e8..7eb5a459 100644 --- a/src/engine/context/types.rs +++ b/src/engine/context/types.rs @@ -131,15 +131,16 @@ impl std::fmt::Display for SymbolKind { /// A single symbol extracted from a changed line, with source location. #[derive(Debug, Clone)] -#[allow(dead_code)] // fields consumed in v0.5 when bundling wired pub struct ExtractedSymbol { /// What kind of symbol this is. pub kind: SymbolKind, /// The file path where the symbol was found. pub file: String, /// Line number in the file (1-indexed). + #[allow(dead_code)] // set, never read until bundling is wired (#792) pub line: u32, /// The raw text that matched (for debugging). + #[allow(dead_code)] // same (#792) pub raw: String, } @@ -210,11 +211,11 @@ pub struct ContextStats { /// The fully assembled context chain, ready for prompt injection. #[derive(Debug, Clone, Default)] -#[allow(dead_code)] // stats consumed in v0.5 when bundling wired pub struct ContextChain { /// Formatted text to inject into the prompt. pub text: String, /// Build statistics. + #[allow(dead_code)] // set, never read until bundling is wired (#792) pub stats: ContextStats, } diff --git a/src/engine/diff_parser.rs b/src/engine/diff_parser.rs index ba09da6e..b00ea070 100644 --- a/src/engine/diff_parser.rs +++ b/src/engine/diff_parser.rs @@ -302,7 +302,7 @@ pub fn detect_language(path: &str) -> &'static str { /// Extract all added lines from parsed file chunks. /// /// Returns `(file_path, line_number, content)` triples. -#[allow(dead_code)] // used by bundling in v0.5 +#[allow(dead_code)] // for the bundling engine, not wired yet (#792) pub fn extract_added_lines(chunks: &[FileChunk]) -> Vec<(String, u32, String)> { let mut result = Vec::new(); diff --git a/src/engine/index_bridge.rs b/src/engine/index_bridge.rs index 92393cf0..f7527d02 100644 --- a/src/engine/index_bridge.rs +++ b/src/engine/index_bridge.rs @@ -189,8 +189,8 @@ impl IndexBridge { } /// The resolved project id (if available). - #[allow(dead_code)] #[inline] + #[cfg(test)] pub fn project_id(&self) -> Option { self.project_id } @@ -264,7 +264,7 @@ impl IndexBridge { /// /// Returns up to `limit` [`crate::index::brain::BrainResult`] entries. /// Returns an empty vec if the bridge is unavailable. - #[allow(dead_code)] + #[cfg(test)] pub fn brain_search(&self, query: &str, limit: usize) -> Vec { let conn = match self.conn.as_ref() { Some(c) => c, @@ -278,34 +278,12 @@ impl IndexBridge { crate::index::brain::brain_search(conn, pid, query, limit).unwrap_or_default() } - /// Run an impact analysis (blast radius) for the given symbol. - /// - /// Returns [`crate::index::graph::ImpactNode`] entries up to `depth`. - /// Returns an empty vec if the bridge is unavailable. - #[allow(dead_code)] - pub fn impact_analysis( - &self, - symbol_name: &str, - depth: u32, - ) -> Vec { - let conn = match self.conn.as_ref() { - Some(c) => c, - None => return Vec::new(), - }; - let pid = match self.project_id { - Some(id) => id, - None => return Vec::new(), - }; - - crate::index::graph::impact_analysis(conn, pid, symbol_name, depth).unwrap_or_default() - } - /// Direct access to the underlying connection (if available). /// /// Used by callers that need raw SQL beyond the typed helpers above. /// Returns `None` if the bridge is unavailable. - #[allow(dead_code)] #[inline] + #[cfg(test)] pub fn connection(&self) -> Option<&Connection> { self.conn.as_ref() } diff --git a/src/engine/language_analyzer.rs b/src/engine/language_analyzer.rs index 477fc490..496d5379 100644 --- a/src/engine/language_analyzer.rs +++ b/src/engine/language_analyzer.rs @@ -28,7 +28,7 @@ pub fn build_language_context_from_chunks(chunks: &[diff_parser::FileChunk]) -> } /// Build language-specific context string from raw diff text. -#[allow(dead_code)] +#[cfg(test)] pub fn build_language_context(diff_text: &str) -> String { let chunks = diff_parser::parse_diff(diff_text); let languages = detect_languages(&chunks); diff --git a/src/engine/memory.rs b/src/engine/memory.rs index b1acecfe..b279c304 100644 --- a/src/engine/memory.rs +++ b/src/engine/memory.rs @@ -36,7 +36,7 @@ impl Default for MemoryBackend { impl MemoryBackend { /// Create a new memory backend with the given namespace. - #[allow(dead_code)] + #[cfg(test)] pub fn new(namespace: &str) -> Self { Self { enabled: false, @@ -135,7 +135,7 @@ impl MemoryBackend { /// Save false positive feedback to Uteke. /// /// Calls: `uteke remember "cora:{project}:fp:{issue_id}" --tags cora,false-positive` - #[allow(dead_code)] + #[cfg(test)] pub fn save_feedback(&self, project: &str, issue_id: &str, feedback: &str) { if !self.enabled { return; diff --git a/src/engine/postprocess.rs b/src/engine/postprocess.rs index fbce8562..939b3a00 100644 --- a/src/engine/postprocess.rs +++ b/src/engine/postprocess.rs @@ -64,7 +64,7 @@ pub struct PostprocessReport { /// Run the shared post-processing pipeline over `issues`. See the module docs /// for the per-source filter table. Drops the truncation count; use /// [`postprocess_report`] when the caller should surface it. -#[cfg_attr(not(test), allow(dead_code))] // callers use postprocess_report; kept for tests/API +#[cfg(test)] pub fn postprocess( issues: Vec, source: &Source<'_>, diff --git a/src/engine/profiles.rs b/src/engine/profiles.rs index f2fb3aa6..de1baa16 100644 --- a/src/engine/profiles.rs +++ b/src/engine/profiles.rs @@ -194,7 +194,7 @@ pub fn parse_profile_yaml(yaml: &str) -> Result { } /// Load all built-in profiles. -#[allow(dead_code)] +#[cfg(test)] pub fn load_all_builtins() -> Vec { BUILTIN_PROFILES .iter() @@ -297,7 +297,7 @@ pub fn resolve_profile_with_root( /// Auto-detect a profile based on project language. /// Returns the best-matching built-in profile name. -#[allow(dead_code)] +#[cfg(test)] pub fn auto_detect_profile(language: &str) -> &'static str { match language { "rs" => "rust-strict", diff --git a/src/engine/rules/mod.rs b/src/engine/rules/mod.rs index 01ddc84c..b53d39ce 100644 --- a/src/engine/rules/mod.rs +++ b/src/engine/rules/mod.rs @@ -6,9 +6,12 @@ pub mod types; use tracing::debug; +#[cfg(test)] use crate::engine::diff_parser::{FileChunk, parse_diff}; use crate::engine::rules::types::{CustomRule, RuleFinding, RulesConfig}; -use crate::engine::scan_input::{self, ScanFile}; +#[cfg(test)] +use crate::engine::scan_input; +use crate::engine::scan_input::ScanFile; use crate::engine::types::{ReviewIssue, Severity}; /// Map severity to a numeric rank for sorting (Critical=4, Major=3, Minor=2, Info=1). @@ -25,6 +28,7 @@ fn severity_rank(sev: Severity) -> u8 { /// chunks (diff adapter over [`run_rules_in`]). /// /// Returns findings capped by `config.max_findings`. +#[cfg(test)] pub fn run_rules(chunks: &[FileChunk], config: &RulesConfig) -> Vec { run_rules_in(&scan_input::from_chunks(chunks), config) } @@ -382,7 +386,7 @@ pub fn format_rule_context(findings: &[RuleFinding]) -> String { } /// Convenience: parse diff + run rules in one step. -#[allow(dead_code)] // public API for future standalone usage +#[cfg(test)] pub fn parse_and_run_rules(diff: &str, config: &RulesConfig) -> Vec { let chunks = parse_diff(diff); run_rules(&chunks, config) diff --git a/src/engine/secrets_scanner.rs b/src/engine/secrets_scanner.rs index 968a336b..fcbac9c9 100644 --- a/src/engine/secrets_scanner.rs +++ b/src/engine/secrets_scanner.rs @@ -5,9 +5,12 @@ use std::sync::LazyLock; use tracing::debug; use crate::engine::Severity; +#[cfg(test)] use crate::engine::diff_parser::FileChunk; use crate::engine::rules::types::RuleFinding; -use crate::engine::scan_input::{self, ScanFile}; +#[cfg(test)] +use crate::engine::scan_input; +use crate::engine::scan_input::ScanFile; // ─── Built-in secret patterns ─── @@ -113,7 +116,7 @@ static TEST_FIXTURE_RE: LazyLock = LazyLock::new(|| { /// /// Returns findings capped at `max_findings`. Secret values are masked in the /// message body. -#[cfg_attr(not(test), allow(dead_code))] // callers use scan_secrets_in; kept for tests/API +#[cfg(test)] pub fn scan_secrets(chunks: &[FileChunk], max_findings: usize) -> Vec { scan_secrets_in(&scan_input::from_chunks(chunks), max_findings) } diff --git a/src/engine/security_scanner.rs b/src/engine/security_scanner.rs index 1fc718f2..4e5b541a 100644 --- a/src/engine/security_scanner.rs +++ b/src/engine/security_scanner.rs @@ -9,10 +9,13 @@ use std::sync::LazyLock; use tracing::debug; use crate::engine::Severity; +#[cfg(test)] use crate::engine::diff_parser::FileChunk; use crate::engine::rules::builtin::post_match_filter_for_path; use crate::engine::rules::types::RuleFinding; -use crate::engine::scan_input::{self, ScanFile}; +#[cfg(test)] +use crate::engine::scan_input; +use crate::engine::scan_input::ScanFile; // ─── Security patterns ─── @@ -169,7 +172,7 @@ static COMPILED_PATTERNS: LazyLock> = Laz /// /// Only scans added lines (not removed/context) to reduce false positives. /// Returns findings sorted by severity (worst first). -#[cfg_attr(not(test), allow(dead_code))] // callers use scan_security_in; kept for tests/API +#[cfg(test)] pub fn scan_security(chunks: &[FileChunk], max_findings: usize) -> Vec { scan_security_in(&scan_input::from_chunks(chunks), max_findings) } diff --git a/src/engine/types.rs b/src/engine/types.rs index 734d444e..769920f6 100644 --- a/src/engine/types.rs +++ b/src/engine/types.rs @@ -73,56 +73,6 @@ impl fmt::Display for Severity { } } -/// Issue type categories. -/// -/// Kept for API completeness — used for deserialization and future typed -/// issue-type matching. Currently the LLM returns `issue_type` as a string, -/// but this enum provides a structured alternative. -#[allow(dead_code)] -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum IssueType { - Security, - Performance, - Bug, - BestPractice, - Style, - Suggestion, -} - -#[allow(dead_code)] -impl fmt::Display for IssueType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - IssueType::Security => write!(f, "security"), - IssueType::Performance => write!(f, "performance"), - IssueType::Bug => write!(f, "bug"), - IssueType::BestPractice => write!(f, "best_practice"), - IssueType::Style => write!(f, "style"), - IssueType::Suggestion => write!(f, "suggestion"), - } - } -} - -#[allow(dead_code)] -impl IssueType { - /// Parse from string with lenient matching (accepts plural forms, etc.) - pub fn from_str_lossy(s: &str) -> Self { - match s.to_lowercase().as_str() { - "security" | "sec" => IssueType::Security, - "performance" | "perf" => IssueType::Performance, - "bug" | "bugs" => IssueType::Bug, - "best_practice" | "best-practice" | "bestpractice" | "best practice" => { - IssueType::BestPractice - } - "style" | "formatting" => IssueType::Style, - // suggestion/info merged into wildcard — all three arms returned - // identical IssueType::Suggestion, verified by clippy match_same_arms - _ => IssueType::Suggestion, - } - } -} - /// Read a severity the way a model writes it. A synonym (`high`, `warning`) /// maps to its level; a word that is not a severity (`"performance"`, a /// category in the wrong field) must not make the whole batch fail to parse, so @@ -299,102 +249,6 @@ mod tests { assert!(!Severity::Info.icon().is_empty()); } - // ─── IssueType::from_str_lossy ─── - - #[test] - fn issue_type_security() { - assert_eq!(IssueType::from_str_lossy("security"), IssueType::Security); - } - - #[test] - fn issue_type_sec_alias() { - assert_eq!(IssueType::from_str_lossy("sec"), IssueType::Security); - } - - #[test] - fn issue_type_performance() { - assert_eq!( - IssueType::from_str_lossy("performance"), - IssueType::Performance - ); - } - - #[test] - fn issue_type_perf_alias() { - assert_eq!(IssueType::from_str_lossy("perf"), IssueType::Performance); - } - - #[test] - fn issue_type_bug() { - assert_eq!(IssueType::from_str_lossy("bug"), IssueType::Bug); - } - - #[test] - fn issue_type_bugs_alias() { - assert_eq!(IssueType::from_str_lossy("bugs"), IssueType::Bug); - } - - #[test] - fn issue_type_best_practice_variants() { - assert_eq!( - IssueType::from_str_lossy("best_practice"), - IssueType::BestPractice - ); - assert_eq!( - IssueType::from_str_lossy("best-practice"), - IssueType::BestPractice - ); - assert_eq!( - IssueType::from_str_lossy("bestpractice"), - IssueType::BestPractice - ); - assert_eq!( - IssueType::from_str_lossy("best practice"), - IssueType::BestPractice - ); - } - - #[test] - fn issue_type_style() { - assert_eq!(IssueType::from_str_lossy("style"), IssueType::Style); - } - - #[test] - fn issue_type_formatting_alias() { - assert_eq!(IssueType::from_str_lossy("formatting"), IssueType::Style); - } - - #[test] - fn issue_type_suggestion() { - assert_eq!( - IssueType::from_str_lossy("suggestion"), - IssueType::Suggestion - ); - } - - #[test] - fn issue_type_info_alias() { - assert_eq!(IssueType::from_str_lossy("info"), IssueType::Suggestion); - } - - #[test] - fn issue_type_unknown_falls_back() { - assert_eq!(IssueType::from_str_lossy("xyz"), IssueType::Suggestion); - assert_eq!(IssueType::from_str_lossy(""), IssueType::Suggestion); - } - - // ─── IssueType display ─── - - #[test] - fn issue_type_display() { - assert_eq!(format!("{}", IssueType::Security), "security"); - assert_eq!(format!("{}", IssueType::Performance), "performance"); - assert_eq!(format!("{}", IssueType::Bug), "bug"); - assert_eq!(format!("{}", IssueType::BestPractice), "best_practice"); - assert_eq!(format!("{}", IssueType::Style), "style"); - assert_eq!(format!("{}", IssueType::Suggestion), "suggestion"); - } - // ─── LLMConfig::default ─── #[test] @@ -582,29 +436,26 @@ impl Default for LLMConfig { } /// CLI exit codes. -#[allow(dead_code)] pub const EXIT_OK: i32 = 0; -#[allow(dead_code)] pub const EXIT_ERROR: i32 = 1; -#[allow(dead_code)] pub const EXIT_BLOCKED: i32 = 2; -#[allow(dead_code)] +#[cfg(test)] pub const EXIT_AUTH_ERROR: i32 = 3; /// Maximum diff size in bytes (50KB by default). /// /// Kept for API completeness — future commands may enforce this limit. -#[allow(dead_code)] +#[cfg(test)] pub const MAX_DIFF_SIZE: usize = 50 * 1024; /// Maximum files per scan batch. /// /// Kept for API completeness — scanner uses matching values inline. -#[allow(dead_code)] +#[cfg(test)] pub const MAX_SCAN_BATCH_FILES: usize = 20; /// Maximum characters per scan batch. /// /// Kept for API completeness — scanner uses matching values inline. -#[allow(dead_code)] +#[cfg(test)] pub const MAX_SCAN_BATCH_CHARS: usize = 80_000; diff --git a/src/error.rs b/src/error.rs index 19bf53f3..72526d03 100644 --- a/src/error.rs +++ b/src/error.rs @@ -6,7 +6,6 @@ use thiserror::Error; /// continues to use `anyhow::Result` and converts via `?` (automatic /// `From for anyhow::Error` provided by `thiserror` + anyhow interop). #[derive(Debug, Error)] -#[allow(dead_code)] pub enum CoraError { /// HTTP request to LLM API failed (network, DNS, timeout, etc.) #[error("LLM API request failed: {0}")] @@ -24,10 +23,6 @@ pub enum CoraError { #[error("streaming error: {0}")] LlmStream(String), - /// JSON repair still failed after fix attempt. - #[error("JSON repair failed: {0}")] - LlmJsonRepair(String), - /// YAML config parse error. #[error("config parse error: {0}")] ConfigParse(String), @@ -40,10 +35,6 @@ pub enum CoraError { #[error("no API key found")] NoApiKey, - /// Diff exceeds maximum allowed size. - #[error("diff too large ({actual} chars, max {max})")] - DiffTooLarge { actual: usize, max: usize }, - /// Invalid git ref (shell metacharacters or path traversal). #[error("invalid ref: {0}")] InvalidRef(String), @@ -68,20 +59,8 @@ pub enum CoraError { #[error("cache serialize error: {0}")] CacheSerialize(String), - /// File scanner error. - #[error("scanner error: {0}")] - ScannerError(String), - /// Auth file read/write error. #[error("auth error: {0}")] AuthError(String), - - /// Hook install/uninstall error. - #[error("hook error: {0}")] - HookError(String), - - /// LLM request timed out. - #[error("LLM request timed out: {0}")] - Timeout(String), } // test comment for cora review diff --git a/src/git/diff.rs b/src/git/diff.rs index fa6502dd..59194d61 100644 --- a/src/git/diff.rs +++ b/src/git/diff.rs @@ -1,4 +1,3 @@ -use std::path::Path; use std::process::Command; use crate::error::CoraError; @@ -183,17 +182,6 @@ fn parse_remote_url(url: &str) -> (String, String) { } } -/// Check if a path is inside a git worktree. -/// -/// Kept for API completeness — useful for pre-commit hooks and future commands -/// that need to guard against running outside a repository. -#[allow(dead_code)] -pub fn is_inside_git_repo(dir: Option<&Path>) -> bool { - let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")); - let search_dir = dir.unwrap_or(&cwd); - Repository::discover(search_dir).is_ok() -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/hook/install.rs b/src/hook/install.rs index 17282712..4458ce2f 100644 --- a/src/hook/install.rs +++ b/src/hook/install.rs @@ -129,23 +129,6 @@ fn find_git_hooks_dir() -> Result { Ok(hooks_dir) } -/// Check whether the cora pre-commit hook is installed. -/// -/// Kept for API completeness — useful for future `cora hook status` and -/// guard logic in pre-commit hook template. -#[allow(dead_code)] -pub fn is_hook_installed() -> Result { - let hooks_dir = find_git_hooks_dir()?; - let hook_path = hooks_dir.join("pre-commit"); - - if !hook_path.is_file() { - return Ok(false); - } - - let content = std::fs::read_to_string(&hook_path).unwrap_or_default(); - Ok(content.contains("cora")) -} - #[cfg(test)] mod tests { use super::is_cora_managed; diff --git a/src/index/ast.rs b/src/index/ast.rs index f709fbd3..cf3c9158 100644 --- a/src/index/ast.rs +++ b/src/index/ast.rs @@ -3,8 +3,6 @@ // ! Provides proper AST-based symbol and edge extraction using tree-sitter. // ! Only compiled when the `tree-sitter` feature is enabled. -#![allow(dead_code, unused)] - use crate::index::extract::CallSite; use crate::index::extract::ExtractedDef; use crate::index::symbols::SymbolKind; @@ -23,6 +21,7 @@ pub struct AstNode { /// Full signature text. pub signature: String, /// Parent scope name (struct/class for methods). + #[allow(dead_code)] // computed at every site, never read (#792) pub parent: Option, } @@ -51,7 +50,6 @@ pub enum EdgeKind { Imports, Implements, Inherits, - ChildOf, Route, } @@ -62,7 +60,6 @@ impl EdgeKind { Self::Imports => "IMPORTS", Self::Implements => "IMPLEMENTS", Self::Inherits => "INHERITS", - Self::ChildOf => "CHILD_OF", Self::Route => "ROUTE", } } @@ -1720,23 +1717,6 @@ fn extract_c( } } } - "declaration" => { - // Top-level const/typedef etc - if let Some(decl) = child.child_by_field_name("declarator") { - // Only capture if it looks like a function pointer or named constant - let mut dc = child.walk(); - if dc.goto_first_child() { - loop { - if dc.node().kind() == "type_qualifier" { - // const — skip for now (too noisy) - } - if !dc.goto_next_sibling() { - break; - } - } - } - } - } _ => {} } } @@ -1984,11 +1964,6 @@ fn extract_csharp( loop { let base = node_text(&bc.node(), source); if !base.is_empty() { - let edge_kind = if kind == SymbolKind::Interface { - EdgeKind::Inherits - } else { - EdgeKind::Implements - }; // Heuristic: base type starting with 'I' is likely an interface let ek = if base.starts_with('I') && base @@ -2218,7 +2193,7 @@ fn extract_ruby( node: &tree_sitter::Node, source: &str, file_path: &str, - mut nodes: &mut Vec, + nodes: &mut Vec, edges: &mut Vec, ) { match node.kind() { @@ -2274,6 +2249,9 @@ fn extract_ruby( extract_methods_from_ruby_node(node, source, file_path, &name, nodes); } } + // Unreachable today: the "module" arm above shadows this one, so methods inside a + // Ruby module are not indexed (#791). That fix removes the arm above and this allow. + #[allow(unreachable_patterns)] "module" => { let name = if let Some(n) = node.child_by_field_name("name") { node_text(&n, source) diff --git a/src/index/extract.rs b/src/index/extract.rs index 797473a5..78f0b1e3 100644 --- a/src/index/extract.rs +++ b/src/index/extract.rs @@ -501,25 +501,12 @@ fn extract_svelte(content: &str, file: &str, out: &mut Vec) { } } -/// Extract function call sites from source code. +/// Regex-based call-site extraction with scope tracking. /// -/// When the `tree-sitter` feature is enabled, uses AST-based extraction for -/// supported languages. Falls back to regex-based scope tracking for others. -#[allow(dead_code)] +/// Used when the `tree-sitter` feature is off; with it, the AST extractor +/// (`ast::extract`) records the calls. +#[cfg(not(feature = "tree-sitter"))] pub fn extract_calls(content: &str, language: &str, file_path: &str) -> Vec { - #[cfg(feature = "tree-sitter")] - { - use super::ast; - if ast::get_language(language).is_some() || language == "svelte" { - let (_nodes, edges) = ast::extract(content, language, file_path); - return edges - .into_iter() - .filter(|e| e.kind == ast::EdgeKind::Calls) - .map(Into::into) - .collect(); - } - } - // Regex fallback use crate::engine::context::extraction as ctx_extract; use crate::engine::context::types::SymbolKind as CtxSymbolKind; @@ -583,24 +570,6 @@ pub fn extract_calls(content: &str, language: &str, file_path: &str) -> Vec Vec { - use super::ast; - if ast::get_language(language).is_some() || language == "svelte" { - let (_nodes, edges) = ast::extract(content, language, file_path); - return edges; - } - Vec::new() -} - /// Detect HTTP route definitions from source code using regex heuristics. /// /// Catches common route registration patterns across frameworks: @@ -856,7 +825,6 @@ fn is_builtin(name: &str) -> bool { /// All extracted data from a single file (symbols + calls + kg edges). /// Used by bulk indexing to parse tree-sitter only once. #[derive(Debug, Clone, Default)] -#[allow(dead_code)] pub struct ExtractedAll { pub symbols: Vec, pub calls: Vec, @@ -870,7 +838,6 @@ pub type KgEdge = crate::index::ast::AstEdge; /// A knowledge-graph edge stub when tree-sitter is disabled (never used). #[cfg(not(feature = "tree-sitter"))] #[derive(Debug, Clone, Default)] -#[allow(dead_code)] pub struct KgEdge { pub source: String, pub kind: String, diff --git a/src/index/graph.rs b/src/index/graph.rs index 07d779c1..275ac1cd 100644 --- a/src/index/graph.rs +++ b/src/index/graph.rs @@ -10,8 +10,8 @@ use super::dead_filters; use super::symbols::{IndexedSymbol, SymbolKind}; /// A directed edge in the call graph: caller → callee. -#[allow(dead_code)] #[derive(Debug, Clone)] +#[cfg(test)] pub struct CallEdge { /// Symbol that makes the call. pub caller: String, @@ -24,7 +24,7 @@ pub struct CallEdge { } /// Store call edges in the database, scoped to a project. -#[allow(dead_code)] +#[cfg(test)] pub fn store_edges( conn: &Connection, edges: &[CallEdge], @@ -43,60 +43,8 @@ pub fn store_edges( Ok(count) } -/// A typed edge in the knowledge graph. -#[cfg(feature = "tree-sitter")] -#[derive(Debug, Clone)] -pub struct KgEdge { - /// Source symbol. - pub source: String, - /// Edge kind: CALLS, IMPORTS, IMPLEMENTS, INHERITS, CHILD_OF. - pub kind: String, - /// Target symbol. - pub target: String, - /// File where the relationship is defined. - pub file: String, - /// Line number. - pub line: u32, -} - -/// Store knowledge graph edges in the `edges` table. -#[cfg(feature = "tree-sitter")] -#[allow(dead_code)] -pub fn store_kg_edges( - conn: &Connection, - edges: &[KgEdge], - project_id: i64, -) -> anyhow::Result { - let tx = conn.unchecked_transaction()?; - let mut count = 0; - for edge in edges { - tx.execute( - "INSERT INTO edges (source, kind, target, file, line, project_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", - rusqlite::params![edge.source, edge.kind, edge.target, edge.file, edge.line as i64, project_id], - )?; - count += 1; - } - tx.commit()?; - Ok(count) -} - -/// Clear knowledge graph edges for a specific file. -#[cfg(feature = "tree-sitter")] -#[allow(dead_code)] -pub fn clear_kg_edges_for_file( - conn: &Connection, - file: &str, - project_id: i64, -) -> anyhow::Result<()> { - conn.execute( - "DELETE FROM edges WHERE file = ?1 AND project_id = ?2", - rusqlite::params![file, project_id], - )?; - Ok(()) -} - /// Clear call graph edges for a specific file (before re-indexing), scoped to project. -#[allow(dead_code)] +#[cfg(test)] pub fn clear_edges_for_file(conn: &Connection, file: &str, project_id: i64) -> anyhow::Result<()> { conn.execute( "DELETE FROM call_graph WHERE file = ?1 AND project_id = ?2", @@ -234,7 +182,6 @@ pub fn find_callers_cross_project( /// Find all callees of a symbol (what does this call?), scoped to a project. /// /// Returns symbols that are called by the given name. -#[allow(dead_code)] pub fn find_callees( conn: &Connection, project_id: i64, @@ -350,7 +297,6 @@ pub struct CrossProjectCallerResult { } /// A callee result entry. -#[allow(dead_code)] #[derive(Debug, Clone, serde::Serialize)] pub struct CalleeResult { pub callee: String, @@ -391,12 +337,12 @@ fn call_site_types( .unwrap_or((None, None)) } -#[allow(dead_code)] /// Trace the execution path from a symbol — BFS over call_graph + edges. /// /// `symbol_name` may be `Type::name`; each hop then carries the type of the /// node it reached (the qualifier of a call, the impl type of a calling /// method), so same-named methods of other types are not merged (#743). +#[cfg(test)] pub fn trace_path( conn: &Connection, project_id: i64, diff --git a/src/index/mod.rs b/src/index/mod.rs index dffc9ddc..f919e5a9 100644 --- a/src/index/mod.rs +++ b/src/index/mod.rs @@ -27,8 +27,6 @@ use rusqlite::Connection; use sha2::{Digest, Sha256}; use tracing::{debug, info}; -#[allow(unused_imports)] -pub use graph::{CallEdge, CalleeResult, CallerResult, ImpactNode}; pub use symbols::{SearchOutcome, SearchResult, SymbolKind, SymbolQuery}; /// Open or create the **global** symbol index database. diff --git a/src/index/schema.rs b/src/index/schema.rs index 49ace81a..9ae6ae93 100644 --- a/src/index/schema.rs +++ b/src/index/schema.rs @@ -3,7 +3,7 @@ use rusqlite::Connection; /// Current schema version. -#[allow(dead_code)] +#[cfg(test)] const SCHEMA_VERSION: i32 = 9; /// Serialises index opening (PRAGMAs + migrations) within a process: several diff --git a/src/index/session.rs b/src/index/session.rs index c61868e1..0d37ac7d 100644 --- a/src/index/session.rs +++ b/src/index/session.rs @@ -40,7 +40,6 @@ pub enum ConfigSource<'a> { /// Project `.cora.yaml` only (MCP: no env/global/secrets). ProjectOnly, /// [`Self::ProjectOnly`] discovered from `start` instead of the cwd. - #[cfg_attr(not(test), allow(dead_code))] ProjectOnlyAt(&'a Path), } @@ -69,7 +68,7 @@ pub fn load_project_only(start: &Path) -> Option { /// Result of [`configure`]: what was applied to the process. #[derive(Debug, Clone)] -#[cfg_attr(not(test), allow(dead_code))] // brain_mode/backend are the test seam +#[cfg_attr(not(test), allow(dead_code))] // `brain_mode` and `backend` are the test seam pub struct Configured { /// `brain.embedding` string that was handed to `resolve_backend`. pub brain_mode: String, diff --git a/src/index/symbols.rs b/src/index/symbols.rs index 5112fc03..24954222 100644 --- a/src/index/symbols.rs +++ b/src/index/symbols.rs @@ -124,7 +124,6 @@ pub struct SymbolQuery { impl SymbolQuery { /// Create a text search query. - #[allow(dead_code)] pub fn text(text: &str) -> Self { Self { text: Some(text.to_string()), @@ -136,7 +135,7 @@ impl SymbolQuery { } /// Create a kind-filtered query. - #[allow(dead_code)] + #[cfg(test)] pub fn kind(kind: SymbolKind) -> Self { Self { kind: Some(kind), diff --git a/src/main.rs b/src/main.rs index 330d2ce0..ae5006c0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -562,7 +562,7 @@ enum Command { /// Overwrite existing cora entry #[clap(long)] force: bool, - /// Install ALL detected agents (non-interactive) + /// Accepted for compatibility: `cora install` never asks questions #[clap(long, short)] yes: bool, /// Remove cora MCP entry from detected agents (uninstall) @@ -1615,7 +1615,7 @@ async fn main() -> Result<()> { agents, dry_run, force, - yes, + yes: _, remove, validate, no_instructions, @@ -1630,7 +1630,6 @@ async fn main() -> Result<()> { agents, dry_run, force, - yes, remove, validate, }; diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs index 8ddd0c9c..760f979f 100644 --- a/src/mcp/mod.rs +++ b/src/mcp/mod.rs @@ -9,21 +9,3 @@ pub mod agent_tools; pub mod protocol; pub mod server; pub mod tools; - -use serde::{Deserialize, Serialize}; - -/// MCP server configuration. -#[derive(Debug, Clone, Serialize, Deserialize)] -#[allow(dead_code)] -pub struct McpConfig { - /// Enable MCP server. - #[serde(default)] - pub enabled: bool, -} - -#[allow(clippy::derivable_impls)] -impl Default for McpConfig { - fn default() -> Self { - Self { enabled: false } - } -} diff --git a/src/mcp/tools.rs b/src/mcp/tools.rs index a3a624db..c2829bbe 100644 --- a/src/mcp/tools.rs +++ b/src/mcp/tools.rs @@ -1089,7 +1089,6 @@ fn handle_install(params: &serde_json::Value) -> ToolResult { agents, dry_run, force: false, - yes: true, // MCP is non-interactive; guarded by `confirm` above remove: false, validate: false, };