From fcd3d8d7891b5dfb3af36137a30dd9725e37b0db Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 09:30:41 +0800 Subject: [PATCH 1/6] feat(cli): add codeint schema capability manifest command Add the codeint schema subcommand to emit a deterministic JSON or TOON capability manifest derived directly from clap command metadata, built-in Metric definitions, built-in Language plugins, live MCP tool definitions, and CLI exit codes. Closes #186 --- crates/cli/src/check.rs | 12 +- crates/cli/src/lib.rs | 50 ++++++- crates/cli/src/mcp.rs | 101 +++++++------ crates/cli/tests/schema.rs | 251 ++++++++++++++++++++++++++++++++ crates/config/src/cli_schema.rs | 192 ++++++++++++++++++++++++ crates/config/src/lib.rs | 36 +++++ crates/report/src/lib.rs | 2 + crates/report/src/sarif.rs | 43 +----- crates/report/src/schema.rs | 153 +++++++++++++++++++ docs/reference.md | 19 +++ 10 files changed, 769 insertions(+), 90 deletions(-) create mode 100644 crates/cli/tests/schema.rs create mode 100644 crates/config/src/cli_schema.rs create mode 100644 crates/report/src/schema.rs diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index f678623..bc635e3 100644 --- a/crates/cli/src/check.rs +++ b/crates/cli/src/check.rs @@ -21,7 +21,7 @@ use codeint_plugin_host::{ PluginHostError, WasmLanguagePlugin, WasmMetricPlugin, load_language_plugins_with_limits, load_metric_plugins_with_limits, }; -use codeint_report::{MeasuredLanguage, Report}; +use codeint_report::{LanguageSchema, MeasuredLanguage, Report}; use rayon::prelude::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator}; #[cfg(test)] @@ -96,6 +96,16 @@ pub(crate) const BUILT_IN_LANGUAGE_PLUGINS: [NamedLanguagePlugin<'static>; 5] = }, ]; +pub(crate) fn built_in_languages() -> Vec { + BUILT_IN_LANGUAGE_PLUGINS + .iter() + .map(|named| LanguageSchema { + name: named.name.to_owned(), + extensions: named.plugin.extensions(), + }) + .collect() +} + pub(crate) struct LoadedPlugins { external_languages: Vec<(String, WasmLanguagePlugin)>, external_metrics: Vec<(String, WasmMetricPlugin)>, diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index c3c9d6d..1f00d32 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -16,15 +16,15 @@ use std::io::Write; use std::path::{Path, PathBuf}; use std::process::ExitCode; -use codeint_config::{Command, ConfigError, ReportDestination, read_invocation}; +use codeint_config::{Command, ConfigError, ReportDestination, cli_schema, read_invocation}; use codeint_git::ResultCache; -use codeint_report::ReportError; +use codeint_report::{ExitCodeSchema, ReportError}; pub use codeint_config::{ - CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat, - TrendRange, + CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, SchemaFormat, + TrendFormat, TrendRange, }; -pub use codeint_report::{DiffReport, GuardReport, Report, TrendReport}; +pub use codeint_report::{DiffReport, GuardReport, Report, SchemaReport, TrendReport}; const DEFAULT_WORST_FINDINGS: usize = 20; const DEFAULT_TREND_COMMITS: usize = 20; @@ -188,6 +188,15 @@ pub fn guard(folder: &Path, target: &Path) -> Result guard::guard(folder, target).map_err(|err| CodeintError::from_cli_error(CliError::Guard(err))) } +pub fn schema() -> SchemaReport { + SchemaReport::build( + cli_schema(), + check::built_in_languages(), + mcp::tool_definitions(), + exit_codes(), + ) +} + #[derive(Debug, thiserror::Error)] enum CliError { #[error(transparent)] @@ -212,9 +221,30 @@ enum CliError { }, } +const SUCCESS: u8 = 0; const BUDGET_OR_REGRESSION_FAILED: u8 = 1; const OPERATIONAL_ERROR: u8 = 2; +fn exit_codes() -> Vec { + vec![ + ExitCodeSchema { + code: SUCCESS, + name: "success", + description: "The run succeeded, and no Budget or Regression failed.", + }, + ExitCodeSchema { + code: BUDGET_OR_REGRESSION_FAILED, + name: "budget_or_regression_failed", + description: "The run succeeded, and at least one Budget or Regression failed.", + }, + ExitCodeSchema { + code: OPERATIONAL_ERROR, + name: "operational_error", + description: "An operational error stopped the run, such as an invalid option, missing Git ref, or invalid codeint.json.", + }, + ] +} + enum Outcome { Passed, Failed(Vec), @@ -304,9 +334,19 @@ fn run() -> Result { target, format, } => run_guard(&folder, &target, format), + Command::Schema { + destination, + format, + } => run_schema(&destination, format), } } +fn run_schema(destination: &ReportDestination, format: SchemaFormat) -> Result { + let report = schema(); + write_report(&report.render(format)?, destination)?; + Ok(Outcome::Passed) +} + fn run_guard(folder: &Path, target: &Path, format: GuardFormat) -> Result { let report = guard::guard(folder, target)?; print_report(&format!("{}\n", report.render(format)?))?; diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 55e02b3..d6a0b42 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -6,6 +6,7 @@ use codeint_config::{ CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat, TrendRange, }; +use codeint_report::McpToolSchema; use serde_json::{Value, json}; use crate::{CheckOptions, DiffOptions, TrendOptions, check, diff, guard, trend}; @@ -120,58 +121,62 @@ fn handle_initialize(params: Option<&Value>) -> Value { }) } -fn handle_tools_list() -> Value { - json!({ - "tools": [ - { - "name": "check", - "description": "Measure Software entropy of a Git repository working tree (Erosion, Duplication, Verbosity, Import cycles) and report any Budget failures.", - "inputSchema": { - "type": "object", - "properties": { - "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, - "all": { "type": "boolean", "description": "Return all Findings instead of the 20 worst per Metric." } - } +pub(crate) fn tool_definitions() -> Vec { + vec![ + McpToolSchema { + name: "check".to_owned(), + description: "Measure Software entropy of a Git repository working tree (Erosion, Duplication, Verbosity, Import cycles) and report any Budget failures.".to_owned(), + input_schema: json!({ + "type": "object", + "properties": { + "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, + "all": { "type": "boolean", "description": "Return all Findings instead of the 20 worst per Metric." } } - }, - { - "name": "diff", - "description": "Compare the working tree (or a head Git ref) against the merge-base of base_ref and classify Findings as new, resolved, or unchanged.", - "inputSchema": { - "type": "object", - "required": ["base_ref"], - "properties": { - "base_ref": { "type": "string", "description": "Base Git ref such as main or origin/main." }, - "head_ref": { "type": "string", "description": "Optional head Git ref instead of the working tree." }, - "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, - "all": { "type": "boolean", "description": "Return all Findings instead of the 20 worst per Metric." } - } + }), + }, + McpToolSchema { + name: "diff".to_owned(), + description: "Compare the working tree (or a head Git ref) against the merge-base of base_ref and classify Findings as new, resolved, or unchanged.".to_owned(), + input_schema: json!({ + "type": "object", + "required": ["base_ref"], + "properties": { + "base_ref": { "type": "string", "description": "Base Git ref such as main or origin/main." }, + "head_ref": { "type": "string", "description": "Optional head Git ref instead of the working tree." }, + "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, + "all": { "type": "boolean", "description": "Return all Findings instead of the 20 worst per Metric." } } - }, - { - "name": "trend", - "description": "Measure each main-line commit over time (latest 20 commits or since YYYY-MM-DD).", - "inputSchema": { - "type": "object", - "properties": { - "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, - "since": { "type": "string", "description": "UTC date YYYY-MM-DD to start the trend from." } - } + }), + }, + McpToolSchema { + name: "trend".to_owned(), + description: "Measure each main-line commit over time (latest 20 commits or since YYYY-MM-DD).".to_owned(), + input_schema: json!({ + "type": "object", + "properties": { + "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, + "since": { "type": "string", "description": "UTC date YYYY-MM-DD to start the trend from." } } - }, - { - "name": "guard", - "description": "Query the architectural boundary zone, allowed and denied target zones, public_files constraints, and allowed importers for an existing or planned file path.", - "inputSchema": { - "type": "object", - "required": ["file"], - "properties": { - "file": { "type": "string", "description": "Repository-relative or absolute path to the existing or planned file." }, - "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." } - } + }), + }, + McpToolSchema { + name: "guard".to_owned(), + description: "Query the architectural boundary zone, allowed and denied target zones, public_files constraints, and allowed importers for an existing or planned file path.".to_owned(), + input_schema: json!({ + "type": "object", + "required": ["file"], + "properties": { + "file": { "type": "string", "description": "Repository-relative or absolute path to the existing or planned file." }, + "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." } } - } - ] + }), + }, + ] +} + +fn handle_tools_list() -> Value { + json!({ + "tools": tool_definitions(), }) } diff --git a/crates/cli/tests/schema.rs b/crates/cli/tests/schema.rs new file mode 100644 index 0000000..4ede47b --- /dev/null +++ b/crates/cli/tests/schema.rs @@ -0,0 +1,251 @@ +use std::collections::BTreeSet; +use std::io::Write; +use std::path::Path; +use std::process::{Command, Output, Stdio}; + +use serde_json::{Value, json}; +use tempfile::TempDir; + +fn run_codeint(cwd: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_codeint")) + .args(args) + .current_dir(cwd) + .output() + .expect("run codeint") +} + +fn schema_json(cwd: &Path, extra_args: &[&str]) -> Value { + let mut args = vec!["schema"]; + args.extend_from_slice(extra_args); + let output = run_codeint(cwd, &args); + assert_eq!( + output.status.code(), + Some(0), + "codeint {args:?} failed with stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).expect("schema output must be valid JSON") +} + +fn help_subcommands(cwd: &Path) -> BTreeSet { + let output = run_codeint(cwd, &["--help"]); + assert_eq!(output.status.code(), Some(0)); + let help = String::from_utf8(output.stdout).expect("utf8 help"); + let mut in_commands = false; + let mut commands = BTreeSet::new(); + for line in help.lines() { + if line.trim() == "Commands:" { + in_commands = true; + continue; + } + if !in_commands { + continue; + } + if line.trim().is_empty() { + break; + } + if let Some(name) = line.split_whitespace().next() + && name != "help" + { + commands.insert(name.to_owned()); + } + } + commands +} + +fn live_mcp_tools(cwd: &Path) -> Value { + let mut child = Command::new(env!("CARGO_BIN_EXE_codeint")) + .arg("mcp") + .current_dir(cwd) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn codeint mcp"); + { + let mut stdin = child.stdin.take().expect("mcp stdin"); + writeln!( + stdin, + "{}", + json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}) + ) + .expect("write tools/list"); + } + let output = child.wait_with_output().expect("wait mcp"); + assert_eq!( + output.status.code(), + Some(0), + "mcp stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + let line = String::from_utf8(output.stdout) + .expect("utf8 mcp stdout") + .lines() + .next() + .expect("mcp response line") + .to_owned(); + let response: Value = serde_json::from_str(&line).expect("valid mcp json"); + response["result"]["tools"].clone() +} + +fn find_command<'a>(manifest: &'a Value, name: &str) -> &'a Value { + manifest["commands"] + .as_array() + .expect("commands array") + .iter() + .find(|cmd| cmd["name"].as_str() == Some(name)) + .unwrap_or_else(|| panic!("missing command {name} in schema")) +} + +fn flag_names(command: &Value) -> BTreeSet { + command["flags"] + .as_array() + .expect("flags array") + .iter() + .filter_map(|flag| flag["long"].as_str().map(str::to_owned)) + .collect() +} + +#[test] +fn schema_matches_live_cli_commands_flags_metrics_formats_mcp_tools_version_and_exit_codes() { + let non_repo = TempDir::new().expect("tempdir"); + let manifest = schema_json(non_repo.path(), &[]); + + assert_eq!(manifest["name"], "codeint"); + assert_eq!(manifest["version"], env!("CARGO_PKG_VERSION")); + let version_out = run_codeint(non_repo.path(), &["--version"]); + assert_eq!(version_out.status.code(), Some(0)); + let version_text = String::from_utf8(version_out.stdout).expect("utf8 version"); + assert_eq!( + version_text.trim(), + format!( + "{} {}", + manifest["name"].as_str().unwrap(), + manifest["version"].as_str().unwrap() + ) + ); + + let live_commands = help_subcommands(non_repo.path()); + let schema_commands: BTreeSet = manifest["commands"] + .as_array() + .expect("commands array") + .iter() + .map(|cmd| cmd["name"].as_str().expect("command name").to_owned()) + .collect(); + assert_eq!(schema_commands, live_commands); + assert!(schema_commands.contains("schema")); + + let check_cmd = find_command(&manifest, "check"); + assert_eq!( + flag_names(check_cmd), + BTreeSet::from([ + "--all".to_owned(), + "--format".to_owned(), + "--output".to_owned(), + ]) + ); + let diff_cmd = find_command(&manifest, "diff"); + assert_eq!( + flag_names(diff_cmd), + BTreeSet::from([ + "--all".to_owned(), + "--format".to_owned(), + "--head".to_owned(), + "--output".to_owned(), + ]) + ); + assert_eq!(diff_cmd["arguments"][0]["value_name"], "BASE_REF"); + assert_eq!(diff_cmd["arguments"][0]["required"], true); + + let schema_cmd = find_command(&manifest, "schema"); + assert_eq!( + flag_names(schema_cmd), + BTreeSet::from(["--format".to_owned(), "--output".to_owned()]) + ); + + let metric_keys: Vec<&str> = manifest["metrics"] + .as_array() + .expect("metrics array") + .iter() + .map(|m| m["key"].as_str().expect("metric key")) + .collect(); + assert_eq!( + metric_keys, + ["erosion", "duplication", "verbosity", "import_cycles"] + ); + for metric in manifest["metrics"].as_array().expect("metrics array") { + assert!(!metric["name"].as_str().unwrap_or_default().is_empty()); + assert!( + !metric["description"] + .as_str() + .unwrap_or_default() + .is_empty() + ); + } + + let format_names: BTreeSet<&str> = manifest["output_formats"] + .as_array() + .expect("output_formats array") + .iter() + .map(|f| f["name"].as_str().expect("format name")) + .collect(); + assert_eq!( + format_names, + BTreeSet::from(["json", "markdown", "sarif", "text", "toon"]) + ); + + let mcp_tools = live_mcp_tools(non_repo.path()); + assert_eq!(manifest["mcp_tools"], mcp_tools); + + let exit_codes: Vec = manifest["exit_codes"] + .as_array() + .expect("exit_codes array") + .iter() + .map(|entry| entry["code"].as_i64().expect("exit code integer")) + .collect(); + assert_eq!(exit_codes, [0, 1, 2]); +} + +#[test] +fn schema_supports_json_and_toon_formats_output_file_and_deterministic_rendering() { + let dir = TempDir::new().expect("tempdir"); + + let first_json = run_codeint(dir.path(), &["schema", "--format", "json"]); + let second_json = run_codeint(dir.path(), &["schema"]); + assert_eq!(first_json.status.code(), Some(0)); + assert_eq!(second_json.status.code(), Some(0)); + assert_eq!(first_json.stdout, second_json.stdout); + let expected: Value = serde_json::from_slice(&first_json.stdout).expect("valid json"); + + let toon_output = run_codeint(dir.path(), &["schema", "--format", "toon"]); + assert_eq!( + toon_output.status.code(), + Some(0), + "stderr: {}", + String::from_utf8_lossy(&toon_output.stderr) + ); + let toon_text = String::from_utf8(toon_output.stdout).expect("utf8 toon"); + assert!(toon_text.contains("name: codeint")); + assert!(toon_text.contains(&format!("version: {}", env!("CARGO_PKG_VERSION")))); + let decoded: Value = toon_format::decode_default(&toon_text).expect("valid toon"); + assert_eq!(decoded, expected); + + let out_file = dir.path().join("manifest.json"); + let file_output = run_codeint( + dir.path(), + &[ + "schema", + "--format", + "json", + "--output", + out_file.to_str().expect("utf8 path"), + ], + ); + assert_eq!(file_output.status.code(), Some(0)); + assert!(file_output.stdout.is_empty()); + let written = std::fs::read(&out_file).expect("read written manifest"); + assert_eq!(written, first_json.stdout); + + let invalid = run_codeint(dir.path(), &["schema", "--format", "yaml"]); + assert_eq!(invalid.status.code(), Some(2)); +} diff --git a/crates/config/src/cli_schema.rs b/crates/config/src/cli_schema.rs new file mode 100644 index 0000000..76e18f0 --- /dev/null +++ b/crates/config/src/cli_schema.rs @@ -0,0 +1,192 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use clap::{Arg, Command as ClapCommand, CommandFactory}; +use serde::Serialize; + +use crate::Arguments; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct CliSchema { + pub name: String, + pub version: String, + pub description: String, + pub commands: Vec, + pub output_formats: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct CliCommandSchema { + pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + pub arguments: Vec, + pub flags: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub subcommands: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct CliArgumentSchema { + pub name: String, + pub value_name: String, + pub required: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct CliFlagSchema { + #[serde(skip_serializing_if = "Option::is_none")] + pub short: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub long: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub value_name: Option, + pub takes_value: bool, + pub required: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub default_value: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub possible_values: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct OutputFormatSchema { + pub name: String, + pub commands: Vec, +} + +pub fn cli_schema() -> CliSchema { + let root = Arguments::command(); + let commands: Vec = root + .get_subcommands() + .filter(|sub| !sub.is_hide_set() && sub.get_name() != "help") + .map(describe_command) + .collect(); + let output_formats = collect_output_formats(&commands); + CliSchema { + name: root.get_name().to_owned(), + version: root + .get_version() + .unwrap_or(env!("CARGO_PKG_VERSION")) + .to_owned(), + description: root + .get_about() + .map(ToString::to_string) + .unwrap_or_default(), + commands, + output_formats, + } +} + +fn describe_command(command: &ClapCommand) -> CliCommandSchema { + let mut arguments = Vec::new(); + let mut flags = Vec::new(); + for arg in command.get_arguments().filter(|arg| !arg.is_hide_set()) { + if arg.is_positional() { + arguments.push(describe_argument(arg)); + } else { + flags.push(describe_flag(arg)); + } + } + let subcommands = command + .get_subcommands() + .filter(|sub| !sub.is_hide_set() && sub.get_name() != "help") + .map(describe_command) + .collect(); + CliCommandSchema { + name: command.get_name().to_owned(), + description: command.get_about().map(ToString::to_string), + arguments, + flags, + subcommands, + } +} + +fn describe_argument(arg: &Arg) -> CliArgumentSchema { + let name = arg.get_id().as_str().to_owned(); + let value_name = first_value_name(arg).unwrap_or_else(|| name.to_ascii_uppercase()); + CliArgumentSchema { + name, + value_name, + required: arg.is_required_set(), + description: arg.get_help().map(ToString::to_string), + } +} + +fn describe_flag(arg: &Arg) -> CliFlagSchema { + let takes_value = arg.get_action().takes_values(); + let value_name = takes_value.then(|| first_value_name(arg)).flatten(); + let default_value = takes_value + .then(|| { + arg.get_default_values() + .first() + .and_then(|value| value.to_str()) + .map(str::to_owned) + }) + .flatten(); + let possible_values = if takes_value { + arg.get_possible_values() + .into_iter() + .filter(|value| !value.is_hide_set()) + .map(|value| value.get_name().to_owned()) + .collect() + } else { + Vec::new() + }; + CliFlagSchema { + short: arg.get_short().map(|short| format!("-{short}")), + long: arg.get_long().map(|long| format!("--{long}")), + value_name, + takes_value, + required: arg.is_required_set(), + default_value, + possible_values, + description: arg.get_help().map(ToString::to_string), + } +} + +fn first_value_name(arg: &Arg) -> Option { + arg.get_value_names() + .and_then(|names| names.first()) + .map(|name| name.as_str().to_owned()) +} + +fn collect_output_formats(commands: &[CliCommandSchema]) -> Vec { + let mut by_format: BTreeMap> = BTreeMap::new(); + record_command_formats(commands, "", &mut by_format); + by_format + .into_iter() + .map(|(name, commands)| OutputFormatSchema { + name, + commands: commands.into_iter().collect(), + }) + .collect() +} + +fn record_command_formats( + commands: &[CliCommandSchema], + prefix: &str, + by_format: &mut BTreeMap>, +) { + for command in commands { + let full_name = if prefix.is_empty() { + command.name.clone() + } else { + format!("{prefix} {}", command.name) + }; + for flag in &command.flags { + if flag.long.as_deref() == Some("--format") { + for format in &flag.possible_values { + by_format + .entry(format.clone()) + .or_default() + .insert(full_name.clone()); + } + } + } + record_command_formats(&command.subcommands, &full_name, by_format); + } +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 642a0b3..7c24034 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -6,6 +6,7 @@ use clap::{Parser, Subcommand}; mod boundaries; mod calendar_day; +mod cli_schema; mod codeint_json; mod config_error; mod regression_limits; @@ -15,6 +16,9 @@ pub use boundaries::{ Boundaries, BoundaryDirective, BoundaryPreset, BoundaryRuleDecision, BoundarySourceSet, }; pub use calendar_day::{CalendarDay, CalendarDayError}; +pub use cli_schema::{ + CliArgumentSchema, CliCommandSchema, CliFlagSchema, CliSchema, OutputFormatSchema, cli_schema, +}; pub use codeint_json::{ Budget, Budgets, Configuration, DetectedLanguage, LanguageCoverage, Languages, PluginDeclaration, PluginKind, PluginLimits, PluginSource, Sha256Digest, SourceSetOverrides, @@ -105,6 +109,12 @@ pub enum GuardFormat { Json, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] +pub enum SchemaFormat { + Json, + Toon, +} + const LATEST_COMMITS_OF_A_TREND: usize = 20; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -158,6 +168,10 @@ pub enum Command { target: PathBuf, format: GuardFormat, }, + Schema { + destination: ReportDestination, + format: SchemaFormat, + }, } #[derive(Debug)] @@ -268,6 +282,24 @@ enum CommandArguments { )] format: GuardFormat, }, + #[command( + about = "Print a machine-readable capability manifest of CLI commands, flags, built-in Metrics, output formats, MCP tools, and exit codes" + )] + Schema { + #[arg( + long, + value_name = "FILE", + help = "Write the schema manifest to this file instead of standard output" + )] + output: Option, + #[arg( + long, + value_enum, + default_value_t = SchemaFormat::Json, + help = "The format of the schema manifest" + )] + format: SchemaFormat, + }, } #[derive(Debug, clap::Args)] @@ -328,6 +360,10 @@ fn build_command( target: path, format, }), + CommandArguments::Schema { output, format } => Ok(Command::Schema { + destination: report_destination(current_folder, output)?, + format, + }), } } diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index ec6083c..e457cfb 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -23,6 +23,7 @@ mod guard; mod markdown; mod measurement; mod sarif; +mod schema; #[cfg(test)] mod tests; mod trend; @@ -30,6 +31,7 @@ mod trend; pub use diff::{BaseCommit, DiffReport, Head, HeadCommit}; pub use guard::{GuardAllowedTarget, GuardDeniedTarget, GuardReport}; pub use measurement::CommitMeasurement; +pub use schema::{ExitCodeSchema, LanguageSchema, McpToolSchema, MetricSchema, SchemaReport}; pub use trend::{TrendPoint, TrendReport}; const DECIMAL_SCALE: f64 = 10_000.0; diff --git a/crates/report/src/sarif.rs b/crates/report/src/sarif.rs index a28ca62..f956b6a 100644 --- a/crates/report/src/sarif.rs +++ b/crates/report/src/sarif.rs @@ -4,6 +4,7 @@ use serde::Serialize; use codeint_model::{Metric, SourceSet}; +use crate::schema::{BUILT_IN_METRICS, built_in_metric_descriptor}; use crate::{ BoundaryFindingRow, CloneGroupFinding, CloneLocation, ErodedFunctionFinding, ExternalMetricFinding, FlaggedLineRow, ImportCycleFinding, Report, SourceSetSection, @@ -224,46 +225,16 @@ impl SarifLog { } } -const RULES: [Metric; 4] = [ - Metric::Erosion, - Metric::Duplication, - Metric::Verbosity, - Metric::ImportCycles, -]; +const RULES: [Metric; 4] = BUILT_IN_METRICS; fn descriptor(metric: Metric) -> Rule { - let (name, short_description, full_description, help) = match metric { - Metric::Erosion => ( - "Erosion", - "A function with cyclomatic complexity over 10", - "Erosion is the share of total Function mass held by functions whose cyclomatic complexity is greater than 10. Function mass is cyclomatic complexity times the square root of source lines.", - "Split the function into smaller functions, each with a cyclomatic complexity of 10 or less.", - ), - Metric::Duplication => ( - "Duplication", - "A Clone group: code fragments with the same token sequence", - "Duplication is the share of source lines that belong to at least one Clone group. A Clone group is two or more code fragments with the same token sequence once identifiers and literals are normalized.", - "Extract the fragments of the Clone group into one shared function or module.", - ), - Metric::Verbosity => ( - "Verbosity", - "A Flagged line: code that can be deleted or collapsed", - "Verbosity is the share of source lines that are Flagged lines, clone lines, or both. A Flagged line matches a verbose-code pattern of the source language, and the result names the rule it matches.", - "Delete or collapse the line as its rule describes; the behavior stays the same.", - ), - Metric::ImportCycles => ( - "Import cycles", - "An Import cycle among runtime imports", - "Import cycles is the share of modules that belong to at least one Import cycle. An Import cycle is a group of modules in which every module can reach every other module through runtime imports.", - "Break the Import cycle, for example by moving the code that the modules share into a module that imports none of them.", - ), - }; + let info = built_in_metric_descriptor(metric); Rule { id: metric.key().to_owned(), - name: name.to_owned(), - short_description: Text::from(short_description), - full_description: Text::from(full_description), - help: Text::from(help), + name: info.name.to_owned(), + short_description: Text::from(info.short_description), + full_description: Text::from(info.full_description), + help: Text::from(info.help), } } diff --git a/crates/report/src/schema.rs b/crates/report/src/schema.rs new file mode 100644 index 0000000..e700c7d --- /dev/null +++ b/crates/report/src/schema.rs @@ -0,0 +1,153 @@ +use codeint_config::{ + CliCommandSchema, CliSchema, NewFindingsRule, OutputFormatSchema, RegressionLimits, + SchemaFormat, +}; +use codeint_model::{Metric, SourceSet}; +use serde::Serialize; +use serde_json::Value; + +use crate::ReportError; + +pub(crate) const BUILT_IN_METRICS: [Metric; 4] = [ + Metric::Erosion, + Metric::Duplication, + Metric::Verbosity, + Metric::ImportCycles, +]; + +const SOURCE_SETS: [SourceSet; 4] = [ + SourceSet::Production, + SourceSet::Test, + SourceSet::Generated, + SourceSet::Vendored, +]; + +#[derive(Debug, Clone, Copy)] +pub(crate) struct BuiltInMetricDescriptor { + pub(crate) name: &'static str, + pub(crate) short_description: &'static str, + pub(crate) full_description: &'static str, + pub(crate) help: &'static str, +} + +pub(crate) fn built_in_metric_descriptor(metric: Metric) -> BuiltInMetricDescriptor { + match metric { + Metric::Erosion => BuiltInMetricDescriptor { + name: "Erosion", + short_description: "A function with cyclomatic complexity over 10", + full_description: "Erosion is the share of total Function mass held by functions whose cyclomatic complexity is greater than 10. Function mass is cyclomatic complexity times the square root of source lines.", + help: "Split the function into smaller functions, each with a cyclomatic complexity of 10 or less.", + }, + Metric::Duplication => BuiltInMetricDescriptor { + name: "Duplication", + short_description: "A Clone group: code fragments with the same token sequence", + full_description: "Duplication is the share of source lines that belong to at least one Clone group. A Clone group is two or more code fragments with the same token sequence once identifiers and literals are normalized.", + help: "Extract the fragments of the Clone group into one shared function or module.", + }, + Metric::Verbosity => BuiltInMetricDescriptor { + name: "Verbosity", + short_description: "A Flagged line: code that can be deleted or collapsed", + full_description: "Verbosity is the share of source lines that are Flagged lines, clone lines, or both. A Flagged line matches a verbose-code pattern of the source language, and the result names the rule it matches.", + help: "Delete or collapse the line as its rule describes; the behavior stays the same.", + }, + Metric::ImportCycles => BuiltInMetricDescriptor { + name: "Import cycles", + short_description: "An Import cycle among runtime imports", + full_description: "Import cycles is the share of modules that belong to at least one Import cycle. An Import cycle is a group of modules in which every module can reach every other module through runtime imports.", + help: "Break the Import cycle, for example by moving the code that the modules share into a module that imports none of them.", + }, + } +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct SchemaReport { + name: String, + version: String, + description: String, + commands: Vec, + metrics: Vec, + source_sets: Vec<&'static str>, + languages: Vec, + output_formats: Vec, + mcp_tools: Vec, + exit_codes: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct MetricSchema { + key: &'static str, + name: &'static str, + short_description: &'static str, + description: &'static str, + unit: &'static str, + default_ratio_rise_limit: f64, + default_new_findings_rule: NewFindingsRule, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct LanguageSchema { + pub name: String, + pub extensions: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct McpToolSchema { + pub name: String, + pub description: String, + #[serde(rename = "inputSchema")] + pub input_schema: Value, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ExitCodeSchema { + pub code: u8, + pub name: &'static str, + pub description: &'static str, +} + +impl SchemaReport { + pub fn build( + cli: CliSchema, + languages: Vec, + mcp_tools: Vec, + exit_codes: Vec, + ) -> SchemaReport { + let default_limits = RegressionLimits::default(); + let metrics = BUILT_IN_METRICS + .into_iter() + .map(|metric| { + let descriptor = built_in_metric_descriptor(metric); + let limit = default_limits.limit(SourceSet::Production, metric); + MetricSchema { + key: metric.key(), + name: descriptor.name, + short_description: descriptor.short_description, + description: descriptor.full_description, + unit: "ratio", + default_ratio_rise_limit: limit.ratio_rise.ratio(), + default_new_findings_rule: limit.new_findings, + } + }) + .collect(); + let source_sets = SOURCE_SETS.into_iter().map(SourceSet::key).collect(); + SchemaReport { + name: cli.name, + version: cli.version, + description: cli.description, + commands: cli.commands, + metrics, + source_sets, + languages, + output_formats: cli.output_formats, + mcp_tools, + exit_codes, + } + } + + pub fn render(&self, format: SchemaFormat) -> Result { + match format { + SchemaFormat::Json => serde_json::to_string_pretty(self).map_err(ReportError::Json), + SchemaFormat::Toon => toon_format::encode_default(self).map_err(ReportError::Toon), + } + } +} diff --git a/docs/reference.md b/docs/reference.md index 92e93a0..fc7f9a1 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -30,6 +30,7 @@ The working tree adds `src/route.ts`, an eroded function that is not committed. | `update` | Update a standalone codeint binary in place from GitHub Releases; see [`codeint update`](#codeint-update) | | `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, `trend`, and `guard` tools; see [`codeint mcp`](#codeint-mcp) | | `guard` | Show the architectural boundary zone, allowed and denied target zones, `public_files` constraints, and allowed importers for a file path; see [`codeint guard`](#codeint-guard) | +| `schema` | Print a machine-readable capability manifest of CLI commands, flags, built-in Metrics, output formats, MCP tools, and exit codes; see [`codeint schema`](#codeint-schema) | | `help` | Print the help of codeint, or of the command that follows it | | Option | Meaning | @@ -514,6 +515,24 @@ codeint guard src/route.ts --format toon codeint guard src/route.ts --format json ``` +### `codeint schema` + +| Option | Meaning | +| ------ | ------- | +| `--output ` | Write the schema manifest to this file instead of standard output | +| `--format ` | The format of the schema manifest: `json`, the default, or `toon` | +| `-h, --help` | Print the help of `codeint schema` | + +`codeint schema` prints a deterministic, machine-readable manifest describing the running binary version, every CLI command and flag, built-in Metrics, Source sets, built-in Language plugins, output formats, MCP tools, and exit codes. +It is derived directly from live CLI and MCP definitions, works outside a Git repository, and stays 100% local and offline. + +```sh exit=0 +codeint schema +codeint schema --format json +codeint schema --format toon +codeint schema --output schema.json +``` + ## Exit codes | Exit code | Meaning | From 73c3e7c254004c98377d0f6a55e39c477238be56 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 09:45:11 +0800 Subject: [PATCH 2/6] feat(config): add codeint config --resolved with per-field provenance Track default, file, and CLI provenance inside the configuration loader during merge and expose codeint config --resolved across text, JSON, and TOON formats. Closes #187 --- crates/cli/src/config.rs | 22 ++ crates/cli/src/lib.rs | 32 +- crates/cli/src/remedy.rs | 9 + crates/cli/tests/config.rs | 273 +++++++++++++++++ crates/config/HOW-TO.md | 1 + crates/config/src/boundaries.rs | 27 +- crates/config/src/codeint_json.rs | 409 +++++++++++++++++++++++-- crates/config/src/lib.rs | 87 +++++- crates/config/src/regression_limits.rs | 66 +++- crates/config/src/resolved.rs | 140 +++++++++ crates/report/src/config.rs | 45 +++ crates/report/src/lib.rs | 10 + docs/reference.md | 26 ++ 13 files changed, 1106 insertions(+), 41 deletions(-) create mode 100644 crates/cli/src/config.rs create mode 100644 crates/cli/tests/config.rs create mode 100644 crates/config/src/resolved.rs create mode 100644 crates/report/src/config.rs diff --git a/crates/cli/src/config.rs b/crates/cli/src/config.rs new file mode 100644 index 0000000..11861e2 --- /dev/null +++ b/crates/cli/src/config.rs @@ -0,0 +1,22 @@ +use std::path::Path; + +use codeint_config::{ConfigOverrides, ConfigurationFileError, read_resolved_configuration}; +use codeint_git::{GitError, Repository}; +use codeint_report::ConfigReport; + +#[derive(Debug, thiserror::Error)] +pub(crate) enum ConfigCommandError { + #[error(transparent)] + Git(#[from] GitError), + #[error(transparent)] + Configuration(#[from] ConfigurationFileError), +} + +pub(crate) fn resolved_config( + folder: &Path, + overrides: &ConfigOverrides, +) -> Result { + let repository = Repository::discover(folder)?; + let resolved = read_resolved_configuration(repository.root(), overrides)?; + Ok(ConfigReport::from_resolved(&resolved)) +} diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index c3c9d6d..52ff8e0 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -2,6 +2,7 @@ mod check; mod commit_measurement; +mod config; mod diff; mod guard; mod init; @@ -21,10 +22,10 @@ use codeint_git::ResultCache; use codeint_report::ReportError; pub use codeint_config::{ - CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat, - TrendRange, + BudgetOverride, CalendarDay, ConfigFormat, ConfigOverrides, FindingsShown, GuardFormat, + PluginHostConfig, ReportFormat, SourceSetOverride, TrendFormat, TrendRange, }; -pub use codeint_report::{DiffReport, GuardReport, Report, TrendReport}; +pub use codeint_report::{ConfigReport, DiffReport, GuardReport, Report, TrendReport}; const DEFAULT_WORST_FINDINGS: usize = 20; const DEFAULT_TREND_COMMITS: usize = 20; @@ -188,11 +189,21 @@ pub fn guard(folder: &Path, target: &Path) -> Result guard::guard(folder, target).map_err(|err| CodeintError::from_cli_error(CliError::Guard(err))) } +pub fn resolved_config( + folder: &Path, + overrides: &ConfigOverrides, +) -> Result { + config::resolved_config(folder, overrides) + .map_err(|err| CodeintError::from_cli_error(CliError::ConfigCommand(err))) +} + #[derive(Debug, thiserror::Error)] enum CliError { #[error(transparent)] Config(#[from] ConfigError), #[error(transparent)] + ConfigCommand(#[from] config::ConfigCommandError), + #[error(transparent)] Check(#[from] check::CheckError), #[error(transparent)] Guard(#[from] guard::GuardError), @@ -304,9 +315,24 @@ fn run() -> Result { target, format, } => run_guard(&folder, &target, format), + Command::Config { + folder, + format, + overrides, + } => run_config(&folder, format, &overrides), } } +fn run_config( + folder: &Path, + format: ConfigFormat, + overrides: &ConfigOverrides, +) -> Result { + let report = config::resolved_config(folder, overrides)?; + print_report(&format!("{}\n", report.render(format)?))?; + Ok(Outcome::Passed) +} + fn run_guard(folder: &Path, target: &Path, format: GuardFormat) -> Result { let report = guard::guard(folder, target)?; print_report(&format!("{}\n", report.render(format)?))?; diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 9747e89..b1c6184 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -5,6 +5,7 @@ use codeint_plugin_host::PluginHostError; use crate::CliError; use crate::check::CheckError; +use crate::config::ConfigCommandError; use crate::guard::GuardError; use crate::init::InitError; use crate::update::UpdateError; @@ -12,6 +13,7 @@ use crate::update::UpdateError; pub(crate) fn remedy(error: &CliError) -> &'static str { match error { CliError::Config(error) => config_remedy(error), + CliError::ConfigCommand(error) => config_command_remedy(error), CliError::Check(error) => check_remedy(error), CliError::Guard(error) => guard_remedy(error), CliError::Init(error) => init_remedy(error), @@ -45,6 +47,13 @@ fn check_remedy(error: &CheckError) -> &'static str { } } +fn config_command_remedy(error: &ConfigCommandError) -> &'static str { + match error { + ConfigCommandError::Git(error) => git_remedy(error), + ConfigCommandError::Configuration(error) => configuration_file_remedy(error), + } +} + fn guard_remedy(error: &GuardError) -> &'static str { match error { GuardError::Git(error) => git_remedy(error), diff --git a/crates/cli/tests/config.rs b/crates/cli/tests/config.rs new file mode 100644 index 0000000..39158c0 --- /dev/null +++ b/crates/cli/tests/config.rs @@ -0,0 +1,273 @@ +use std::fs; +use std::path::Path; +use std::process::{Command, Output}; + +use serde_json::{Value, json}; +use tempfile::TempDir; + +fn init_repo_with_config(config: Option) -> TempDir { + let dir = TempDir::new().expect("tempdir"); + let status = Command::new("git") + .current_dir(dir.path()) + .args(["init", "--quiet", "--initial-branch", "main"]) + .status() + .expect("run git init"); + assert!(status.success(), "git init failed"); + if let Some(body) = config { + fs::write(dir.path().join("codeint.json"), body.to_string()).expect("write codeint.json"); + } + dir +} + +fn invoke(cwd: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_codeint")) + .current_dir(cwd) + .args(args) + .output() + .expect("invoke codeint") +} + +fn invoke_ok_stdout(cwd: &Path, args: &[&str]) -> String { + let output = invoke(cwd, args); + assert_eq!( + output.status.code(), + Some(0), + "expected exit 0, stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).expect("utf8 stdout") +} + +fn resolved_json(cwd: &Path, extra_args: &[&str]) -> Value { + let mut args = vec!["config", "--resolved", "--format", "json"]; + args.extend_from_slice(extra_args); + let stdout = invoke_ok_stdout(cwd, &args); + serde_json::from_str(&stdout).expect("valid JSON") +} + +fn assert_setting(payload: &Value, key: &str, expected_value: Value, expected_source: &str) { + let settings = payload["settings"] + .as_array() + .expect("settings array in resolved config"); + let entry = settings + .iter() + .find(|item| item["key"] == key) + .unwrap_or_else(|| panic!("missing setting {key} in {payload}")); + assert_eq!(entry["value"], expected_value, "wrong value for {key}"); + assert_eq!(entry["source"], expected_source, "wrong source for {key}"); +} + +#[test] +fn config_resolved_reports_defaults_only_across_text_json_and_toon_formats() { + let repo = init_repo_with_config(None); + + let payload = resolved_json(repo.path(), &[]); + assert_eq!(payload["config_file_present"], false); + assert!( + payload["config_file"] + .as_str() + .expect("config_file string") + .ends_with("codeint.json") + ); + assert_setting(&payload, "source_sets.production", json!([]), "default"); + assert_setting(&payload, "source_sets.test", json!([]), "default"); + assert_setting(&payload, "source_sets.generated", json!([]), "default"); + assert_setting(&payload, "source_sets.vendored", json!([]), "default"); + assert_setting(&payload, "budgets", json!({}), "default"); + assert_setting( + &payload, + "regression_limits.production.erosion.ratio_rise", + json!(0.01), + "default", + ); + assert_setting( + &payload, + "regression_limits.production.erosion.new_findings", + json!("numerator_rise_with_new_findings"), + "default", + ); + assert_setting( + &payload, + "regression_limits.production.import_cycles.new_findings", + json!("any_new_finding"), + "default", + ); + assert_setting(&payload, "languages", Value::Null, "default"); + assert_setting(&payload, "plugins", json!([]), "default"); + assert_setting(&payload, "plugin_limits.memory_mb", json!(64), "default"); + assert_setting(&payload, "plugin_limits.timeout_ms", json!(5000), "default"); + assert_setting(&payload, "boundaries", Value::Null, "default"); + + let text = invoke_ok_stdout(repo.path(), &["config", "--resolved"]); + assert!(text.contains("source_sets.production = [] [default]")); + assert!(text.contains("plugin_limits.memory_mb = 64 [default]")); + assert!(text.contains("plugin_limits.timeout_ms = 5000 [default]")); + + let toon = invoke_ok_stdout(repo.path(), &["config", "--resolved", "--format", "toon"]); + let decoded: Value = toon_format::decode_default(&toon).expect("valid TOON"); + assert_eq!(decoded["config_file_present"], false); + assert_setting(&decoded, "plugin_limits.memory_mb", json!(64), "default"); +} + +#[test] +fn config_resolved_merges_file_and_cli_overrides_with_per_field_provenance() { + let repo = init_repo_with_config(Some(json!({ + "source_sets": { + "test": ["spec/**"] + }, + "budgets": { + "production": { + "erosion": 0.25, + "duplication": 0.1 + } + }, + "regression_limits": { + "erosion": { + "ratio_rise": 0.05 + }, + "test": { + "erosion": { + "new_findings": "never" + } + } + }, + "plugin_limits": { + "memory_mb": 128 + }, + "boundaries": { + "preset": "layered", + "strict_zones": true + } + }))); + + let file_only = resolved_json(repo.path(), &[]); + assert_eq!(file_only["config_file_present"], true); + assert_setting(&file_only, "source_sets.test", json!(["spec/**"]), "file"); + assert_setting(&file_only, "source_sets.production", json!([]), "default"); + assert_setting( + &file_only, + "budgets.production.erosion", + json!(0.25), + "file", + ); + assert_setting( + &file_only, + "budgets.production.duplication", + json!(0.1), + "file", + ); + assert_setting( + &file_only, + "regression_limits.production.erosion.ratio_rise", + json!(0.05), + "file", + ); + assert_setting( + &file_only, + "regression_limits.production.erosion.new_findings", + json!("numerator_rise_with_new_findings"), + "default", + ); + assert_setting( + &file_only, + "regression_limits.test.erosion.new_findings", + json!("never"), + "file", + ); + assert_setting(&file_only, "plugin_limits.memory_mb", json!(128), "file"); + assert_setting( + &file_only, + "plugin_limits.timeout_ms", + json!(5000), + "default", + ); + assert_setting(&file_only, "boundaries.preset", json!("layered"), "file"); + assert_setting(&file_only, "boundaries.strict_zones", json!(true), "file"); + assert_setting( + &file_only, + "boundaries.source_sets", + json!(["production"]), + "default", + ); + + let with_cli = resolved_json( + repo.path(), + &[ + "--budget", + "production.erosion=0.15", + "--budget", + "test.verbosity=0.3", + "--source-set", + "test=e2e/**", + "--plugin-memory-mb", + "256", + "--plugin-timeout-ms", + "9000", + ], + ); + assert_setting(&with_cli, "budgets.production.erosion", json!(0.15), "cli"); + assert_setting( + &with_cli, + "budgets.production.duplication", + json!(0.1), + "file", + ); + assert_setting(&with_cli, "budgets.test.verbosity", json!(0.3), "cli"); + assert_setting(&with_cli, "source_sets.test", json!(["e2e/**"]), "cli"); + assert_setting(&with_cli, "source_sets.production", json!([]), "default"); + assert_setting(&with_cli, "plugin_limits.memory_mb", json!(256), "cli"); + assert_setting(&with_cli, "plugin_limits.timeout_ms", json!(9000), "cli"); + + let text = invoke_ok_stdout( + repo.path(), + &[ + "config", + "--resolved", + "--budget", + "production.erosion=0.15", + "--plugin-memory-mb", + "256", + ], + ); + assert!(text.contains("budgets.production.erosion = 0.15 [cli]")); + assert!(text.contains("budgets.production.duplication = 0.1 [file]")); + assert!(text.contains("plugin_limits.memory_mb = 256 [cli]")); + assert!(text.contains("plugin_limits.timeout_ms = 5000 [default]")); +} + +#[test] +fn config_resolved_rejects_invalid_config_invalid_override_and_non_repository() { + let bad_repo = init_repo_with_config(Some(json!({ "unknown_key": true }))); + let bad_cfg = invoke(bad_repo.path(), &["config", "--resolved"]); + assert_eq!(bad_cfg.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&bad_cfg.stderr).contains("unknown_key")); + + let good_repo = init_repo_with_config(None); + let bad_budget = invoke( + good_repo.path(), + &["config", "--resolved", "--budget", "production.erosion=1.5"], + ); + assert_eq!(bad_budget.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&bad_budget.stderr).contains("between 0 and 1")); + + let missing_flag = invoke(good_repo.path(), &["config"]); + assert_eq!(missing_flag.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&missing_flag.stderr).contains("--resolved")); + + let non_repo = TempDir::new().expect("tempdir outside git"); + let outside = invoke(non_repo.path(), &["config", "--resolved"]); + assert_eq!(outside.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&outside.stderr).contains("not inside a Git repository")); +} + +#[test] +fn config_resolved_accepts_subdirectory_path_argument() { + let repo = init_repo_with_config(Some(json!({ + "plugin_limits": { "memory_mb": 96 } + }))); + fs::create_dir_all(repo.path().join("src")).expect("create src dir"); + + let payload = resolved_json(repo.path(), &["src"]); + assert_eq!(payload["config_file_present"], true); + assert_setting(&payload, "plugin_limits.memory_mb", json!(96), "file"); +} diff --git a/crates/config/HOW-TO.md b/crates/config/HOW-TO.md index 35aaa11..62a0749 100644 --- a/crates/config/HOW-TO.md +++ b/crates/config/HOW-TO.md @@ -10,6 +10,7 @@ let configuration = read_configuration(repository.root())?; ``` - `read_configuration` reads `codeint.json` at the root of the repository, so pass the root of the working tree, never the folder the user named. +- `read_resolved_configuration` runs the same merge pipeline with `ConfigOverrides` and returns both the merged `Configuration` and per-field `ResolvedSetting` entries with `ConfigProvenance` (`default`, `file`, or `cli`). - It returns `Configuration::default()` when the file is absent; codeint runs with defaults. - Every other failure is a `ConfigurationFileError`, which stops the run with exit code 2. Its message names the key with its path, such as `source_sets.test[1]`, and the expected JSON type. diff --git a/crates/config/src/boundaries.rs b/crates/config/src/boundaries.rs index 66145b6..d5f329c 100644 --- a/crates/config/src/boundaries.rs +++ b/crates/config/src/boundaries.rs @@ -151,6 +151,9 @@ struct CompiledRule { #[derive(Debug, Clone)] pub struct Boundaries { + preset: Option, + resolved_zones: BTreeMap, + resolved_rules: Vec, zones: BTreeMap, rules: Vec, strict_zones: bool, @@ -159,12 +162,18 @@ pub struct Boundaries { impl Boundaries { pub(crate) fn from_file(file: BoundariesFile) -> Result { - let (merged_zones, merged_rules) = merge_preset(file.preset, file.zones, file.rules); + let preset = file.preset; + let (merged_zones, merged_rules) = merge_preset(preset, file.zones, file.rules); + let resolved_zones = merged_zones.clone(); + let resolved_rules = merged_rules.clone(); let boundaries_key = KeyPath::default().child(KeySegment::Key("boundaries".to_owned())); let zones = compile_zones(&boundaries_key, merged_zones)?; let rules = compile_rules(&boundaries_key, &zones, merged_rules)?; let source_sets = resolve_source_sets(file.source_sets); Ok(Boundaries { + preset, + resolved_zones, + resolved_rules, zones, rules, strict_zones: file.strict_zones, @@ -172,6 +181,22 @@ impl Boundaries { }) } + pub(crate) fn preset(&self) -> Option { + self.preset + } + + pub(crate) fn source_set_keys(&self) -> Vec<&'static str> { + self.source_sets.iter().map(|set| set.key()).collect() + } + + pub(crate) fn resolved_zones_json(&self) -> serde_json::Value { + serde_json::to_value(&self.resolved_zones).unwrap_or(serde_json::Value::Null) + } + + pub(crate) fn resolved_rules_json(&self) -> serde_json::Value { + serde_json::to_value(&self.resolved_rules).unwrap_or(serde_json::Value::Null) + } + pub fn applies_to_source_set(&self, source_set: SourceSet) -> bool { self.source_sets.contains(&source_set) } diff --git a/crates/config/src/codeint_json.rs b/crates/config/src/codeint_json.rs index 98d2f2d..ba7813c 100644 --- a/crates/config/src/codeint_json.rs +++ b/crates/config/src/codeint_json.rs @@ -9,10 +9,14 @@ use crate::config_error::{ CONFIGURATION_FILE_NAME, ConfigurationFileError, JsonType, KeyPath, KeySegment, glob_set, }; use crate::regression_limits::RegressionLimitSetting; +use crate::resolved::{ + BudgetOverride, ConfigOverrides, ConfigProvenance, ResolvedConfiguration, ResolvedSetting, + SourceSetOverride, resolve_with_provenance, +}; use globset::GlobSet; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use serde_json::Value; +use serde_json::{Value, json}; mod shape; mod starter; @@ -205,6 +209,10 @@ impl Budgets { } impl Budget { + pub fn new(ratio: f64) -> Option { + (ratio.is_finite() && (0.0..=1.0).contains(&ratio)).then_some(Budget(ratio)) + } + pub fn ratio(self) -> f64 { self.0 } @@ -590,9 +598,20 @@ struct SourceSetGlobs { } pub fn read_configuration(repository_root: &Path) -> Result { - match std::fs::read_to_string(repository_root.join(CONFIGURATION_FILE_NAME)) { - Ok(text) => parse(&text), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Configuration::default()), + read_resolved_configuration(repository_root, &ConfigOverrides::default()) + .map(|resolved| resolved.configuration) +} + +pub fn read_resolved_configuration( + repository_root: &Path, + overrides: &ConfigOverrides, +) -> Result { + let config_file = repository_root.join(CONFIGURATION_FILE_NAME); + match std::fs::read_to_string(&config_file) { + Ok(text) => parse_with_overrides(config_file, true, Some(&text), overrides), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + parse_with_overrides(config_file, false, None, overrides) + } Err(error) => Err(ConfigurationFileError::Unreadable(error)), } } @@ -602,31 +621,377 @@ pub fn configuration_schema() -> String { format!("{:#}\n", schema.as_value()) } -fn parse(text: &str) -> Result { - let value: Value = serde_json::from_str(text).map_err(ConfigurationFileError::NotJson)?; - check_schema_version(&value, env!("CARGO_PKG_VERSION"))?; - let schema = schemars::schema_for!(ConfigurationFile); - shape::check_shape(&value, schema.as_value())?; - let file: ConfigurationFile = - serde_json::from_value(value).map_err(ConfigurationFileError::NotJson)?; - let effective = file.without_schema_address(); +fn parse_with_overrides( + config_file: PathBuf, + config_file_present: bool, + text: Option<&str>, + overrides: &ConfigOverrides, +) -> Result { + let (raw, file) = match text { + Some(text) => { + let value: Value = + serde_json::from_str(text).map_err(ConfigurationFileError::NotJson)?; + check_schema_version(&value, env!("CARGO_PKG_VERSION"))?; + let schema = schemars::schema_for!(ConfigurationFile); + shape::check_shape(&value, schema.as_value())?; + let file: ConfigurationFile = + serde_json::from_value(value.clone()).map_err(ConfigurationFileError::NotJson)?; + (Some(value), file) + } + None => (None, ConfigurationFile::default()), + }; + let mut effective = file.without_schema_address(); + let mut settings = Vec::new(); + let source_set_overrides = merge_source_sets( + raw.as_ref(), + &mut effective.source_sets, + &overrides.source_sets, + &mut settings, + )?; + let budgets = merge_budgets(&mut effective.budgets, &overrides.budgets, &mut settings); + let regression_limits = regression_limits(file.regression_limits); + append_regression_limit_settings(®ression_limits, &mut settings); + append_languages_setting(&effective.languages, &mut settings); + let languages = languages(file.languages)?; + append_plugins_setting(raw.as_ref(), &effective.plugins, &mut settings); + let plugins = plugins(file.plugins)?; + let plugin_limits = merge_plugin_limits(&mut effective.plugin_limits, overrides, &mut settings); let parsed_boundaries = file.boundaries.map(Boundaries::from_file).transpose()?; - Ok(Configuration { + append_boundaries_settings(raw.as_ref(), parsed_boundaries.as_ref(), &mut settings); + let configuration = Configuration { effective, - source_set_overrides: source_set_overrides(file.source_sets)?, - budgets: budgets(file.budgets), - languages: languages(file.languages)?, - regression_limits: regression_limits(file.regression_limits), - plugins: plugins(file.plugins)?, - plugin_limits: plugin_limits(file.plugin_limits), + source_set_overrides, + budgets, + languages, + regression_limits, + plugins, + plugin_limits, boundaries: parsed_boundaries, + }; + Ok(ResolvedConfiguration { + config_file, + config_file_present, + configuration, + settings, }) } -fn plugin_limits(file: PluginLimitsFile) -> PluginLimits { +const ORDERED_SOURCE_SETS: [SourceSet; 4] = [ + SourceSet::Production, + SourceSet::Test, + SourceSet::Generated, + SourceSet::Vendored, +]; + +fn has_json_path(raw: Option<&Value>, path: &[&str]) -> bool { + let mut current = match raw { + Some(value) => value, + None => return false, + }; + for segment in path { + match current.get(*segment) { + Some(next) => current = next, + None => return false, + } + } + true +} + +fn push_setting( + settings: &mut Vec, + key: impl Into, + value: Value, + source: ConfigProvenance, +) { + settings.push(ResolvedSetting { + key: key.into(), + value, + source, + }); +} + +fn merge_source_sets( + raw: Option<&Value>, + globs: &mut SourceSetGlobs, + overrides: &[SourceSetOverride], + settings: &mut Vec, +) -> Result { + let cli_by_set = group_source_set_overrides(overrides); + let slots = [ + (SourceSet::Production, &mut globs.production), + (SourceSet::Test, &mut globs.test), + (SourceSet::Generated, &mut globs.generated), + (SourceSet::Vendored, &mut globs.vendored), + ]; + for (source_set, slot) in slots { + let source = if let Some(cli_globs) = cli_by_set.get(&source_set) { + *slot = cli_globs.clone(); + ConfigProvenance::Cli + } else if has_json_path(raw, &["source_sets", source_set.key()]) { + ConfigProvenance::File + } else { + ConfigProvenance::Default + }; + push_setting( + settings, + format!("source_sets.{}", source_set.key()), + json!(slot), + source, + ); + } + source_set_overrides(globs.clone()) +} + +fn group_source_set_overrides(overrides: &[SourceSetOverride]) -> BTreeMap> { + let mut grouped: BTreeMap> = BTreeMap::new(); + for entry in overrides { + grouped + .entry(entry.source_set) + .or_default() + .push(entry.glob.clone()); + } + grouped +} + +fn merge_budgets( + file_budgets: &mut SourceSetBudgets, + overrides: &[BudgetOverride], + settings: &mut Vec, +) -> Budgets { + let mut resolved: BTreeMap<(SourceSet, String), (Budget, ConfigProvenance)> = BTreeMap::new(); + for (source_set, metric, budget) in budgets(file_budgets.clone()).set { + resolved.insert((source_set, metric), (budget, ConfigProvenance::File)); + } + for entry in overrides { + file_budgets.set(entry.source_set, &entry.metric, entry.budget); + resolved.insert( + (entry.source_set, entry.metric.clone()), + (entry.budget, ConfigProvenance::Cli), + ); + } + if resolved.is_empty() { + push_setting(settings, "budgets", json!({}), ConfigProvenance::Default); + } else { + for source_set in ORDERED_SOURCE_SETS { + for ((set, metric), (budget, source)) in &resolved { + if *set == source_set { + push_setting( + settings, + format!("budgets.{}.{metric}", source_set.key()), + json!(budget.ratio()), + *source, + ); + } + } + } + } + Budgets { + set: resolved + .into_iter() + .map(|((source_set, metric), (budget, _))| (source_set, metric, budget)) + .collect(), + } +} + +fn append_regression_limit_settings( + limits: &RegressionLimits, + settings: &mut Vec, +) { + let mut metric_keys: Vec = Metric::BUILT_IN_KEYS + .iter() + .chain(["boundaries"].iter()) + .map(|key| (*key).to_owned()) + .collect(); + metric_keys.extend(limits.extra_metric_keys()); + for source_set in ORDERED_SOURCE_SETS { + for metric_key in &metric_keys { + let resolved = limits.resolved_limit_for_key(source_set, metric_key); + let prefix = format!("regression_limits.{}.{metric_key}", source_set.key()); + push_setting( + settings, + format!("{prefix}.ratio_rise"), + json!(resolved.limit.ratio_rise.ratio()), + resolved.ratio_rise_source, + ); + push_setting( + settings, + format!("{prefix}.new_findings"), + json!(resolved.limit.new_findings), + resolved.new_findings_source, + ); + } + } +} + +fn append_languages_setting( + entries: &Option>, + settings: &mut Vec, +) { + match entries { + Some(entries) => push_setting( + settings, + "languages", + serde_json::to_value(entries).unwrap_or(Value::Null), + ConfigProvenance::File, + ), + None => push_setting( + settings, + "languages", + Value::Null, + ConfigProvenance::Default, + ), + } +} + +fn append_plugins_setting( + raw: Option<&Value>, + entries: &[PluginEntry], + settings: &mut Vec, +) { + let source = if has_json_path(raw, &["plugins"]) { + ConfigProvenance::File + } else { + ConfigProvenance::Default + }; + push_setting( + settings, + "plugins", + serde_json::to_value(entries).unwrap_or_else(|_| json!([])), + source, + ); +} + +fn merge_plugin_limits( + file: &mut PluginLimitsFile, + overrides: &ConfigOverrides, + settings: &mut Vec, +) -> PluginLimits { + let (memory_mb, memory_source) = resolve_with_provenance( + DEFAULT_PLUGIN_MEMORY_MB, + file.memory_mb, + overrides.plugin_memory_mb, + ); + let (timeout_ms, timeout_source) = resolve_with_provenance( + DEFAULT_PLUGIN_TIMEOUT_MS, + file.timeout_ms, + overrides.plugin_timeout_ms, + ); + if let Some(value) = overrides.plugin_memory_mb { + file.memory_mb = Some(value); + } + if let Some(value) = overrides.plugin_timeout_ms { + file.timeout_ms = Some(value); + } + push_setting( + settings, + "plugin_limits.memory_mb", + json!(memory_mb), + memory_source, + ); + push_setting( + settings, + "plugin_limits.timeout_ms", + json!(timeout_ms), + timeout_source, + ); PluginLimits { - memory_mb: file.memory_mb.unwrap_or(DEFAULT_PLUGIN_MEMORY_MB), - timeout_ms: file.timeout_ms.unwrap_or(DEFAULT_PLUGIN_TIMEOUT_MS), + memory_mb, + timeout_ms, + } +} + +fn append_boundaries_settings( + raw: Option<&Value>, + boundaries: Option<&Boundaries>, + settings: &mut Vec, +) { + let Some(boundaries) = boundaries else { + push_setting( + settings, + "boundaries", + Value::Null, + ConfigProvenance::Default, + ); + return; + }; + let preset_source = if boundaries.preset().is_some() { + ConfigProvenance::File + } else { + ConfigProvenance::Default + }; + push_setting( + settings, + "boundaries.preset", + serde_json::to_value(boundaries.preset()).unwrap_or(Value::Null), + preset_source, + ); + let strict_source = if has_json_path(raw, &["boundaries", "strict_zones"]) { + ConfigProvenance::File + } else { + ConfigProvenance::Default + }; + push_setting( + settings, + "boundaries.strict_zones", + json!(boundaries.strict_zones()), + strict_source, + ); + let has_non_empty_source_sets = raw + .and_then(|value| value.get("boundaries")) + .and_then(|value| value.get("source_sets")) + .and_then(Value::as_array) + .is_some_and(|items| !items.is_empty()); + let source_sets_source = if has_non_empty_source_sets { + ConfigProvenance::File + } else { + ConfigProvenance::Default + }; + push_setting( + settings, + "boundaries.source_sets", + json!(boundaries.source_set_keys()), + source_sets_source, + ); + push_setting( + settings, + "boundaries.zones", + boundaries.resolved_zones_json(), + ConfigProvenance::File, + ); + push_setting( + settings, + "boundaries.rules", + boundaries.resolved_rules_json(), + ConfigProvenance::File, + ); +} + +impl SourceSetBudgets { + fn set(&mut self, source_set: SourceSet, metric: &str, budget: Budget) { + let slots = [ + (SourceSet::Production, &mut self.production), + (SourceSet::Test, &mut self.test), + (SourceSet::Generated, &mut self.generated), + (SourceSet::Vendored, &mut self.vendored), + ]; + if let Some((_, target)) = slots.into_iter().find(|(set, _)| *set == source_set) { + target.set(metric, budget); + } + } +} + +impl MetricBudgets { + fn set(&mut self, metric: &str, budget: Budget) { + match metric { + "erosion" => self.erosion = Some(budget), + "duplication" => self.duplication = Some(budget), + "verbosity" => self.verbosity = Some(budget), + "import_cycles" => self.import_cycles = Some(budget), + "boundaries" => self.boundaries = Some(budget), + other => { + self.external.insert(other.to_owned(), budget); + } + } } } diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 642a0b3..2a2f192 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -9,6 +9,7 @@ mod calendar_day; mod codeint_json; mod config_error; mod regression_limits; +mod resolved; mod result_cache_folder; pub use boundaries::{ @@ -19,10 +20,14 @@ pub use codeint_json::{ Budget, Budgets, Configuration, DetectedLanguage, LanguageCoverage, Languages, PluginDeclaration, PluginKind, PluginLimits, PluginSource, Sha256Digest, SourceSetOverrides, StarterConfigurationError, configuration_schema, published_schema_address, read_configuration, - write_starter_configuration, + read_resolved_configuration, write_starter_configuration, }; pub use config_error::{ConfigurationFileError, JsonType, KeyPath, KeySegment}; pub use regression_limits::{NewFindingsRule, RatioRise, RegressionLimit, RegressionLimits}; +pub use resolved::{ + BudgetOverride, ConfigOverrides, ConfigProvenance, ResolvedConfiguration, ResolvedSetting, + SourceSetOverride, +}; const DEFAULT_PLUGIN_DOWNLOAD_TIMEOUT_SECONDS: u64 = 60; @@ -105,6 +110,13 @@ pub enum GuardFormat { Json, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] +pub enum ConfigFormat { + Text, + Toon, + Json, +} + const LATEST_COMMITS_OF_A_TREND: usize = 20; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -113,7 +125,7 @@ pub enum TrendRange { Since(CalendarDay), } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq)] pub enum Command { Check { folder: PathBuf, @@ -158,6 +170,11 @@ pub enum Command { target: PathBuf, format: GuardFormat, }, + Config { + folder: PathBuf, + format: ConfigFormat, + overrides: ConfigOverrides, + }, } #[derive(Debug)] @@ -268,6 +285,54 @@ enum CommandArguments { )] format: GuardFormat, }, + #[command( + about = "Inspect the effective active configuration and where each setting came from" + )] + Config { + #[arg( + help = "A folder inside the Git repository to inspect; the current folder by default" + )] + path: Option, + #[arg( + long, + required = true, + help = "Print the effective active configuration and per-field provenance" + )] + resolved: bool, + #[arg( + long, + value_enum, + default_value_t = ConfigFormat::Text, + help = "The format of the output" + )] + format: ConfigFormat, + #[arg( + long = "budget", + value_name = "SPEC", + help = "Override a Budget ratio as SOURCE_SET.METRIC=RATIO" + )] + budgets: Vec, + #[arg( + long = "source-set", + value_name = "SPEC", + help = "Override a Source set glob as SOURCE_SET=GLOB" + )] + source_sets: Vec, + #[arg( + long = "plugin-memory-mb", + value_name = "MB", + value_parser = clap::value_parser!(u64).range(1..=4096), + help = "Override plugin_limits.memory_mb (1 to 4096)" + )] + plugin_memory_mb: Option, + #[arg( + long = "plugin-timeout-ms", + value_name = "MS", + value_parser = clap::value_parser!(u64).range(1..=300_000), + help = "Override plugin_limits.timeout_ms (1 to 300000)" + )] + plugin_timeout_ms: Option, + }, } #[derive(Debug, clap::Args)] @@ -328,6 +393,24 @@ fn build_command( target: path, format, }), + CommandArguments::Config { + path, + resolved: _, + format, + budgets, + source_sets, + plugin_memory_mb, + plugin_timeout_ms, + } => Ok(Command::Config { + folder: existing_folder(current_folder, path)?, + format, + overrides: ConfigOverrides { + budgets, + source_sets, + plugin_memory_mb, + plugin_timeout_ms, + }, + }), } } diff --git a/crates/config/src/regression_limits.rs b/crates/config/src/regression_limits.rs index 5d9cbdf..e9238f1 100644 --- a/crates/config/src/regression_limits.rs +++ b/crates/config/src/regression_limits.rs @@ -1,7 +1,12 @@ +use std::collections::BTreeSet; + use codeint_model::{Metric, SourceSet}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; +use crate::ConfigProvenance; +use crate::resolved::resolve_with_provenance; + #[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)] #[serde(transparent)] pub struct RatioRise(f64); @@ -74,16 +79,6 @@ impl RegressionLimit { RegressionLimit::DEFAULT } } - - fn overridden_by(self, setting: Option) -> RegressionLimit { - let Some(setting) = setting else { - return self; - }; - RegressionLimit { - ratio_rise: setting.ratio_rise.unwrap_or(self.ratio_rise), - new_findings: setting.new_findings.unwrap_or(self.new_findings), - } - } } impl RegressionLimitSetting { @@ -108,6 +103,14 @@ impl RegressionLimits { } pub fn limit_for_key(&self, source_set: SourceSet, metric_key: &str) -> RegressionLimit { + self.resolved_limit_for_key(source_set, metric_key).limit + } + + pub(crate) fn resolved_limit_for_key( + &self, + source_set: SourceSet, + metric_key: &str, + ) -> ResolvedRegressionLimit { let for_every_source_set = self .every_source_set .iter() @@ -118,9 +121,39 @@ impl RegressionLimits { .iter() .find(|(set_in, set_for, _)| *set_in == source_set && set_for == metric_key) .map(|(_, _, setting)| *setting); - RegressionLimit::default_for_key(metric_key) - .overridden_by(for_every_source_set) - .overridden_by(for_this_source_set) + let base = RegressionLimit::default_for_key(metric_key); + let (ratio_rise, ratio_rise_source) = resolve_with_provenance( + base.ratio_rise, + for_this_source_set + .and_then(|setting| setting.ratio_rise) + .or_else(|| for_every_source_set.and_then(|setting| setting.ratio_rise)), + None, + ); + let (new_findings, new_findings_source) = resolve_with_provenance( + base.new_findings, + for_this_source_set + .and_then(|setting| setting.new_findings) + .or_else(|| for_every_source_set.and_then(|setting| setting.new_findings)), + None, + ); + ResolvedRegressionLimit { + limit: RegressionLimit { + ratio_rise, + new_findings, + }, + ratio_rise_source, + new_findings_source, + } + } + + pub(crate) fn extra_metric_keys(&self) -> Vec { + let mut keys = BTreeSet::new(); + for (_, key) in self.metric_keys() { + if !Metric::BUILT_IN_KEYS.contains(&key) && key != "boundaries" { + keys.insert(key.to_owned()); + } + } + keys.into_iter().collect() } pub(crate) fn metric_keys(&self) -> impl Iterator, &str)> { @@ -134,3 +167,10 @@ impl RegressionLimits { ) } } + +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) struct ResolvedRegressionLimit { + pub(crate) limit: RegressionLimit, + pub(crate) ratio_rise_source: ConfigProvenance, + pub(crate) new_findings_source: ConfigProvenance, +} diff --git a/crates/config/src/resolved.rs b/crates/config/src/resolved.rs new file mode 100644 index 0000000..853242f --- /dev/null +++ b/crates/config/src/resolved.rs @@ -0,0 +1,140 @@ +use std::fmt; +use std::path::PathBuf; +use std::str::FromStr; + +use codeint_model::SourceSet; +use serde::Serialize; +use serde_json::Value; + +use crate::{Budget, Configuration}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ConfigProvenance { + Default, + File, + Cli, +} + +impl ConfigProvenance { + pub fn label(self) -> &'static str { + match self { + ConfigProvenance::Default => "default", + ConfigProvenance::File => "file", + ConfigProvenance::Cli => "cli", + } + } +} + +impl fmt::Display for ConfigProvenance { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.label()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ResolvedSetting { + pub key: String, + pub value: Value, + pub source: ConfigProvenance, +} + +#[derive(Debug)] +pub struct ResolvedConfiguration { + pub config_file: PathBuf, + pub config_file_present: bool, + pub configuration: Configuration, + pub settings: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct BudgetOverride { + pub source_set: SourceSet, + pub metric: String, + pub budget: Budget, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SourceSetOverride { + pub source_set: SourceSet, + pub glob: String, +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct ConfigOverrides { + pub budgets: Vec, + pub source_sets: Vec, + pub plugin_memory_mb: Option, + pub plugin_timeout_ms: Option, +} + +impl FromStr for BudgetOverride { + type Err = String; + + fn from_str(raw: &str) -> Result { + let (target, ratio_text) = raw.split_once('=').ok_or_else(|| { + format!("{raw:?} must use SOURCE_SET.METRIC=RATIO, such as production.erosion=0.25") + })?; + let (source_set_text, metric) = target.split_once('.').ok_or_else(|| { + format!("{target:?} must name SOURCE_SET.METRIC, such as production.erosion") + })?; + let source_set = parse_source_set(source_set_text)?; + if metric.trim().is_empty() || metric.contains('.') { + return Err(format!("{metric:?} is not a valid Metric key in {raw:?}")); + } + let ratio: f64 = ratio_text + .parse() + .map_err(|_| format!("{ratio_text:?} is not a number between 0 and 1"))?; + let budget = Budget::new(ratio) + .ok_or_else(|| format!("Budget ratio must be between 0 and 1, not {ratio}"))?; + Ok(BudgetOverride { + source_set, + metric: metric.to_owned(), + budget, + }) + } +} + +impl FromStr for SourceSetOverride { + type Err = String; + + fn from_str(raw: &str) -> Result { + let (source_set_text, glob) = raw + .split_once('=') + .ok_or_else(|| format!("{raw:?} must use SOURCE_SET=GLOB, such as test=spec/**"))?; + let source_set = parse_source_set(source_set_text)?; + if glob.trim().is_empty() { + return Err(format!("glob in {raw:?} must not be empty")); + } + Ok(SourceSetOverride { + source_set, + glob: glob.to_owned(), + }) + } +} + +pub(crate) fn parse_source_set(name: &str) -> Result { + match name { + "production" => Ok(SourceSet::Production), + "test" => Ok(SourceSet::Test), + "generated" => Ok(SourceSet::Generated), + "vendored" => Ok(SourceSet::Vendored), + _ => Err(format!( + "{name:?} is not a Source set; use one of production, test, generated, vendored" + )), + } +} + +pub(crate) fn resolve_with_provenance( + default: T, + from_file: Option, + from_cli: Option, +) -> (T, ConfigProvenance) { + if let Some(value) = from_cli { + return (value, ConfigProvenance::Cli); + } + if let Some(value) = from_file { + return (value, ConfigProvenance::File); + } + (default, ConfigProvenance::Default) +} diff --git a/crates/report/src/config.rs b/crates/report/src/config.rs new file mode 100644 index 0000000..e7766f2 --- /dev/null +++ b/crates/report/src/config.rs @@ -0,0 +1,45 @@ +use codeint_config::{ConfigFormat, ResolvedConfiguration, ResolvedSetting}; +use serde::Serialize; + +use crate::ReportError; + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ConfigReport { + config_file: String, + config_file_present: bool, + settings: Vec, +} + +impl ConfigReport { + pub fn from_resolved(resolved: &ResolvedConfiguration) -> ConfigReport { + ConfigReport { + config_file: resolved.config_file.display().to_string(), + config_file_present: resolved.config_file_present, + settings: resolved.settings.clone(), + } + } + + pub fn render(&self, format: ConfigFormat) -> Result { + match format { + ConfigFormat::Text => Ok(self.format_lines()), + ConfigFormat::Toon => crate::encode_toon(self), + ConfigFormat::Json => crate::encode_json(self), + } + } + + fn format_lines(&self) -> String { + let mut lines = Vec::with_capacity(self.settings.len() + 2); + let state = if self.config_file_present { + "loaded" + } else { + "not found; using defaults" + }; + lines.push(format!("config_file: {} ({state})", self.config_file)); + lines.push("settings:".to_owned()); + for setting in &self.settings { + let value = serde_json::to_string(&setting.value).unwrap_or_else(|_| "null".to_owned()); + lines.push(format!(" {} = {value} [{}]", setting.key, setting.source)); + } + lines.join("\n") + } +} diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index ec6083c..1cdc2b7 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -18,6 +18,7 @@ use codeint_model::{ use serde::ser::SerializeMap; use serde::{Deserialize, Serialize, Serializer}; +mod config; mod diff; mod guard; mod markdown; @@ -27,6 +28,7 @@ mod sarif; mod tests; mod trend; +pub use config::ConfigReport; pub use diff::{BaseCommit, DiffReport, Head, HeadCommit}; pub use guard::{GuardAllowedTarget, GuardDeniedTarget, GuardReport}; pub use measurement::CommitMeasurement; @@ -47,6 +49,14 @@ pub enum ReportError { Sarif(#[source] serde_json::Error), } +pub(crate) fn encode_toon(value: &T) -> Result { + toon_format::encode_default(value).map_err(ReportError::Toon) +} + +pub(crate) fn encode_json(value: &T) -> Result { + serde_json::to_string_pretty(value).map_err(ReportError::Json) +} + #[derive(Debug, Serialize)] pub struct Report { #[serde(flatten)] diff --git a/docs/reference.md b/docs/reference.md index 92e93a0..3eacd15 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -30,6 +30,7 @@ The working tree adds `src/route.ts`, an eroded function that is not committed. | `update` | Update a standalone codeint binary in place from GitHub Releases; see [`codeint update`](#codeint-update) | | `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, `trend`, and `guard` tools; see [`codeint mcp`](#codeint-mcp) | | `guard` | Show the architectural boundary zone, allowed and denied target zones, `public_files` constraints, and allowed importers for a file path; see [`codeint guard`](#codeint-guard) | +| `config` | Inspect the effective active configuration and where each setting came from; see [`codeint config`](#codeint-config) | | `help` | Print the help of codeint, or of the command that follows it | | Option | Meaning | @@ -514,6 +515,31 @@ codeint guard src/route.ts --format toon codeint guard src/route.ts --format json ``` +### `codeint config` + +| Argument | Meaning | +| -------- | ------- | +| `[PATH]` | A folder inside the Git repository to inspect; the current folder by default | + +| Option | Meaning | +| ------ | ------- | +| `--resolved` | Print the effective active configuration and per-field provenance | +| `--format ` | The format of the output: `text`, the default, `toon`, or `json` | +| `--budget ` | Override a Budget ratio as `SOURCE_SET.METRIC=RATIO` | +| `--source-set ` | Override a Source set glob as `SOURCE_SET=GLOB` | +| `--plugin-memory-mb ` | Override `plugin_limits.memory_mb` (1 to 4096) | +| `--plugin-timeout-ms ` | Override `plugin_limits.timeout_ms` (1 to 300000) | +| `-h, --help` | Print the help of `codeint config` | + +`codeint config --resolved` prints every effective active setting merged from built-in defaults, `codeint.json`, and CLI overrides alongside its provenance (`default`, `file`, or `cli`). + +```sh exit=0 +codeint config --resolved +codeint config --resolved src --format text +codeint config --resolved --format toon +codeint config --resolved --format json --budget production.erosion=0.25 --source-set test=spec/** --plugin-memory-mb 128 --plugin-timeout-ms 10000 +``` + ## Exit codes | Exit code | Meaning | From d30ac66bef682d1ef7c76aed42ab36922323f3c9 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 09:45:34 +0800 Subject: [PATCH 3/6] feat(cli): add read-only codeint doctor command Add read-only offline diagnostics for Git repository status, codeint.json validity, $schema version compatibility, detected Language plugins, Workspace packages, and external Wasm Plugin paths and SHA-256 digests across text, JSON, and TOON formats. Closes #188 --- crates/cli/src/check.rs | 4 +- crates/cli/src/doctor.rs | 414 ++++++++++++++++++++++++++++++ crates/cli/src/lib.rs | 29 ++- crates/cli/src/remedy.rs | 4 +- crates/cli/tests/doctor.rs | 341 ++++++++++++++++++++++++ crates/config/src/codeint_json.rs | 112 +++++++- crates/config/src/lib.rs | 38 ++- crates/report/src/doctor.rs | 182 +++++++++++++ crates/report/src/guard.rs | 8 +- crates/report/src/lib.rs | 44 +++- docs/reference.md | 27 +- 11 files changed, 1178 insertions(+), 25 deletions(-) create mode 100644 crates/cli/src/doctor.rs create mode 100644 crates/cli/tests/doctor.rs create mode 100644 crates/report/src/doctor.rs diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index f678623..34729d6 100644 --- a/crates/cli/src/check.rs +++ b/crates/cli/src/check.rs @@ -388,7 +388,7 @@ fn first_two_plugin_names( (names[0].to_owned(), names[1].to_owned()) } -fn read_manifests( +pub(crate) fn read_manifests( tree: &Snapshot, plugins: &[NamedLanguagePlugin<'_>], ) -> Result>, CheckError> { @@ -409,7 +409,7 @@ fn read_manifests( .collect() } -fn find_workspace( +pub(crate) fn find_workspace( plugins: &[NamedLanguagePlugin<'_>], manifests_by_plugin: &[Vec], ) -> Result { diff --git a/crates/cli/src/doctor.rs b/crates/cli/src/doctor.rs new file mode 100644 index 0000000..5bbbd76 --- /dev/null +++ b/crates/cli/src/doctor.rs @@ -0,0 +1,414 @@ +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; + +use codeint_config::{ + Configuration, ConfigurationInspection, LanguageCoverage, PluginDeclaration, PluginHostConfig, + PluginKind, PluginSource, SchemaVersionStatus, inspect_configuration, +}; +use codeint_git::{GitError, Repository, Snapshot}; +use codeint_plugin_host::{sha256, sha256_hex}; +use codeint_report::{DoctorCheck, DoctorReport}; + +use crate::check::{BUILT_IN_LANGUAGE_PLUGINS, find_workspace, read_manifests}; +use crate::describe; +use crate::remedy::{configuration_file_remedy, git_remedy}; + +const NEWER_SCHEMA_REMEDY: &str = "Run codeint update (or upgrade the codeint npm package) to match or exceed the $schema version, or lower the $schema tag in codeint.json."; + +pub(crate) fn doctor(folder: &Path, plugin_host: &PluginHostConfig) -> DoctorReport { + let mut checks = Vec::new(); + let (git_check, repository, root) = check_git(folder); + checks.push(git_check); + + let (config_checks, configuration) = check_configuration(&root); + checks.extend(config_checks); + + if let Some(repository) = &repository { + checks.extend(check_repository_contents( + repository, + configuration.as_ref(), + )); + } + + if let Some(configuration) = &configuration { + checks.extend(check_plugins(&root, configuration, plugin_host)); + } else if repository.is_some() && !root.join("codeint.json").exists() { + checks.push(DoctorCheck::pass( + "plugins", + "No external Wasm Plugins configured", + )); + } + + DoctorReport::new( + env!("CARGO_PKG_VERSION"), + root.display().to_string(), + checks, + ) +} + +fn check_git(folder: &Path) -> (DoctorCheck, Option, PathBuf) { + match Repository::discover(folder) { + Ok(repository) => { + let root = repository.root().to_path_buf(); + let check = DoctorCheck::pass( + "git", + format!("Git repository detected at {}", root.display()), + ); + (check, Some(repository), root) + } + Err(GitError::NotInRepository { .. }) => { + let check = DoctorCheck::warn("git", "Not inside a Git repository") + .with_detail( + "codeint check, diff, trend, and init require a Git repository; diagnostics below inspect the target directory directly.", + ) + .with_remedy("Run git init or run codeint doctor inside a Git repository."); + (check, None, folder.to_path_buf()) + } + Err(error) => { + let check = DoctorCheck::error("git", describe(&error)).with_remedy(git_remedy(&error)); + (check, None, folder.to_path_buf()) + } + } +} + +fn check_configuration(root: &Path) -> (Vec, Option) { + match inspect_configuration(root) { + ConfigurationInspection::Missing { .. } => { + let check = + DoctorCheck::warn("config", "No codeint.json found; using built-in defaults") + .with_remedy("Run codeint init to write a starter codeint.json."); + (vec![check], None) + } + ConfigurationInspection::Valid { + schema, + configuration, + .. + } => { + let checks = valid_configuration_checks(&schema, &configuration); + (checks, Some(*configuration)) + } + ConfigurationInspection::Invalid { schema, error, .. } => { + let config_check = DoctorCheck::error("config", describe(&error)) + .with_remedy(configuration_file_remedy(&error)); + let mut checks = vec![config_check]; + if let Some(schema_status) = schema { + checks.push(schema_check(&schema_status)); + } + (checks, None) + } + } +} + +fn valid_configuration_checks( + schema: &SchemaVersionStatus, + configuration: &Configuration, +) -> Vec { + let has_external_metrics = configuration + .plugins + .iter() + .any(|plugin| plugin.kind == PluginKind::Metric); + let config_check = + if !has_external_metrics && let Err(error) = configuration.validate_metrics(&[]) { + DoctorCheck::error("config", describe(&error)) + .with_remedy(configuration_file_remedy(&error)) + } else { + DoctorCheck::pass("config", "codeint.json is valid") + }; + vec![config_check, schema_check(schema)] +} + +fn schema_check(status: &SchemaVersionStatus) -> DoctorCheck { + let binary_version = env!("CARGO_PKG_VERSION"); + match status { + SchemaVersionStatus::Missing => { + DoctorCheck::pass("schema", "No $schema set in codeint.json (optional)") + } + SchemaVersionStatus::Compatible { + url, + version: Some(version), + } => DoctorCheck::pass( + "schema", + format!("$schema targets codeint v{version} (compatible with v{binary_version})"), + ) + .with_detail(url.clone()), + SchemaVersionStatus::Compatible { url, version: None } => { + DoctorCheck::pass("schema", "Custom $schema configured").with_detail(url.clone()) + } + SchemaVersionStatus::NewerThanBinary { + url, + config_version, + binary_version, + } => DoctorCheck::error( + "schema", + format!( + "codeint.json targets codeint v{config_version} via $schema, which is newer than this binary (v{binary_version})" + ), + ) + .with_detail(url.clone()) + .with_remedy(NEWER_SCHEMA_REMEDY), + } +} + +fn check_repository_contents( + repository: &Repository, + configuration: Option<&Configuration>, +) -> Vec { + let tree = match repository.working_tree() { + Ok(tree) => tree, + Err(error) => { + return vec![ + DoctorCheck::error("languages", describe(&error)).with_remedy(git_remedy(&error)), + ]; + } + }; + vec![ + check_languages(&tree, configuration), + check_workspace(&tree), + ] +} + +fn check_languages(tree: &Snapshot, configuration: Option<&Configuration>) -> DoctorCheck { + let mut plugin_names: Vec<&str> = BUILT_IN_LANGUAGE_PLUGINS + .iter() + .map(|plugin| plugin.name) + .collect(); + if let Some(config) = configuration { + for plugin in &config.plugins { + if plugin.kind == PluginKind::Language && !plugin_names.contains(&plugin.name.as_str()) + { + plugin_names.push(plugin.name.as_str()); + } + } + } + let default_config = Configuration::default(); + let languages = &configuration.unwrap_or(&default_config).languages; + let coverage = match languages.coverage_of(&plugin_names) { + Ok(coverage) => coverage, + Err(error) => { + return DoctorCheck::error("languages", describe(&error)) + .with_remedy(configuration_file_remedy(&error)); + } + }; + let counts = count_language_files(tree, &coverage); + if counts.is_empty() { + return DoctorCheck::warn( + "languages", + "No measurable source files matched by any built-in Language plugin", + ); + } + let total_files: usize = counts.iter().map(|(_, count)| *count).sum(); + let breakdown: Vec = counts + .iter() + .map(|(name, count)| format!("{name}: {count}")) + .collect(); + DoctorCheck::pass( + "languages", + format!( + "Detected {} Language {} across {} {} ({})", + counts.len(), + if counts.len() == 1 { + "plugin" + } else { + "plugins" + }, + total_files, + if total_files == 1 { "file" } else { "files" }, + breakdown.join(", ") + ), + ) +} + +fn count_language_files( + tree: &Snapshot, + coverage: &[LanguageCoverage<'_>], +) -> Vec<(String, usize)> { + let mut counts = Vec::new(); + for (index, named) in BUILT_IN_LANGUAGE_PLUGINS.iter().enumerate() { + let extensions = named.plugin.extensions(); + let matched = tree + .files() + .iter() + .filter(|path| { + path.extension() + .is_some_and(|ext| extensions.iter().any(|c| c == ext)) + && coverage[index].covers(path) + }) + .count(); + if matched > 0 { + counts.push((named.name.to_owned(), matched)); + } + } + counts +} + +fn check_workspace(tree: &Snapshot) -> DoctorCheck { + let manifests = match read_manifests(tree, &BUILT_IN_LANGUAGE_PLUGINS) { + Ok(manifests) => manifests, + Err(error) => { + return DoctorCheck::error("workspace", describe(&error)); + } + }; + let workspace = match find_workspace(&BUILT_IN_LANGUAGE_PLUGINS, &manifests) { + Ok(workspace) => workspace, + Err(error) => { + return DoctorCheck::error("workspace", describe(&error)).with_remedy( + "Fix the manifest that the message names so that your package manager accepts it.", + ); + } + }; + if !workspace.has_members() { + return DoctorCheck::pass( + "workspace", + "Single-package repository (no Workspace packages)", + ); + } + let members: Vec = workspace + .member_roots() + .map(|root| root.as_str().to_owned()) + .collect(); + DoctorCheck::pass( + "workspace", + format!( + "Discovered {} Workspace {}", + members.len(), + if members.len() == 1 { + "package" + } else { + "packages" + } + ), + ) + .with_detail(members.join(", ")) +} + +fn check_plugins( + root: &Path, + configuration: &Configuration, + plugin_host: &PluginHostConfig, +) -> Vec { + if configuration.plugins.is_empty() { + return vec![DoctorCheck::pass( + "plugins", + "No external Wasm Plugins configured", + )]; + } + let mut seen_names: BTreeSet = BUILT_IN_LANGUAGE_PLUGINS + .iter() + .map(|plugin| plugin.name.to_owned()) + .collect(); + configuration + .plugins + .iter() + .map(|declaration| check_single_plugin(root, declaration, &mut seen_names, plugin_host)) + .collect() +} + +fn check_single_plugin( + root: &Path, + declaration: &PluginDeclaration, + seen_names: &mut BTreeSet, + plugin_host: &PluginHostConfig, +) -> DoctorCheck { + let id = format!("plugin:{}", declaration.name); + if !seen_names.insert(declaration.name.clone()) { + return DoctorCheck::error( + id, + format!( + "External Wasm Plugin {:?} duplicates an existing Plugin name", + declaration.name + ), + ) + .with_remedy( + "Give each external plugin in codeint.json a unique name that does not collide with built-in plugins.", + ); + } + match &declaration.source { + PluginSource::Path(declared_path) => { + let resolved = if declared_path.is_absolute() { + declared_path.clone() + } else { + root.join(declared_path) + }; + verify_plugin_file( + id, + &declaration.name, + &resolved, + &declaration.sha256.to_hex(), + &declared_path.display().to_string(), + ) + } + PluginSource::HttpsUrl(url) => check_remote_plugin(id, declaration, url, plugin_host), + } +} + +fn check_remote_plugin( + id: String, + declaration: &PluginDeclaration, + url: &str, + plugin_host: &PluginHostConfig, +) -> DoctorCheck { + let expected = declaration.sha256.to_hex(); + let cached_path = plugin_host + .cache_dir + .as_ref() + .map(|dir| dir.join(format!("{expected}.wasm"))); + if let Some(path) = cached_path + && path.exists() + { + return verify_plugin_file( + id, + &declaration.name, + &path, + &expected, + &format!("cached from {url}"), + ); + } + DoctorCheck::warn( + id, + format!( + "External Wasm Plugin {:?} is not cached locally yet", + declaration.name + ), + ) + .with_detail(format!( + "url: {url} (doctor runs offline and does not download remote plugins)" + )) + .with_remedy("Run codeint check to download and verify this plugin into the local cache.") +} + +fn verify_plugin_file( + id: String, + name: &str, + resolved_path: &Path, + expected_hex: &str, + label: &str, +) -> DoctorCheck { + let bytes = match std::fs::read(resolved_path) { + Ok(bytes) => bytes, + Err(error) => { + return DoctorCheck::error( + id, + format!("Cannot read external Wasm Plugin {name:?} at {label}: {error}"), + ) + .with_remedy( + "Check that the plugin path in codeint.json points to an existing readable WebAssembly component file.", + ); + } + }; + let actual_hex = sha256_hex(&sha256(&bytes)); + if actual_hex != expected_hex { + return DoctorCheck::error( + id, + format!("SHA-256 hash mismatch for external Wasm Plugin {name:?} at {label}"), + ) + .with_detail(format!("expected {expected_hex}, found {actual_hex}")) + .with_remedy( + "Verify the plugin file has not been modified, then update sha256 in codeint.json to match the trusted file.", + ); + } + DoctorCheck::pass( + id, + format!("External Wasm Plugin {name:?} verified ({label})"), + ) + .with_detail(format!("sha256: {expected_hex}")) +} diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index c3c9d6d..6dc9f76 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -3,6 +3,7 @@ mod check; mod commit_measurement; mod diff; +mod doctor; mod guard; mod init; mod mcp; @@ -21,10 +22,13 @@ use codeint_git::ResultCache; use codeint_report::ReportError; pub use codeint_config::{ - CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat, - TrendRange, + CalendarDay, DoctorFormat, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, + TrendFormat, TrendRange, +}; +pub use codeint_report::{ + DiffReport, DoctorCheck, DoctorReport, DoctorStatus, DoctorSummary, GuardReport, Report, + TrendReport, }; -pub use codeint_report::{DiffReport, GuardReport, Report, TrendReport}; const DEFAULT_WORST_FINDINGS: usize = 20; const DEFAULT_TREND_COMMITS: usize = 20; @@ -188,6 +192,10 @@ pub fn guard(folder: &Path, target: &Path) -> Result guard::guard(folder, target).map_err(|err| CodeintError::from_cli_error(CliError::Guard(err))) } +pub fn doctor(folder: &Path, plugin_host: &PluginHostConfig) -> DoctorReport { + doctor::doctor(folder, plugin_host) +} + #[derive(Debug, thiserror::Error)] enum CliError { #[error(transparent)] @@ -304,9 +312,24 @@ fn run() -> Result { target, format, } => run_guard(&folder, &target, format), + Command::Doctor { + folder, + format, + plugin_host, + } => run_doctor(&folder, format, &plugin_host), } } +fn run_doctor( + folder: &Path, + format: DoctorFormat, + plugin_host: &PluginHostConfig, +) -> Result { + let report = doctor::doctor(folder, plugin_host); + print_report(&format!("{}\n", report.render(format)?))?; + Ok(Outcome::from_failures(report.blocking_error_messages())) +} + fn run_guard(folder: &Path, target: &Path, format: GuardFormat) -> Result { let report = guard::guard(folder, target)?; print_report(&format!("{}\n", report.render(format)?))?; diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 9747e89..5a5d2ab 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -109,7 +109,7 @@ fn config_remedy(error: &ConfigError) -> &'static str { } } -fn git_remedy(error: &GitError) -> &'static str { +pub(crate) fn git_remedy(error: &GitError) -> &'static str { match error { GitError::NotInRepository { .. } => { "Run codeint inside a Git repository, or pass a folder inside one: codeint check " @@ -158,7 +158,7 @@ fn workspace_remedy(error: &WorkspaceError) -> &'static str { } } -fn configuration_file_remedy(error: &ConfigurationFileError) -> &'static str { +pub(crate) fn configuration_file_remedy(error: &ConfigurationFileError) -> &'static str { plugin_config_remedy(error) .or_else(|| boundary_config_remedy(error)) .or_else(|| file_access_remedy(error)) diff --git a/crates/cli/tests/doctor.rs b/crates/cli/tests/doctor.rs new file mode 100644 index 0000000..c243bdd --- /dev/null +++ b/crates/cli/tests/doctor.rs @@ -0,0 +1,341 @@ +use std::collections::BTreeMap; +use std::fs; +use std::path::Path; +use std::process::{Command, Output}; + +use codeint_plugin_host::{sha256, sha256_hex}; +use serde_json::{Value, json}; +use tempfile::TempDir; + +struct DoctorFixture { + dir: TempDir, + cache: TempDir, +} + +impl DoctorFixture { + fn plain() -> DoctorFixture { + DoctorFixture { + dir: TempDir::new().expect("tempdir"), + cache: TempDir::new().expect("cache dir"), + } + } + + fn git_repo() -> DoctorFixture { + let fixture = DoctorFixture::plain(); + let status = Command::new("git") + .args(["init", "-q", "-b", "main"]) + .current_dir(fixture.root()) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_NOSYSTEM", "1") + .status() + .expect("git init"); + assert!(status.success(), "git init failed"); + fixture + } + + fn git_repo_with_ts() -> DoctorFixture { + let fixture = DoctorFixture::git_repo(); + fixture.write("src/app.ts", "export const ok = 1;\n"); + fixture + } + + fn root(&self) -> &Path { + self.dir.path() + } + + fn write(&self, relative: &str, contents: impl AsRef<[u8]>) { + let target = self.dir.path().join(relative); + let parent = target.parent().expect("relative path has parent"); + fs::create_dir_all(parent).expect("create parent dirs"); + fs::write(&target, contents.as_ref()).expect("write file"); + } + + fn write_config(&self, config: &Value) { + self.write("codeint.json", config.to_string()); + } + + fn write_plugin_config(&self, plugin: Value) { + self.write_config(&json!({ + "$schema": current_schema_url(), + "plugins": [plugin] + })); + } + + fn write_local_plugin(&self, name: &str, path: &str, sha256: &str) { + self.write_plugin_config(json!({ + "name": name, + "path": path, + "sha256": sha256 + })); + } + + fn run(&self, args: &[&str]) -> Output { + let mut command = Command::new(env!("CARGO_BIN_EXE_codeint")); + command.current_dir(self.dir.path()); + command.env("CODEINT_CACHE_DIR", self.cache.path()); + command.arg("doctor").args(args); + command.output().expect("run codeint doctor") + } + + fn run_json(&self, extra_args: &[&str], expected_exit: i32) -> Value { + let mut args = extra_args.to_vec(); + args.extend(["--format", "json"]); + let output = self.run(&args); + assert_eq!( + output.status.code(), + Some(expected_exit), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).unwrap_or_else(|error| { + panic!( + "expected valid JSON stdout, got {error}\nstdout: {}\nstderr: {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ) + }) + } + + fn run_text(&self, expected_exit: i32) -> String { + let output = self.run(&[]); + assert_eq!(output.status.code(), Some(expected_exit)); + String::from_utf8(output.stdout).expect("utf8") + } + + fn snapshot(&self) -> BTreeMap> { + let mut files = BTreeMap::new(); + collect_tree(self.root(), self.root(), &mut files); + files + } +} + +fn collect_tree(root: &Path, current: &Path, files: &mut BTreeMap>) { + let mut entries: Vec<_> = fs::read_dir(current) + .expect("read dir") + .map(|entry| entry.expect("dir entry")) + .collect(); + entries.sort_by_key(|entry| entry.file_name()); + for entry in entries { + let path = entry.path(); + if path.file_name().and_then(|name| name.to_str()) == Some(".git") { + continue; + } + let file_type = entry.file_type().expect("file type"); + if file_type.is_dir() { + collect_tree(root, &path, files); + } else if file_type.is_file() { + let relative = path + .strip_prefix(root) + .expect("relative path") + .to_string_lossy() + .into_owned(); + files.insert(relative, fs::read(&path).expect("read file")); + } + } +} + +fn find_check<'a>(report: &'a Value, id: &str) -> &'a Value { + report["checks"] + .as_array() + .expect("checks array") + .iter() + .find(|check| check["id"] == id) + .unwrap_or_else(|| panic!("expected check {id:?} in report: {report}")) +} + +fn assert_check_field(report: &Value, id: &str, status: &str, field: &str, expected: &str) { + let check = find_check(report, id); + assert_eq!(check["status"], status, "check: {check}"); + let text = check[field].as_str().unwrap_or_default(); + assert!( + text.contains(expected), + "expected {id}.{field} to contain {expected:?}, got {text:?}" + ); +} + +fn assert_non_blocking_summary(report: &Value, expected_status: &str, expect_warnings: bool) { + assert_eq!(report["status"], expected_status); + assert_eq!(report["summary"]["errors"], 0); + let warnings = report["summary"]["warnings"].as_u64().unwrap_or(0); + if expect_warnings { + assert!(warnings >= 1, "expected warnings in {report}"); + } else { + assert_eq!(warnings, 0, "unexpected warnings in {report}"); + } +} + +fn current_schema_url() -> String { + format!( + "https://raw.githubusercontent.com/avidianity/codeint/v{}/schema/codeint.schema.json", + env!("CARGO_PKG_VERSION") + ) +} + +#[test] +fn doctor_reports_healthy_repo_in_text_json_and_toon_and_is_strictly_read_only() { + let fixture = DoctorFixture::git_repo(); + fixture.write_config(&json!({ "$schema": current_schema_url() })); + fixture.write( + "package.json", + r#"{ "name": "root", "private": true, "workspaces": ["packages/*"] }"#, + ); + fixture.write("packages/app/package.json", r#"{ "name": "app" }"#); + fixture.write( + "packages/app/src/index.ts", + "export function greet(name: string): string {\n return name;\n}\n", + ); + + let before = fixture.snapshot(); + + let report = fixture.run_json(&[], 0); + assert_eq!(report["version"], env!("CARGO_PKG_VERSION")); + assert_non_blocking_summary(&report, "pass", false); + assert!(report["summary"]["passed"].as_u64().unwrap_or(0) >= 6); + for id in ["git", "config", "schema", "plugins"] { + assert_eq!(find_check(&report, id)["status"], "pass"); + } + assert_check_field( + &report, + "languages", + "pass", + "summary", + "typescript-javascript", + ); + assert_check_field(&report, "workspace", "pass", "detail", "packages/app"); + + let text = fixture.run_text(0); + assert!(text.contains("Passing checks:"), "text: {text}"); + assert!(text.contains("[PASS] git:"), "text: {text}"); + assert!(!text.contains("Warnings:"), "text: {text}"); + assert!(!text.contains("Blocking errors:"), "text: {text}"); + + let toon_out = fixture.run(&["--format", "toon"]); + assert_eq!(toon_out.status.code(), Some(0)); + let toon_text = String::from_utf8(toon_out.stdout).expect("utf8"); + let decoded: Value = toon_format::decode_default(&toon_text).expect("valid TOON"); + assert_eq!(decoded["status"], "pass"); + assert_eq!(decoded["summary"]["errors"], 0); + + let sub_report = fixture.run_json(&["packages/app"], 0); + assert_eq!(sub_report["status"], "pass"); + + assert_eq!( + before, + fixture.snapshot(), + "codeint doctor must never modify repository files" + ); +} + +#[test] +fn doctor_reports_blocking_error_for_invalid_codeint_json_and_exits_nonzero() { + let fixture = DoctorFixture::git_repo_with_ts(); + fixture.write("codeint.json", "{ \"not_valid\": "); + + let syntax_report = fixture.run_json(&[], 1); + assert_eq!(syntax_report["status"], "error"); + assert!(syntax_report["summary"]["errors"].as_u64().unwrap_or(0) >= 1); + assert_check_field( + &syntax_report, + "config", + "error", + "summary", + "not valid JSON", + ); + + fixture.write("codeint.json", r#"{ "unknown_key": true }"#); + let text = fixture.run_text(1); + assert!(text.contains("Blocking errors:"), "text: {text}"); + assert!(text.contains("[ERROR] config:"), "text: {text}"); + assert!(text.contains("unknown_key"), "text: {text}"); +} + +#[test] +fn doctor_reports_blocking_error_for_future_schema_version_and_exits_nonzero() { + let fixture = DoctorFixture::git_repo_with_ts(); + fixture.write_config(&json!({ + "$schema": "https://raw.githubusercontent.com/avidianity/codeint/v99.0.0/schema/codeint.schema.json" + })); + + let report = fixture.run_json(&[], 1); + assert_eq!(report["status"], "error"); + assert_check_field(&report, "schema", "error", "summary", "v99.0.0"); + assert_check_field(&report, "schema", "error", "remedy", "codeint update"); +} + +#[test] +fn doctor_warns_outside_git_repository_without_blocking_and_remains_read_only() { + let fixture = DoctorFixture::plain(); + fixture.write("src/app.ts", "export const ok = 1;\n"); + let before = fixture.snapshot(); + + let report = fixture.run_json(&[], 0); + assert_non_blocking_summary(&report, "warn", true); + assert_eq!(find_check(&report, "git")["status"], "warn"); + + let text = fixture.run_text(0); + assert!(text.contains("Warnings:"), "text: {text}"); + assert!(text.contains("[WARN] git:"), "text: {text}"); + assert!(!text.contains("Blocking errors:"), "text: {text}"); + + assert_eq!(before, fixture.snapshot(), "non-Git doctor must not write"); + assert!(!fixture.root().join(".git").exists()); +} + +#[test] +fn doctor_verifies_external_wasm_plugins_and_fails_on_missing_or_mismatched_sha256() { + let fixture = DoctorFixture::git_repo_with_ts(); + + fixture.write_plugin_config(json!({ "name": "missing-hash", "path": "plugins/sample.wasm" })); + let missing_hash_report = fixture.run_json(&[], 1); + assert_check_field(&missing_hash_report, "config", "error", "summary", "sha256"); + + let zeros = "0000000000000000000000000000000000000000000000000000000000000000"; + fixture.write_local_plugin("sample-plugin", "plugins/missing.wasm", zeros); + let missing_file_report = fixture.run_json(&[], 1); + assert_eq!( + find_check(&missing_file_report, "plugin:sample-plugin")["status"], + "error" + ); + + let wasm_bytes = b"\0asm\x01\0\0\0"; + fixture.write("plugins/sample.wasm", wasm_bytes); + let actual_hash = sha256_hex(&sha256(wasm_bytes)); + + fixture.write_local_plugin("sample-plugin", "plugins/sample.wasm", zeros); + let mismatch_report = fixture.run_json(&[], 1); + assert_check_field( + &mismatch_report, + "plugin:sample-plugin", + "error", + "detail", + &actual_hash, + ); + + fixture.write_local_plugin("sample-plugin", "plugins/sample.wasm", &actual_hash); + let valid_report = fixture.run_json(&[], 0); + assert_eq!(valid_report["status"], "pass"); + assert_eq!( + find_check(&valid_report, "plugin:sample-plugin")["status"], + "pass" + ); + + fixture.write_plugin_config(json!({ + "name": "remote-plugin", + "kind": "metric", + "url": "https://example.invalid/plugins/remote.wasm", + "sha256": actual_hash + })); + let remote_report = fixture.run_json(&[], 0); + assert_eq!(remote_report["status"], "warn"); + assert_eq!( + find_check(&remote_report, "plugin:remote-plugin")["status"], + "warn" + ); + assert!( + fs::read_dir(fixture.cache.path()) + .expect("read cache dir") + .next() + .is_none(), + "doctor must not write to cache directory" + ); +} diff --git a/crates/config/src/codeint_json.rs b/crates/config/src/codeint_json.rs index 98d2f2d..0bc6e0b 100644 --- a/crates/config/src/codeint_json.rs +++ b/crates/config/src/codeint_json.rs @@ -589,6 +589,37 @@ struct SourceSetGlobs { vendored: Vec, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SchemaVersionStatus { + Missing, + Compatible { + url: String, + version: Option, + }, + NewerThanBinary { + url: String, + config_version: String, + binary_version: String, + }, +} + +#[derive(Debug)] +pub enum ConfigurationInspection { + Missing { + path: PathBuf, + }, + Valid { + path: PathBuf, + schema: SchemaVersionStatus, + configuration: Box, + }, + Invalid { + path: PathBuf, + schema: Option, + error: ConfigurationFileError, + }, +} + pub fn read_configuration(repository_root: &Path) -> Result { match std::fs::read_to_string(repository_root.join(CONFIGURATION_FILE_NAME)) { Ok(text) => parse(&text), @@ -597,6 +628,46 @@ pub fn read_configuration(repository_root: &Path) -> Result ConfigurationInspection { + let path = repository_root.join(CONFIGURATION_FILE_NAME); + let text = match std::fs::read_to_string(&path) { + Ok(text) => text, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return ConfigurationInspection::Missing { path }; + } + Err(error) => { + return ConfigurationInspection::Invalid { + path, + schema: None, + error: ConfigurationFileError::Unreadable(error), + }; + } + }; + let value: Value = match serde_json::from_str(&text) { + Ok(value) => value, + Err(error) => { + return ConfigurationInspection::Invalid { + path, + schema: None, + error: ConfigurationFileError::NotJson(error), + }; + } + }; + let schema = inspect_schema_version(&value, env!("CARGO_PKG_VERSION")); + match parse_value_without_schema_version(value) { + Ok(configuration) => ConfigurationInspection::Valid { + path, + schema, + configuration: Box::new(configuration), + }, + Err(error) => ConfigurationInspection::Invalid { + path, + schema: Some(schema), + error, + }, + } +} + pub fn configuration_schema() -> String { let schema = schemars::schema_for!(ConfigurationFile); format!("{:#}\n", schema.as_value()) @@ -605,6 +676,12 @@ pub fn configuration_schema() -> String { fn parse(text: &str) -> Result { let value: Value = serde_json::from_str(text).map_err(ConfigurationFileError::NotJson)?; check_schema_version(&value, env!("CARGO_PKG_VERSION"))?; + parse_value_without_schema_version(value) +} + +fn parse_value_without_schema_version( + value: Value, +) -> Result { let schema = schemars::schema_for!(ConfigurationFile); shape::check_shape(&value, schema.as_value())?; let file: ConfigurationFile = @@ -855,21 +932,46 @@ fn source_set_overrides( const OFFICIAL_SCHEMA_PREFIX: &str = "https://raw.githubusercontent.com/avidianity/codeint/v"; const OFFICIAL_SCHEMA_SUFFIX: &str = "/schema/codeint.schema.json"; -fn check_schema_version(value: &Value, binary_version: &str) -> Result<(), ConfigurationFileError> { +fn inspect_schema_version(value: &Value, binary_version: &str) -> SchemaVersionStatus { let Some(schema_url) = value.get("$schema").and_then(Value::as_str) else { - return Ok(()); + return SchemaVersionStatus::Missing; }; let Some(config_version) = extract_official_schema_version(schema_url) else { - return Ok(()); + return SchemaVersionStatus::Compatible { + url: schema_url.to_owned(), + version: None, + }; }; let (Some(cfg), Some(bin)) = (parse_semver(config_version), parse_semver(binary_version)) else { - return Ok(()); + return SchemaVersionStatus::Compatible { + url: schema_url.to_owned(), + version: Some(config_version.to_owned()), + }; }; if cfg > bin { - return Err(ConfigurationFileError::NewerSchemaVersion { + return SchemaVersionStatus::NewerThanBinary { + url: schema_url.to_owned(), config_version: config_version.to_owned(), binary_version: binary_version.to_owned(), + }; + } + SchemaVersionStatus::Compatible { + url: schema_url.to_owned(), + version: Some(config_version.to_owned()), + } +} + +fn check_schema_version(value: &Value, binary_version: &str) -> Result<(), ConfigurationFileError> { + if let SchemaVersionStatus::NewerThanBinary { + config_version, + binary_version, + .. + } = inspect_schema_version(value, binary_version) + { + return Err(ConfigurationFileError::NewerSchemaVersion { + config_version, + binary_version, }); } Ok(()) diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 642a0b3..e0cd750 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -16,9 +16,10 @@ pub use boundaries::{ }; pub use calendar_day::{CalendarDay, CalendarDayError}; pub use codeint_json::{ - Budget, Budgets, Configuration, DetectedLanguage, LanguageCoverage, Languages, - PluginDeclaration, PluginKind, PluginLimits, PluginSource, Sha256Digest, SourceSetOverrides, - StarterConfigurationError, configuration_schema, published_schema_address, read_configuration, + Budget, Budgets, Configuration, ConfigurationInspection, DetectedLanguage, LanguageCoverage, + Languages, PluginDeclaration, PluginKind, PluginLimits, PluginSource, SchemaVersionStatus, + Sha256Digest, SourceSetOverrides, StarterConfigurationError, configuration_schema, + inspect_configuration, published_schema_address, read_configuration, write_starter_configuration, }; pub use config_error::{ConfigurationFileError, JsonType, KeyPath, KeySegment}; @@ -105,6 +106,13 @@ pub enum GuardFormat { Json, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] +pub enum DoctorFormat { + Text, + Json, + Toon, +} + const LATEST_COMMITS_OF_A_TREND: usize = 20; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -158,6 +166,11 @@ pub enum Command { target: PathBuf, format: GuardFormat, }, + Doctor { + folder: PathBuf, + format: DoctorFormat, + plugin_host: PluginHostConfig, + }, } #[derive(Debug)] @@ -268,6 +281,20 @@ enum CommandArguments { )] format: GuardFormat, }, + #[command( + about = "Run read-only diagnostics on codeint.json, Git repository status, detected languages, Workspace packages, and external Wasm Plugins" + )] + Doctor { + #[arg(help = "A folder to inspect; the current folder by default")] + path: Option, + #[arg( + long, + value_enum, + default_value_t = DoctorFormat::Text, + help = "The format of the output" + )] + format: DoctorFormat, + }, } #[derive(Debug, clap::Args)] @@ -328,6 +355,11 @@ fn build_command( target: path, format, }), + CommandArguments::Doctor { path, format } => Ok(Command::Doctor { + folder: existing_folder(current_folder, path)?, + format, + plugin_host: plugin_host_config_of_this_process(current_folder), + }), } } diff --git a/crates/report/src/doctor.rs b/crates/report/src/doctor.rs new file mode 100644 index 0000000..b5081d4 --- /dev/null +++ b/crates/report/src/doctor.rs @@ -0,0 +1,182 @@ +use std::fmt::Write as _; + +use codeint_config::DoctorFormat; +use serde::Serialize; + +use crate::{ReportError, render_structured}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum DoctorStatus { + Pass, + Warn, + Error, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct DoctorCheck { + pub id: String, + pub status: DoctorStatus, + pub summary: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub detail: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub remedy: Option, +} + +impl DoctorCheck { + pub fn pass(id: impl Into, summary: impl Into) -> DoctorCheck { + DoctorCheck { + id: id.into(), + status: DoctorStatus::Pass, + summary: summary.into(), + detail: None, + remedy: None, + } + } + + pub fn warn(id: impl Into, summary: impl Into) -> DoctorCheck { + DoctorCheck { + id: id.into(), + status: DoctorStatus::Warn, + summary: summary.into(), + detail: None, + remedy: None, + } + } + + pub fn error(id: impl Into, summary: impl Into) -> DoctorCheck { + DoctorCheck { + id: id.into(), + status: DoctorStatus::Error, + summary: summary.into(), + detail: None, + remedy: None, + } + } + + pub fn with_detail(mut self, detail: impl Into) -> DoctorCheck { + self.detail = Some(detail.into()); + self + } + + pub fn with_remedy(mut self, remedy: impl Into) -> DoctorCheck { + self.remedy = Some(remedy.into()); + self + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct DoctorSummary { + pub passed: usize, + pub warnings: usize, + pub errors: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct DoctorReport { + pub version: String, + pub path: String, + pub status: DoctorStatus, + pub summary: DoctorSummary, + pub checks: Vec, +} + +impl DoctorReport { + pub fn new( + version: impl Into, + path: impl Into, + checks: Vec, + ) -> DoctorReport { + let passed = checks + .iter() + .filter(|check| check.status == DoctorStatus::Pass) + .count(); + let warnings = checks + .iter() + .filter(|check| check.status == DoctorStatus::Warn) + .count(); + let errors = checks + .iter() + .filter(|check| check.status == DoctorStatus::Error) + .count(); + let status = if errors > 0 { + DoctorStatus::Error + } else if warnings > 0 { + DoctorStatus::Warn + } else { + DoctorStatus::Pass + }; + DoctorReport { + version: version.into(), + path: path.into(), + status, + summary: DoctorSummary { + passed, + warnings, + errors, + }, + checks, + } + } + + pub fn has_blocking_errors(&self) -> bool { + self.summary.errors > 0 + } + + pub fn blocking_error_messages(&self) -> Vec { + self.checks + .iter() + .filter(|check| check.status == DoctorStatus::Error) + .map(|check| format!("{}: {}", check.id, check.summary)) + .collect() + } + + pub fn render(&self, format: DoctorFormat) -> Result { + render_structured(self, format, DoctorReport::render_text) + } + + fn render_text(&self) -> String { + let mut out = String::new(); + let _ = writeln!(out, "codeint doctor {} ({})", self.version, self.path); + let _ = writeln!( + out, + "summary: {} passed, {} {}, {} blocking {}", + self.summary.passed, + self.summary.warnings, + plural(self.summary.warnings, "warning", "warnings"), + self.summary.errors, + plural(self.summary.errors, "error", "errors"), + ); + self.write_section(&mut out, "Passing checks:", DoctorStatus::Pass, "PASS"); + self.write_section(&mut out, "Warnings:", DoctorStatus::Warn, "WARN"); + self.write_section(&mut out, "Blocking errors:", DoctorStatus::Error, "ERROR"); + out.trim_end_matches('\n').to_owned() + } + + fn write_section(&self, out: &mut String, heading: &str, status: DoctorStatus, badge: &str) { + let items: Vec<&DoctorCheck> = self + .checks + .iter() + .filter(|check| check.status == status) + .collect(); + if items.is_empty() { + return; + } + let _ = writeln!(out); + let _ = writeln!(out, "{heading}"); + for check in items { + let _ = writeln!(out, " [{badge}] {}: {}", check.id, check.summary); + if let Some(detail) = &check.detail { + let _ = writeln!(out, " detail: {detail}"); + } + if let Some(remedy) = &check.remedy { + let _ = writeln!(out, " remedy: {remedy}"); + } + } + } +} + +fn plural<'a>(count: usize, singular: &'a str, plural_word: &'a str) -> &'a str { + if count == 1 { singular } else { plural_word } +} diff --git a/crates/report/src/guard.rs b/crates/report/src/guard.rs index f3a9e47..1cab87a 100644 --- a/crates/report/src/guard.rs +++ b/crates/report/src/guard.rs @@ -6,7 +6,7 @@ use codeint_config::{ use codeint_model::RepoPath; use serde::Serialize; -use crate::ReportError; +use crate::{ReportError, render_structured}; #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct GuardReport { @@ -161,11 +161,7 @@ impl GuardReport { } pub fn render(&self, format: GuardFormat) -> Result { - match format { - GuardFormat::Text => Ok(self.render_text()), - GuardFormat::Toon => toon_format::encode_default(self).map_err(ReportError::Toon), - GuardFormat::Json => serde_json::to_string_pretty(self).map_err(ReportError::Json), - } + render_structured(self, format, GuardReport::render_text) } fn render_text(&self) -> String { diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index ec6083c..021d3cc 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -3,8 +3,8 @@ use std::collections::BTreeMap; use codeint_config::{ - Boundaries as BoundariesConfig, BoundaryDirective, BoundaryRuleDecision, Budgets, - FindingsShown, ReportFormat, + Boundaries as BoundariesConfig, BoundaryDirective, BoundaryRuleDecision, Budgets, DoctorFormat, + FindingsShown, GuardFormat, ReportFormat, }; use codeint_metrics::{ Boundaries, BoundaryEdgeCheck, BoundaryFinding, BoundaryPolicy, CloneGroup, Duplication, @@ -19,6 +19,7 @@ use serde::ser::SerializeMap; use serde::{Deserialize, Serialize, Serializer}; mod diff; +mod doctor; mod guard; mod markdown; mod measurement; @@ -28,6 +29,7 @@ mod tests; mod trend; pub use diff::{BaseCommit, DiffReport, Head, HeadCommit}; +pub use doctor::{DoctorCheck, DoctorReport, DoctorStatus, DoctorSummary}; pub use guard::{GuardAllowedTarget, GuardDeniedTarget, GuardReport}; pub use measurement::CommitMeasurement; pub use trend::{TrendPoint, TrendReport}; @@ -47,6 +49,44 @@ pub enum ReportError { Sarif(#[source] serde_json::Error), } +pub(crate) enum StructuredFormat { + Text, + Json, + Toon, +} + +impl From for StructuredFormat { + fn from(format: DoctorFormat) -> StructuredFormat { + match format { + DoctorFormat::Text => StructuredFormat::Text, + DoctorFormat::Json => StructuredFormat::Json, + DoctorFormat::Toon => StructuredFormat::Toon, + } + } +} + +impl From for StructuredFormat { + fn from(format: GuardFormat) -> StructuredFormat { + match format { + GuardFormat::Text => StructuredFormat::Text, + GuardFormat::Json => StructuredFormat::Json, + GuardFormat::Toon => StructuredFormat::Toon, + } + } +} + +pub(crate) fn render_structured( + value: &T, + format: impl Into, + render_text: impl FnOnce(&T) -> String, +) -> Result { + match format.into() { + StructuredFormat::Text => Ok(render_text(value)), + StructuredFormat::Json => serde_json::to_string_pretty(value).map_err(ReportError::Json), + StructuredFormat::Toon => toon_format::encode_default(value).map_err(ReportError::Toon), + } +} + #[derive(Debug, Serialize)] pub struct Report { #[serde(flatten)] diff --git a/docs/reference.md b/docs/reference.md index 92e93a0..b32ca91 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -30,6 +30,7 @@ The working tree adds `src/route.ts`, an eroded function that is not committed. | `update` | Update a standalone codeint binary in place from GitHub Releases; see [`codeint update`](#codeint-update) | | `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, `trend`, and `guard` tools; see [`codeint mcp`](#codeint-mcp) | | `guard` | Show the architectural boundary zone, allowed and denied target zones, `public_files` constraints, and allowed importers for a file path; see [`codeint guard`](#codeint-guard) | +| `doctor` | Run read-only diagnostics on `codeint.json`, Git repository status, detected languages, Workspace packages, and external Wasm Plugins; see [`codeint doctor`](#codeint-doctor) | | `help` | Print the help of codeint, or of the command that follows it | | Option | Meaning | @@ -514,12 +515,34 @@ codeint guard src/route.ts --format toon codeint guard src/route.ts --format json ``` +### `codeint doctor` + +| Argument | Meaning | +| -------- | ------- | +| `[PATH]` | A folder to inspect; the current folder by default | + +| Option | Meaning | +| ------ | ------- | +| `--format ` | The format of the output: `text`, the default, `json`, or `toon` | +| `-h, --help` | Print the help of `codeint doctor` | + +`codeint doctor` runs strictly read-only, offline diagnostics on Git repository status, `codeint.json` validity, `$schema` version compatibility, detected Language plugins, Workspace packages, and external Wasm Plugin paths and SHA-256 digests. +It separates passing checks, warnings, and blocking errors, exiting with code 0 when no blocking error is found and code 1 when at least one blocking error is found. + +```sh exit=0 +codeint doctor +codeint doctor src +codeint doctor --format text +codeint doctor --format json +codeint doctor --format toon +``` + ## Exit codes | Exit code | Meaning | | --------- | ------- | -| `0` | The run succeeded, and no Budget or Regression failed | -| `1` | The run succeeded, and at least one Budget or Regression failed; codeint still writes the whole report and names each failure on standard error | +| `0` | The run succeeded, and no Budget, Regression, or blocking doctor error failed | +| `1` | The run succeeded, and at least one Budget, Regression, or blocking doctor error failed; codeint still writes the whole report and names each failure on standard error | | `2` | An operational error stopped the run, such as an unknown option, a Git ref that names no commit, or an invalid `codeint.json`; codeint names the error on standard error | ## `codeint.json` From 0bb6b547c540eb5a24c20e4a4caa36d22f81e28a Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 09:48:37 +0800 Subject: [PATCH 4/6] feat(cli): add codeint report command for single-pass re-rendering Add codeint report --format (supporting file paths and stdin via -) to re-render saved check and diff JSON reports losslessly without re-running analysis, failing with exit code 2 on malformed JSON or unsupported schema versions. Closes #185 --- crates/cli/src/lib.rs | 24 +- crates/cli/src/remedy.rs | 29 ++ crates/cli/src/report.rs | 48 ++++ crates/cli/tests/reference/fixture.rs | 10 + crates/cli/tests/report.rs | 365 ++++++++++++++++++++++++++ crates/config/src/lib.rs | 77 ++++++ crates/report/HOW-TO.md | 14 + crates/report/src/diff.rs | 136 +++++----- crates/report/src/lib.rs | 224 +++++++++++----- crates/report/src/markdown.rs | 16 +- crates/report/src/saved.rs | 112 ++++++++ crates/report/src/saved/tests.rs | 26 ++ docs/reference.md | 31 +++ 13 files changed, 960 insertions(+), 152 deletions(-) create mode 100644 crates/cli/src/report.rs create mode 100644 crates/cli/tests/report.rs create mode 100644 crates/report/src/saved.rs create mode 100644 crates/report/src/saved/tests.rs diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index c3c9d6d..05c5205 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -7,6 +7,7 @@ mod guard; mod init; mod mcp; mod remedy; +mod report; mod trend; mod update; @@ -16,7 +17,9 @@ use std::io::Write; use std::path::{Path, PathBuf}; use std::process::ExitCode; -use codeint_config::{Command, ConfigError, ReportDestination, read_invocation}; +use codeint_config::{ + Command, ConfigError, ReportDestination, ReportInput, ReportRenderFormat, read_invocation, +}; use codeint_git::ResultCache; use codeint_report::ReportError; @@ -24,7 +27,7 @@ pub use codeint_config::{ CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat, TrendRange, }; -pub use codeint_report::{DiffReport, GuardReport, Report, TrendReport}; +pub use codeint_report::{DiffReport, GuardReport, Report, SavedReport, TrendReport}; const DEFAULT_WORST_FINDINGS: usize = 20; const DEFAULT_TREND_COMMITS: usize = 20; @@ -202,6 +205,8 @@ enum CliError { Update(#[from] update::UpdateError), #[error(transparent)] Report(#[from] ReportError), + #[error(transparent)] + Rerender(#[from] report::RerenderError), #[error("cannot write the report to standard output")] Output(#[source] std::io::Error), #[error("cannot write the report to {}", path.display())] @@ -304,9 +309,24 @@ fn run() -> Result { target, format, } => run_guard(&folder, &target, format), + Command::Report { + input, + destination, + format, + } => run_report(&input, &destination, format), } } +fn run_report( + input: &ReportInput, + destination: &ReportDestination, + format: ReportRenderFormat, +) -> Result { + let rendered = report::rerender(input, format)?; + write_report(&rendered, destination)?; + Ok(Outcome::Passed) +} + fn run_guard(folder: &Path, target: &Path, format: GuardFormat) -> Result { let report = guard::guard(folder, target)?; print_report(&format!("{}\n", report.render(format)?))?; diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 9747e89..d558cdf 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -3,10 +3,13 @@ use codeint_git::GitError; use codeint_model::{MetricPluginError, WorkspaceError}; use codeint_plugin_host::PluginHostError; +use codeint_report::SavedReportError; + use crate::CliError; use crate::check::CheckError; use crate::guard::GuardError; use crate::init::InitError; +use crate::report::RerenderError; use crate::update::UpdateError; pub(crate) fn remedy(error: &CliError) -> &'static str { @@ -19,6 +22,7 @@ pub(crate) fn remedy(error: &CliError) -> &'static str { CliError::Report(_) => { "This is a defect in codeint; report it at https://github.com/avidianity/codeint/issues." } + CliError::Rerender(error) => rerender_remedy(error), CliError::Output(_) => "Keep standard output open until codeint exits.", CliError::OutputFile { .. } => { "Pass --output a file path that you have permission to write, not a folder." @@ -313,6 +317,31 @@ fn metric_plugin_remedy(error: &MetricPluginError) -> &'static str { } } +fn rerender_remedy(error: &RerenderError) -> &'static str { + match error { + RerenderError::ReadStdin(_) => { + "Pipe a valid UTF-8 JSON report into standard input when passing -." + } + RerenderError::ReadFile { .. } => { + "Pass a readable path to a saved check or diff JSON report, or pass - for standard input." + } + RerenderError::Parse(parse_error) => match parse_error { + SavedReportError::InvalidJson(_) | SavedReportError::NotAnObject => { + "Pass a JSON report generated by codeint check --format json or codeint diff --format json." + } + SavedReportError::UnsupportedSchemaVersion { .. } => { + "Generate the JSON report with a compatible codeint version, or upgrade codeint." + } + SavedReportError::UnrecognizedReport | SavedReportError::InvalidPayload { .. } => { + "Pass a JSON report generated by codeint check --format json or codeint diff --format json." + } + }, + RerenderError::Render(_) => { + "This is a defect in codeint; report it at https://github.com/avidianity/codeint/issues." + } + } +} + fn starter_configuration_remedy(error: &StarterConfigurationError) -> &'static str { match error { StarterConfigurationError::AlreadyExists { .. } => { diff --git a/crates/cli/src/report.rs b/crates/cli/src/report.rs new file mode 100644 index 0000000..36ac5a5 --- /dev/null +++ b/crates/cli/src/report.rs @@ -0,0 +1,48 @@ +use std::io::Read; +use std::path::PathBuf; + +use codeint_config::{ReportInput, ReportRenderFormat}; +use codeint_report::{ReportError, SavedReport, SavedReportError}; + +#[derive(Debug, thiserror::Error)] +pub(crate) enum RerenderError { + #[error("cannot read standard input")] + ReadStdin(#[source] std::io::Error), + #[error("cannot read {}", path.display())] + ReadFile { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error(transparent)] + Parse(#[from] SavedReportError), + #[error(transparent)] + Render(#[from] ReportError), +} + +pub(crate) fn rerender( + input: &ReportInput, + format: ReportRenderFormat, +) -> Result { + let text = read_input(input)?; + let report = SavedReport::from_json(&text)?; + Ok(report.render(format)?) +} + +fn read_input(input: &ReportInput) -> Result { + match input { + ReportInput::StandardInput => { + let mut buffer = String::new(); + std::io::stdin() + .read_to_string(&mut buffer) + .map_err(RerenderError::ReadStdin)?; + Ok(buffer) + } + ReportInput::File(path) => { + std::fs::read_to_string(path).map_err(|source| RerenderError::ReadFile { + path: path.clone(), + source, + }) + } + } +} diff --git a/crates/cli/tests/reference/fixture.rs b/crates/cli/tests/reference/fixture.rs index 3436b27..2b76db7 100644 --- a/crates/cli/tests/reference/fixture.rs +++ b/crates/cli/tests/reference/fixture.rs @@ -93,6 +93,16 @@ impl Template { "src/route.ts", &branching_function("route", "path: string", "path === \"/", 15), ); + let saved = Command::new(env!("CARGO_BIN_EXE_codeint")) + .args(["check", "--format", "json", "--output", "report.json"]) + .current_dir(root) + .output() + .expect("generate sample report.json"); + assert!( + saved.status.success(), + "generate sample report.json failed: {}", + String::from_utf8_lossy(&saved.stderr) + ); template } diff --git a/crates/cli/tests/report.rs b/crates/cli/tests/report.rs new file mode 100644 index 0000000..b293943 --- /dev/null +++ b/crates/cli/tests/report.rs @@ -0,0 +1,365 @@ +use std::fs; +use std::io::Write; +use std::path::Path; +use std::process::{Command, Output, Stdio}; + +use tempfile::TempDir; + +const GIT_ENV: [(&str, &str); 6] = [ + ("GIT_CONFIG_GLOBAL", "/dev/null"), + ("GIT_CONFIG_NOSYSTEM", "1"), + ("GIT_AUTHOR_NAME", "Report Tester"), + ("GIT_AUTHOR_EMAIL", "report@example.invalid"), + ("GIT_COMMITTER_NAME", "Report Tester"), + ("GIT_COMMITTER_EMAIL", "report@example.invalid"), +]; + +fn setup_workspace(files: &[(&str, &str)]) -> (TempDir, TempDir) { + let dir = TempDir::new().expect("temp workspace"); + let cache = TempDir::new().expect("temp cache"); + git_in(dir.path(), &["init", "--quiet", "--initial-branch", "main"]); + populate(dir.path(), files); + (dir, cache) +} + +fn populate(root: &Path, files: &[(&str, &str)]) { + for &(rel, body) in files { + let target = root.join(rel); + fs::create_dir_all(target.parent().expect("parent")).expect("mkdir"); + fs::write(target, body).expect("write"); + } +} + +fn git_in(root: &Path, args: &[&str]) { + let status = Command::new("git") + .args(args) + .current_dir(root) + .envs(GIT_ENV) + .status() + .expect("git"); + assert!(status.success(), "git {args:?} failed"); +} + +fn commit_all(root: &Path, message: &str) { + git_in(root, &["add", "--all"]); + git_in(root, &["commit", "--quiet", "--message", message]); +} + +fn invoke(root: &Path, cache: &Path, args: &[&str], stdin_data: Option<&[u8]>) -> Output { + let mut proc = Command::new(env!("CARGO_BIN_EXE_codeint")); + proc.args(args) + .current_dir(root) + .env("CODEINT_CACHE_DIR", cache) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + if stdin_data.is_some() { + proc.stdin(Stdio::piped()); + } + let mut child = proc.spawn().expect("spawn codeint"); + if let Some(payload) = stdin_data { + child + .stdin + .take() + .expect("stdin handle") + .write_all(payload) + .expect("write stdin"); + } + child.wait_with_output().expect("collect output") +} + +fn eroded_ts(name: &str, branches: usize) -> String { + let arms: String = (1..=branches) + .map(|i| format!(" if (x === {i}) return {i};\n")) + .collect(); + format!("export function {name}(x: number): number {{\n{arms} return 0;\n}}\n") +} + +fn verbose_ts(name: &str) -> String { + format!( + "export function {name}(v: number): string {{\n if (v < 0) {{\n return \"neg\";\n }} else {{\n return \"pos\";\n }}\n}}\n" + ) +} + +fn clone_block_ts(name: &str) -> String { + format!( + "export function {name}(items: number[]): number {{\n let total = 0;\n for (const item of items) {{\n const scaled = item * 2 + 1;\n if (scaled > 10) {{\n total += scaled - 3;\n }} else {{\n total += scaled + 5;\n }}\n }}\n const adjusted = total * 3 - 7;\n return adjusted > 0 ? adjusted : 0;\n}}\n" + ) +} + +fn utf8(bytes: &[u8]) -> String { + String::from_utf8(bytes.to_vec()).expect("valid UTF-8") +} + +fn verify_parity( + root: &Path, + cache: &Path, + base_args: &[&str], + saved_json: &[u8], + file_name: &str, +) { + fs::write(root.join(file_name), saved_json).expect("save json"); + + for format in ["sarif", "markdown", "toon", "json"] { + let mut direct_args = base_args.to_vec(); + direct_args.extend(["--format", format]); + let direct = invoke(root, cache, &direct_args, None); + assert!( + matches!(direct.status.code(), Some(0 | 1)), + "direct {direct_args:?} failed: {}", + utf8(&direct.stderr) + ); + let expected = utf8(&direct.stdout); + + for input in ["-", file_name] { + let stdin = (input == "-").then_some(saved_json); + let rerendered = invoke(root, cache, &["report", input, "--format", format], stdin); + assert_eq!( + rerendered.status.code(), + Some(0), + "report {input} --format {format} failed: {}", + utf8(&rerendered.stderr) + ); + assert_eq!( + utf8(&rerendered.stdout), + expected, + "{input} parity mismatch for --format {format}" + ); + } + } + + let direct_default = invoke(root, cache, base_args, None); + let from_text = invoke( + root, + cache, + &["report", "-", "--format", "text"], + Some(saved_json), + ); + assert_eq!(from_text.status.code(), Some(0)); + assert_eq!(utf8(&from_text.stdout), utf8(&direct_default.stdout)); +} + +fn capture_and_verify_parity( + root: &Path, + cache: &Path, + base_args: &[&str], + expected_code: i32, + file_name: &str, +) { + let mut json_args = base_args.to_vec(); + json_args.extend(["--format", "json"]); + let json_run = invoke(root, cache, &json_args, None); + assert_eq!(json_run.status.code(), Some(expected_code)); + verify_parity(root, cache, base_args, &json_run.stdout, file_name); +} + +#[test] +fn rerenders_check_json_from_stdin_and_file_with_full_format_parity() { + let eroded = eroded_ts("dispatch", 12); + let verbose = verbose_ts("label"); + let dup_a = clone_block_ts("calcA"); + let dup_b = clone_block_ts("calcB"); + let (dir, cache) = setup_workspace(&[ + ("src/eroded.ts", &eroded), + ("src/verbose.ts", &verbose), + ("src/dup_a.ts", &dup_a), + ("src/dup_b.ts", &dup_b), + ( + "src/cycle_a.ts", + "import { b } from \"./cycle_b\";\nexport const a = (): number => b() + 1;\n", + ), + ( + "src/cycle_b.ts", + "import { a } from \"./cycle_a\";\nexport const b = (): number => a() + 1;\n", + ), + ("src/broken.ts", "export const broken = ;\n"), + ("src/types.d.ts", "export type Label = string;\n"), + ( + "codeint.json", + "{\"budgets\":{\"production\":{\"erosion\":0.1}}}\n", + ), + ]); + + capture_and_verify_parity(dir.path(), cache.path(), &["check"], 1, "check-report.json"); + + let to_file = invoke( + dir.path(), + cache.path(), + &[ + "report", + "check-report.json", + "--format", + "markdown", + "--output", + "rendered.md", + ], + None, + ); + assert_eq!(to_file.status.code(), Some(0)); + assert!(to_file.stdout.is_empty()); + let direct_md = invoke( + dir.path(), + cache.path(), + &["check", "--format", "markdown"], + None, + ); + assert_eq!( + fs::read_to_string(dir.path().join("rendered.md")).expect("read rendered.md"), + utf8(&direct_md.stdout) + ); +} + +#[test] +fn rerenders_diff_json_from_stdin_and_file_with_full_format_parity() { + let old = eroded_ts("legacy", 11); + let sign = verbose_ts("sign"); + let (dir, cache) = setup_workspace(&[("src/old.ts", &old), ("src/verbose.ts", &sign)]); + commit_all(dir.path(), "base"); + + git_in(dir.path(), &["checkout", "--quiet", "-b", "feature"]); + let added = eroded_ts("route", 14); + populate( + dir.path(), + &[ + ( + "src/old.ts", + "export function legacy(x: number): number {\n return x;\n}\n", + ), + ("src/added.ts", &added), + ], + ); + commit_all(dir.path(), "feature"); + + capture_and_verify_parity( + dir.path(), + cache.path(), + &["diff", "main", "--head", "feature"], + 1, + "diff-commit.json", + ); + + let extra = verbose_ts("extra"); + populate(dir.path(), &[("src/extra.ts", &extra)]); + capture_and_verify_parity( + dir.path(), + cache.path(), + &["diff", "main"], + 1, + "diff-wt.json", + ); +} + +#[test] +fn rejects_malformed_json_unsupported_schema_and_missing_input_with_exit_code_2() { + struct ErrorCase<'a> { + args: &'a [&'a str], + stdin: Option<&'a [u8]>, + expected: &'a str, + } + + let (dir, cache) = setup_workspace(&[]); + + let cases = [ + ErrorCase { + args: &["report", "-", "--format", "sarif"], + stdin: Some(b"{not json"), + expected: "JSON", + }, + ErrorCase { + args: &["report", "-", "--format", "markdown"], + stdin: Some(b"[1, 2, 3]"), + expected: "JSON object", + }, + ErrorCase { + args: &["report", "-", "--format", "sarif"], + stdin: Some( + br#"{"schema_version": 2, "files": 0, "source_lines": 0, "source_sets": {}}"#, + ), + expected: "unsupported report schema version", + }, + ErrorCase { + args: &["report", "-", "--format", "markdown"], + stdin: Some( + br#"{"$schema": "https://example.invalid/sarif.json", "version": "2.1.0", "runs": []}"#, + ), + expected: "unsupported report schema version", + }, + ErrorCase { + args: &["report", "-", "--format", "toon"], + stdin: Some(br#"{"commits": 1, "source_sets": {}}"#), + expected: "check or diff", + }, + ErrorCase { + args: &["report", "missing.json", "--format", "sarif"], + stdin: None, + expected: "missing.json", + }, + ]; + + for case in cases { + let out = invoke(dir.path(), cache.path(), case.args, case.stdin); + assert_eq!( + out.status.code(), + Some(2), + "expected exit 2 for {:?}", + case.args + ); + let err = utf8(&out.stderr); + assert!( + err.contains(case.expected), + "expected {:?} in stderr for {:?}, got: {err}", + case.expected, + case.args + ); + } +} + +#[test] +fn rerenders_multilanguage_boundaries_and_unresolved_imports_losslessly() { + let (dir, cache) = setup_workspace(&[ + ( + "codeint.json", + r#"{ + "boundaries": { + "zones": { + "domain": { "patterns": ["src/domain/**"] }, + "infra": { "patterns": ["src/infra/**"] } + }, + "rules": [ + { "from": "domain", "deny": ["infra"], "reason": "domain stays pure" } + ] + } +} +"#, + ), + ( + "src/infra/db.ts", + "export function query(): number {\n return 1;\n}\n", + ), + ( + "src/domain/service.ts", + "import { query } from \"../infra/db\";\nimport { missing } from \"./does-not-exist\";\nexport function run(): number {\n return query() + Number(missing);\n}\n", + ), + ( + "src/helper.rs", + "pub fn double(n: i32) -> i32 {\n n * 2\n}\n", + ), + ]); + commit_all(dir.path(), "base"); + + capture_and_verify_parity(dir.path(), cache.path(), &["check"], 0, "multi-check.json"); + + populate( + dir.path(), + &[( + "src/domain/extra.ts", + "import { query } from \"../infra/db\";\nexport const extra = (): number => query();\n", + )], + ); + capture_and_verify_parity( + dir.path(), + cache.path(), + &["diff", "main"], + 1, + "multi-diff.json", + ); +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 642a0b3..c900cfb 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -75,6 +75,12 @@ pub enum ReportDestination { File(PathBuf), } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ReportInput { + StandardInput, + File(PathBuf), +} + const WORST_FINDINGS_PER_METRIC: usize = 20; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -91,6 +97,26 @@ pub enum ReportFormat { Markdown, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] +pub enum ReportRenderFormat { + Toon, + Json, + Sarif, + Markdown, + Text, +} + +impl ReportRenderFormat { + pub fn as_report_format(self) -> ReportFormat { + match self { + ReportRenderFormat::Toon | ReportRenderFormat::Text => ReportFormat::Toon, + ReportRenderFormat::Json => ReportFormat::Json, + ReportRenderFormat::Sarif => ReportFormat::Sarif, + ReportRenderFormat::Markdown => ReportFormat::Markdown, + } + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] pub enum TrendFormat { Toon, @@ -158,6 +184,11 @@ pub enum Command { target: PathBuf, format: GuardFormat, }, + Report { + input: ReportInput, + destination: ReportDestination, + format: ReportRenderFormat, + }, } #[derive(Debug)] @@ -268,6 +299,29 @@ enum CommandArguments { )] format: GuardFormat, }, + #[command( + about = "Re-render a saved check or diff JSON report into another format without re-running analysis" + )] + Report { + #[arg( + value_name = "INPUT", + help = "Path to a saved check or diff JSON report, or - to read from standard input" + )] + input: PathBuf, + #[arg( + long, + value_name = "FILE", + help = "Write the report to this file instead of standard output" + )] + output: Option, + #[arg( + long, + value_enum, + default_value_t = ReportRenderFormat::Toon, + help = "The format of the report" + )] + format: ReportRenderFormat, + }, } #[derive(Debug, clap::Args)] @@ -328,9 +382,32 @@ fn build_command( target: path, format, }), + CommandArguments::Report { + input, + output, + format, + } => build_report_command(current_folder, input, output, format), } } +fn build_report_command( + current_folder: &Path, + input: PathBuf, + output: Option, + format: ReportRenderFormat, +) -> Result { + let source = if input.as_os_str() == "-" { + ReportInput::StandardInput + } else { + ReportInput::File(input) + }; + Ok(Command::Report { + input: source, + destination: report_destination(current_folder, output)?, + format, + }) +} + fn build_trend_command( current_folder: &Path, since: Option, diff --git a/crates/report/HOW-TO.md b/crates/report/HOW-TO.md index b580195..f85432d 100644 --- a/crates/report/HOW-TO.md +++ b/crates/report/HOW-TO.md @@ -89,3 +89,17 @@ let text = trend.render(TrendFormat::Toon)?; - Pass `TrendPoint` values oldest first. - `TrendReport::of` records the four Metric ratios per Source set across commits and omits Source sets that have zero files in every commit. - `render` formats the trend as `Toon`, `Json`, or `Markdown`. + +## Re-render a saved JSON report with `SavedReport` + +```rust +use codeint_config::ReportRenderFormat; +use codeint_report::SavedReport; + +let saved = SavedReport::from_json(&json_text)?; +let sarif = saved.render(ReportRenderFormat::Sarif)?; +``` + +- `SavedReport::from_json` accepts JSON produced by `Report::render(ReportFormat::Json)` or `DiffReport::render(ReportFormat::Json)`. +- It rejects malformed JSON, non-object JSON, unsupported schema versions, and unrecognized payloads with `SavedReportError`. +- `render` formats the saved report as `Toon`, `Json`, `Sarif`, `Markdown`, or `Text` without re-running analysis. diff --git a/crates/report/src/diff.rs b/crates/report/src/diff.rs index cf82cf1..1c0e3d0 100644 --- a/crates/report/src/diff.rs +++ b/crates/report/src/diff.rs @@ -6,13 +6,13 @@ use codeint_config::{ use codeint_model::{Metric, SourceSet}; use serde::ser::SerializeMap; -use serde::{Serialize, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::measurement::{CommitMeasurement, MetricMeasurement, SourceSetMeasurement}; use crate::sarif::{ListedExternalMetric, ListedFindings, SarifLog}; use crate::{ BoundaryFindingRow, BudgetFailure, CloneGroupFinding, Decimal, ErodedFunctionFinding, - ExternalMetricFinding, Findings, FlaggedLineRow, ImportCycleFinding, ReportError, + ExternalMetricFinding, Findings, FlaggedLineRow, ImportCycleFinding, PerSourceSet, ReportError, }; mod markdown; @@ -36,31 +36,29 @@ pub struct HeadCommit { pub commit: String, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] pub struct DiffReport { base: BaseEntry, head: HeadEntry, source_sets: SourceSetChangesSections, - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] over_budget: Vec, - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] regressions: Vec, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] pub(crate) struct Regression { - source_set: &'static str, + source_set: String, metric: String, rule: RegressionRule, base: Decimal, head: Decimal, new_findings: usize, ratio_rise_limit: f64, - #[serde(skip)] - numerator_key: &'static str, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] enum RegressionRule { RatioRise, @@ -68,17 +66,17 @@ enum RegressionRule { NumeratorRiseWithNewFindings, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct BaseEntry { #[serde(rename = "ref")] git_ref: String, merge_base: String, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] enum HeadEntry { - WorkingTree(&'static str), + WorkingTree(String), Commit { #[serde(rename = "ref")] git_ref: String, @@ -86,31 +84,21 @@ enum HeadEntry { }, } -#[derive(Debug, Default, Serialize)] -struct SourceSetChangesSections { - #[serde(skip_serializing_if = "Option::is_none")] - production: Option, - #[serde(skip_serializing_if = "Option::is_none")] - test: Option, - #[serde(skip_serializing_if = "Option::is_none")] - generated: Option, - #[serde(skip_serializing_if = "Option::is_none")] - vendored: Option, -} +type SourceSetChangesSections = PerSourceSet; -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct SourceSetChanges { erosion: MetricChanges, duplication: MetricChanges, verbosity: MetricChanges, import_cycles: MetricChanges, - #[serde(skip_serializing_if = "Option::is_none")] + #[serde(default, skip_serializing_if = "Option::is_none")] boundaries: Option>, - #[serde(flatten)] + #[serde(default, flatten)] external_metrics: BTreeMap, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct ExternalMetricChanges { #[serde(skip)] name: String, @@ -182,11 +170,21 @@ impl DiffReport { ReportFormat::Markdown => Ok(markdown::render(self)), } } + + pub(crate) fn populate_external_metric_names(&mut self) { + for slot in self.source_sets.iter_mut() { + for (key, external) in &mut slot.external_metrics { + if external.name.is_empty() { + external.name = key.clone(); + } + } + } + } } fn head_entry(head: Head) -> HeadEntry { match head { - Head::WorkingTree => HeadEntry::WorkingTree(WORKING_TREE), + Head::WorkingTree => HeadEntry::WorkingTree(WORKING_TREE.to_owned()), Head::Commit(HeadCommit { git_ref, commit }) => HeadEntry::Commit { git_ref, commit }, } } @@ -239,6 +237,40 @@ impl Serialize for MetricChanges { } } +impl<'de, T: Deserialize<'de>> Deserialize<'de> for MetricChanges { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + struct RawMetricChanges { + base_ratio: Decimal, + head_ratio: Decimal, + new: Vec, + #[serde(default)] + new_left_out: usize, + resolved: Vec, + #[serde(default)] + resolved_left_out: usize, + unchanged: usize, + } + + let raw = RawMetricChanges::::deserialize(deserializer)?; + Ok(MetricChanges { + base_ratio: raw.base_ratio, + head_ratio: raw.head_ratio, + base_numerator: Decimal(0.0), + head_numerator: Decimal(0.0), + new: Findings { + listed: raw.new, + left_out: raw.new_left_out, + }, + resolved: Findings { + listed: raw.resolved, + left_out: raw.resolved_left_out, + }, + unchanged: raw.unchanged, + }) + } +} + fn classify( base: MetricMeasurement, head: MetricMeasurement, @@ -354,14 +386,13 @@ impl MetricChanges { .map(|rule| { let (base, head) = self.compared_values(rule); Regression { - source_set: source_set.key(), + source_set: source_set.key().to_owned(), metric: metric_key.to_owned(), rule, base, head, new_findings: self.new_findings(), ratio_rise_limit: limit.ratio_rise.ratio(), - numerator_key: numerator_key(metric_key), } }) .collect() @@ -409,9 +440,9 @@ impl Regression { } RegressionRule::NumeratorRiseWithNewFindings => format!( "The {} {} numerator {} rose from {} to {} with {}.", - crate::markdown::prose(self.source_set), + crate::markdown::prose(&self.source_set), crate::markdown::prose(&self.metric), - crate::markdown::code(self.numerator_key), + crate::markdown::code(numerator_key(&self.metric)), self.base.0, self.head.0, new_findings_phrase(self.new_findings) @@ -443,7 +474,7 @@ impl std::fmt::Display for Regression { RegressionRule::NumeratorRiseWithNewFindings => write!( formatter, "the {source_set} {metric} numerator {} rose from {} to {} with {}", - self.numerator_key, + numerator_key(metric), base.0, head.0, new_findings_phrase(self.new_findings) @@ -542,34 +573,6 @@ fn source_set_changes( } } -impl SourceSetChangesSections { - fn iter(&self) -> impl Iterator { - [ - (SourceSet::Production, &self.production), - (SourceSet::Test, &self.test), - (SourceSet::Generated, &self.generated), - (SourceSet::Vendored, &self.vendored), - ] - .into_iter() - .filter_map(|(source_set, changes)| Some((source_set, changes.as_ref()?))) - } - - fn named(&self) -> Vec<(&'static str, &SourceSetChanges)> { - self.iter() - .map(|(source_set, changes)| (source_set_name(source_set), changes)) - .collect() - } - - fn slot(&mut self, source_set: SourceSet) -> &mut Option { - match source_set { - SourceSet::Production => &mut self.production, - SourceSet::Test => &mut self.test, - SourceSet::Generated => &mut self.generated, - SourceSet::Vendored => &mut self.vendored, - } - } -} - impl Identified for ErodedFunctionFinding { fn id(&self) -> &str { &self.id @@ -605,12 +608,3 @@ impl Identified for BoundaryFindingRow { &self.id } } - -fn source_set_name(source_set: SourceSet) -> &'static str { - match source_set { - SourceSet::Production => "Production", - SourceSet::Test => "Test", - SourceSet::Generated => "Generated", - SourceSet::Vendored => "Vendored", - } -} diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index ec6083c..343ad0f 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -16,13 +16,14 @@ use codeint_model::{ ReferenceRanges, RepoPath, SkippedFile, SourceSet, SourceSets, }; use serde::ser::SerializeMap; -use serde::{Deserialize, Serialize, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; mod diff; mod guard; mod markdown; mod measurement; mod sarif; +mod saved; #[cfg(test)] mod tests; mod trend; @@ -30,6 +31,7 @@ mod trend; pub use diff::{BaseCommit, DiffReport, Head, HeadCommit}; pub use guard::{GuardAllowedTarget, GuardDeniedTarget, GuardReport}; pub use measurement::CommitMeasurement; +pub use saved::{SavedReport, SavedReportError}; pub use trend::{TrendPoint, TrendReport}; const DECIMAL_SCALE: f64 = 10_000.0; @@ -47,25 +49,25 @@ pub enum ReportError { Sarif(#[source] serde_json::Error), } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] pub struct Report { #[serde(flatten)] measured: MeasuredSection, - #[serde(skip_serializing_if = "BTreeMap::is_empty")] + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] languages: BTreeMap, - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] skipped: Vec, - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] declaration_only: Vec, - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] submodules: Vec, - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] over_budget: Vec, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] pub struct BudgetFailure { - source_set: &'static str, + source_set: String, metric: String, ratio: Decimal, budget: f64, @@ -77,7 +79,7 @@ pub struct MeasuredLanguage { pub reference_ranges: ReferenceRanges, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct MeasuredSection { files: usize, source_lines: u64, @@ -89,7 +91,7 @@ enum ReferenceRangeScope { SeveralLanguages, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] enum ReferenceRangeEntry { Published { @@ -97,22 +99,84 @@ enum ReferenceRangeEntry { high: Decimal, source: String, }, - NotShown(&'static str), + NotShown(String), } -#[derive(Debug, Default, Serialize)] -struct SourceSetSections { - #[serde(skip_serializing_if = "Option::is_none")] - production: Option, - #[serde(skip_serializing_if = "Option::is_none")] - test: Option, - #[serde(skip_serializing_if = "Option::is_none")] - generated: Option, - #[serde(skip_serializing_if = "Option::is_none")] - vendored: Option, +#[derive(Debug, Serialize, Deserialize)] +#[serde(bound(deserialize = "T: Deserialize<'de>"))] +pub(crate) struct PerSourceSet { + #[serde(default, skip_serializing_if = "Option::is_none")] + production: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + test: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + generated: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + vendored: Option, +} + +impl Default for PerSourceSet { + fn default() -> PerSourceSet { + PerSourceSet { + production: None, + test: None, + generated: None, + vendored: None, + } + } +} + +impl PerSourceSet { + pub(crate) fn iter(&self) -> impl Iterator { + [ + (SourceSet::Production, &self.production), + (SourceSet::Test, &self.test), + (SourceSet::Generated, &self.generated), + (SourceSet::Vendored, &self.vendored), + ] + .into_iter() + .filter_map(|(source_set, section)| Some((source_set, section.as_ref()?))) + } + + pub(crate) fn iter_mut(&mut self) -> impl Iterator { + [ + &mut self.production, + &mut self.test, + &mut self.generated, + &mut self.vendored, + ] + .into_iter() + .flatten() + } + + pub(crate) fn named(&self) -> Vec<(&'static str, &T)> { + self.iter() + .map(|(source_set, section)| (source_set_label(source_set), section)) + .collect() + } + + pub(crate) fn slot(&mut self, source_set: SourceSet) -> &mut Option { + match source_set { + SourceSet::Production => &mut self.production, + SourceSet::Test => &mut self.test, + SourceSet::Generated => &mut self.generated, + SourceSet::Vendored => &mut self.vendored, + } + } +} + +fn source_set_label(source_set: SourceSet) -> &'static str { + match source_set { + SourceSet::Production => "Production", + SourceSet::Test => "Test", + SourceSet::Generated => "Generated", + SourceSet::Vendored => "Vendored", + } } -#[derive(Debug, Serialize)] +type SourceSetSections = PerSourceSet; + +#[derive(Debug, Serialize, Deserialize)] struct SourceSetSection { files: usize, source_lines: u64, @@ -120,15 +184,15 @@ struct SourceSetSection { duplication: DuplicationSection, verbosity: VerbositySection, import_cycles: ImportCyclesSection, - #[serde(skip_serializing_if = "Option::is_none")] + #[serde(default, skip_serializing_if = "Option::is_none")] boundaries: Option, - #[serde(flatten)] + #[serde(default, flatten)] external_metrics: BTreeMap, - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] packages: Vec, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct BoundariesSection { ratio: Decimal, resolved_imports: usize, @@ -154,7 +218,7 @@ struct BoundaryFindingRow { message: String, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct ExternalMetricSection { #[serde(skip)] name: String, @@ -178,7 +242,7 @@ struct ExternalMetricFinding { message: String, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct PackageSection { path: String, files: usize, @@ -189,32 +253,32 @@ struct PackageSection { import_cycles: PackageImportCycles, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct PackageErosion { ratio: Decimal, eroded_function_mass: Decimal, total_function_mass: Decimal, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct PackageDuplication { ratio: Decimal, clone_lines: u64, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct PackageVerbosity { ratio: Decimal, verbose_lines: u64, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct PackageImportCycles { ratio: Decimal, modules_in_import_cycles: usize, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct ErosionSection { ratio: Decimal, reference_range: ReferenceRangeEntry, @@ -245,7 +309,7 @@ struct ErodedFunctionFinding { function_mass: Decimal, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct DuplicationSection { ratio: Decimal, reference_range: ReferenceRangeEntry, @@ -268,7 +332,7 @@ struct CloneLocation { end_line: u32, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct VerbositySection { ratio: Decimal, reference_range: ReferenceRangeEntry, @@ -287,7 +351,7 @@ struct FlaggedLineRow { rule: String, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct ImportCyclesSection { ratio: Decimal, reference_range: ReferenceRangeEntry, @@ -298,14 +362,14 @@ struct ImportCyclesSection { unresolved_imports: UnresolvedImportsSection, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct UnresolvedImportsSection { count: usize, #[serde(flatten)] imports: Findings, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct UnresolvedImportRow { importer: String, specifier: String, @@ -322,7 +386,7 @@ struct ImportCycleFinding { #[serde(transparent)] struct Decimal(f64); -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] struct SkippedEntry { path: String, reason: String, @@ -346,7 +410,7 @@ fn over_budget<'a>( .filter_map(|(source_set, metric, ratio)| { let budget = budgets.budget_for_key(source_set, metric)?; (!budget.admits(ratio)).then(|| BudgetFailure { - source_set: source_set.key(), + source_set: source_set.key().to_owned(), metric: metric.to_owned(), ratio: Decimal(ratio), budget: budget.ratio(), @@ -366,12 +430,12 @@ impl Decimal { impl ReferenceRangeScope { fn entry(&self, metric: &str) -> ReferenceRangeEntry { match self { - ReferenceRangeScope::OneLanguage(ranges) => ranges.for_metric(metric).map_or( - ReferenceRangeEntry::NotShown(NOT_PUBLISHED_FOR_THIS_LANGUAGE), + ReferenceRangeScope::OneLanguage(ranges) => ranges.for_metric(metric).map_or_else( + || ReferenceRangeEntry::NotShown(NOT_PUBLISHED_FOR_THIS_LANGUAGE.to_owned()), ReferenceRangeEntry::from, ), ReferenceRangeScope::SeveralLanguages => { - ReferenceRangeEntry::NotShown(NOT_SHOWN_FOR_SEVERAL_LANGUAGES) + ReferenceRangeEntry::NotShown(NOT_SHOWN_FOR_SEVERAL_LANGUAGES.to_owned()) } } } @@ -415,6 +479,41 @@ impl Serialize for Findings { } } +impl<'de, T: FindingKind + Deserialize<'de>> Deserialize<'de> for Findings { + fn deserialize>(deserializer: D) -> Result { + struct FindingsVisitor(std::marker::PhantomData); + + impl<'de, T: FindingKind + Deserialize<'de>> serde::de::Visitor<'de> for FindingsVisitor { + type Value = Findings; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "findings map with {}", T::LIST_KEY) + } + + fn visit_map>( + self, + mut map: A, + ) -> Result { + let mut listed = None; + let mut left_out = 0; + while let Some(key) = map.next_key::()? { + if key == T::LIST_KEY { + listed = Some(map.next_value()?); + } else if key == T::LEFT_OUT_KEY { + left_out = map.next_value()?; + } else { + let _ = map.next_value::()?; + } + } + let listed = listed.ok_or_else(|| serde::de::Error::missing_field(T::LIST_KEY))?; + Ok(Findings { listed, left_out }) + } + } + + deserializer.deserialize_map(FindingsVisitor(std::marker::PhantomData)) + } +} + impl FindingKind for ErodedFunctionFinding { const LIST_KEY: &'static str = "findings"; } @@ -545,17 +644,6 @@ impl SourceSetSections { Ok(sections) } - fn iter(&self) -> impl Iterator { - [ - (SourceSet::Production, &self.production), - (SourceSet::Test, &self.test), - (SourceSet::Generated, &self.generated), - (SourceSet::Vendored, &self.vendored), - ] - .into_iter() - .filter_map(|(source_set, section)| Some((source_set, section.as_ref()?))) - } - fn over_budget(&self, budgets: &Budgets) -> Vec { over_budget( budgets, @@ -594,15 +682,6 @@ impl SourceSetSections { }), ) } - - fn slot(&mut self, source_set: SourceSet) -> &mut Option { - match source_set { - SourceSet::Production => &mut self.production, - SourceSet::Test => &mut self.test, - SourceSet::Generated => &mut self.generated, - SourceSet::Vendored => &mut self.vendored, - } - } } impl SourceSetSection { @@ -914,6 +993,16 @@ impl MeasuredSection { source_sets, }) } + + fn populate_external_metric_names(&mut self) { + for slot in self.source_sets.iter_mut() { + for (key, metric) in &mut slot.external_metrics { + if metric.name.is_empty() { + metric.name = key.clone(); + } + } + } + } } impl Report { @@ -1005,6 +1094,13 @@ impl Report { }) } + pub(crate) fn populate_external_metric_names(&mut self) { + self.measured.populate_external_metric_names(); + for section in self.languages.values_mut() { + section.populate_external_metric_names(); + } + } + pub fn over_budget(&self) -> &[BudgetFailure] { &self.over_budget } diff --git a/crates/report/src/markdown.rs b/crates/report/src/markdown.rs index 5b45835..ed4ea67 100644 --- a/crates/report/src/markdown.rs +++ b/crates/report/src/markdown.rs @@ -2,7 +2,7 @@ use crate::{ BoundaryFindingRow, CloneGroupFinding, CloneLocation, DuplicationSection, ErodedFunctionFinding, ErosionSection, ExternalMetricFinding, Findings, FlaggedLineRow, ImportCycleFinding, ImportCyclesSection, MeasuredSection, PackageSection, ReferenceRangeEntry, - Report, SourceSetSection, SourceSetSections, UnresolvedImportRow, VerbositySection, + Report, SourceSetSection, UnresolvedImportRow, VerbositySection, }; #[cfg(test)] @@ -191,20 +191,6 @@ fn package_row(source_set: &str, package: &PackageSection) -> Vec { ] } -impl SourceSetSections { - fn named(&self) -> Vec<(&'static str, &SourceSetSection)> { - [ - ("Production", &self.production), - ("Test", &self.test), - ("Generated", &self.generated), - ("Vendored", &self.vendored), - ] - .into_iter() - .filter_map(|(name, section)| section.as_ref().map(|section| (name, section))) - .collect() - } -} - fn measured_summary(measured: &MeasuredSection) -> String { let sections = measured.source_sets.named(); let total = files_and_lines(measured.files, measured.source_lines); diff --git a/crates/report/src/saved.rs b/crates/report/src/saved.rs new file mode 100644 index 0000000..46a3a5a --- /dev/null +++ b/crates/report/src/saved.rs @@ -0,0 +1,112 @@ +use codeint_config::ReportRenderFormat; +use serde_json::{Map, Value}; + +use crate::{DiffReport, Report, ReportError}; + +#[cfg(test)] +mod tests; + +#[derive(Debug, thiserror::Error)] +pub enum SavedReportError { + #[error("the input is not valid JSON")] + InvalidJson(#[source] serde_json::Error), + #[error("the saved report must be a JSON object")] + NotAnObject, + #[error("unsupported report schema version {found}; this codeint supports schema version 1")] + UnsupportedSchemaVersion { found: String }, + #[error("the input is not a recognized codeint check or diff JSON report")] + UnrecognizedReport, + #[error("cannot parse the saved {kind} report")] + InvalidPayload { + kind: &'static str, + #[source] + source: serde_json::Error, + }, +} + +#[derive(Debug)] +pub enum SavedReport { + Check(Box), + Diff(Box), +} + +impl SavedReport { + pub fn from_json(text: &str) -> Result { + let value: Value = serde_json::from_str(text).map_err(SavedReportError::InvalidJson)?; + let object = value.as_object().ok_or(SavedReportError::NotAnObject)?; + validate_schema_version(object)?; + if is_diff_shape(object) { + let mut report: DiffReport = serde_json::from_value(value).map_err(|source| { + SavedReportError::InvalidPayload { + kind: "diff", + source, + } + })?; + report.populate_external_metric_names(); + return Ok(SavedReport::Diff(Box::new(report))); + } + if is_check_shape(object) { + let mut report: Report = serde_json::from_value(value).map_err(|source| { + SavedReportError::InvalidPayload { + kind: "check", + source, + } + })?; + report.populate_external_metric_names(); + return Ok(SavedReport::Check(Box::new(report))); + } + Err(SavedReportError::UnrecognizedReport) + } + + pub fn render(&self, format: ReportRenderFormat) -> Result { + let report_format = format.as_report_format(); + match self { + SavedReport::Check(report) => report.render(report_format), + SavedReport::Diff(report) => report.render(report_format), + } + } +} + +fn validate_schema_version(object: &Map) -> Result<(), SavedReportError> { + if let Some(version) = object.get("schema_version") + && !is_supported_schema_version(version) + { + return Err(SavedReportError::UnsupportedSchemaVersion { + found: format_schema_value(version), + }); + } + if let Some(schema) = object.get("$schema") { + return Err(SavedReportError::UnsupportedSchemaVersion { + found: format_schema_value(schema), + }); + } + if let Some(version) = object.get("version") + && !is_supported_schema_version(version) + { + return Err(SavedReportError::UnsupportedSchemaVersion { + found: format_schema_value(version), + }); + } + Ok(()) +} + +fn is_supported_schema_version(value: &Value) -> bool { + value.as_u64() == Some(1) || value.as_str() == Some("1") +} + +fn format_schema_value(value: &Value) -> String { + match value.as_str() { + Some(text) => format!("\"{text}\""), + None => value.to_string(), + } +} + +fn is_diff_shape(object: &Map) -> bool { + object.contains_key("base") && object.contains_key("head") && object.contains_key("source_sets") +} + +fn is_check_shape(object: &Map) -> bool { + object.contains_key("files") + && object.contains_key("source_lines") + && object.contains_key("source_sets") +} diff --git a/crates/report/src/saved/tests.rs b/crates/report/src/saved/tests.rs new file mode 100644 index 0000000..c476cc7 --- /dev/null +++ b/crates/report/src/saved/tests.rs @@ -0,0 +1,26 @@ +use super::{SavedReport, SavedReportError}; + +#[test] +fn rejects_non_object_json_values() { + let err = SavedReport::from_json("[1, 2]").expect_err("array is not a saved report"); + assert!(matches!(err, SavedReportError::NotAnObject)); +} + +#[test] +fn accepts_explicit_schema_version_1() { + let json = r#"{"schema_version": 1, "files": 0, "source_lines": 0, "source_sets": {}}"#; + let parsed = SavedReport::from_json(json).expect("schema_version 1 is supported"); + assert!(matches!(parsed, SavedReport::Check(_))); +} + +#[test] +fn rejects_unsupported_schema_version_values() { + let err = SavedReport::from_json( + r#"{"schema_version": "2.0", "files": 0, "source_lines": 0, "source_sets": {}}"#, + ) + .expect_err("schema_version 2.0 is unsupported"); + assert!(matches!( + err, + SavedReportError::UnsupportedSchemaVersion { .. } + )); +} diff --git a/docs/reference.md b/docs/reference.md index 92e93a0..33ebaa0 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -30,6 +30,7 @@ The working tree adds `src/route.ts`, an eroded function that is not committed. | `update` | Update a standalone codeint binary in place from GitHub Releases; see [`codeint update`](#codeint-update) | | `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, `trend`, and `guard` tools; see [`codeint mcp`](#codeint-mcp) | | `guard` | Show the architectural boundary zone, allowed and denied target zones, `public_files` constraints, and allowed importers for a file path; see [`codeint guard`](#codeint-guard) | +| `report` | Re-render a saved `check` or `diff` JSON report into another format without re-running analysis; see [`codeint report`](#codeint-report) | | `help` | Print the help of codeint, or of the command that follows it | | Option | Meaning | @@ -514,6 +515,36 @@ codeint guard src/route.ts --format toon codeint guard src/route.ts --format json ``` +### `codeint report` + +| Argument | Meaning | +| -------- | ------- | +| `` | Path to a saved `check` or `diff` JSON report, or `-` to read from standard input | + +| Option | Meaning | +| ------ | ------- | +| `--output ` | Write the report to this file instead of standard output | +| `--format ` | The format of the report: `toon`, the default, `json`, `sarif`, `markdown`, or `text` | +| `-h, --help` | Print the help of `codeint report` | + +`codeint report` re-renders a saved `codeint check --format json` or `codeint diff --format json` payload into another format without re-running analysis. +Pass `-` as `` to read the JSON payload from standard input. +`--format text` prints the same compact text report as `--format toon`. + +```sh exit=0 +codeint report report.json --format toon +codeint report report.json --format json +codeint report report.json --format sarif --output report.sarif +codeint report report.json --format markdown +codeint report report.json --format text +``` + +An input file that does not exist, malformed JSON, or an unsupported report schema version stops the run with exit code 2: + +```sh exit=2 +codeint report missing.json --format sarif +``` + ## Exit codes | Exit code | Meaning | From c604e564baf5df8c83e89e69d2e3e7ff628f949a Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 09:49:03 +0800 Subject: [PATCH 5/6] feat(cli): add agent status and agent install commands Add codeint agent status and codeint agent install (--dry-run, --client, --config-root, --format text|toon|json) for Claude Code, Cursor, and Codex using atomic temp-file-then-rename updates that preserve existing settings and unrelated MCP servers. Closes #189 --- Cargo.lock | 1 + crates/cli/Cargo.toml | 3 +- crates/cli/src/agent.rs | 509 ++++++++++++++++++++++++++ crates/cli/src/lib.rs | 56 ++- crates/cli/src/remedy.rs | 24 ++ crates/cli/tests/agent.rs | 399 ++++++++++++++++++++ crates/config/src/agent_home.rs | 37 ++ crates/config/src/agent_home/tests.rs | 66 ++++ crates/config/src/lib.rs | 150 ++++++++ crates/report/src/agent.rs | 132 +++++++ crates/report/src/lib.rs | 4 + docs/reference.md | 26 ++ 12 files changed, 1402 insertions(+), 5 deletions(-) create mode 100644 crates/cli/src/agent.rs create mode 100644 crates/cli/tests/agent.rs create mode 100644 crates/config/src/agent_home.rs create mode 100644 crates/config/src/agent_home/tests.rs create mode 100644 crates/report/src/agent.rs diff --git a/Cargo.lock b/Cargo.lock index ef7306e..26815a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -298,6 +298,7 @@ dependencies = [ "serde_json", "tempfile", "thiserror", + "toml", "toon-format", ] diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index b4a5506..d346725 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -22,8 +22,9 @@ codeint-plugin-host = { workspace = true } codeint-report = { workspace = true } rayon = { workspace = true } serde = { workspace = true } -serde_json = { workspace = true } +serde_json = { workspace = true, features = ["preserve_order"] } thiserror = { workspace = true } +toml = { workspace = true } [dev-dependencies] tempfile = { workspace = true } diff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rs new file mode 100644 index 0000000..37c4bfd --- /dev/null +++ b/crates/cli/src/agent.rs @@ -0,0 +1,509 @@ +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use codeint_config::AgentClient; +use codeint_report::{ + AgentInstallAction, AgentInstallEntry, AgentInstallReport, AgentStatusEntry, AgentStatusReport, +}; +use serde_json::{Map as JsonMap, Value as JsonValue}; + +const CODEINT_SERVER_NAME: &str = "codeint"; +const CODEINT_COMMAND: &str = "codeint"; +const CODEINT_MCP_ARG: &str = "mcp"; +const JSON_MCP_KEY: &str = "mcpServers"; +const TOML_MCP_KEY: &str = "mcp_servers"; + +static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0); + +#[derive(Debug, thiserror::Error)] +pub(crate) enum AgentError { + #[error("cannot read agent configuration file {}", path.display())] + Read { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("agent configuration file {} is not valid JSON", path.display())] + InvalidJson { + path: PathBuf, + #[source] + source: serde_json::Error, + }, + #[error("agent configuration file {} is not valid TOML", path.display())] + InvalidToml { + path: PathBuf, + #[source] + source: toml::de::Error, + }, + #[error("cannot serialize JSON configuration for {}", path.display())] + SerializeJson { + path: PathBuf, + #[source] + source: serde_json::Error, + }, + #[error("cannot serialize TOML configuration for {}", path.display())] + SerializeToml { + path: PathBuf, + #[source] + source: toml::ser::Error, + }, + #[error( + "agent configuration file {} must contain a top-level JSON object", + path.display() + )] + ExpectedRootObject { path: PathBuf }, + #[error( + "agent configuration file {} has a non-object {key} entry", + path.display() + )] + InvalidMcpSection { path: PathBuf, key: &'static str }, + #[error( + "agent configuration file {} has a non-object {key} server entry", + path.display() + )] + InvalidCodeintEntry { path: PathBuf, key: &'static str }, + #[error("cannot create folder {}", path.display())] + CreateDir { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("cannot write agent configuration file {}", path.display())] + Write { + path: PathBuf, + #[source] + source: std::io::Error, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ConfigFormat { + Json, + Toml, +} + +enum MergeOutcome { + Unchanged, + Changed(String), +} + +struct PlannedUpdate { + client: AgentClient, + config_path: PathBuf, + action: AgentInstallAction, + content: Option, +} + +trait ConfigDocument: Sized { + const MCP_KEY: &'static str; + + fn empty() -> Self; + fn parse(path: &Path, raw: &str) -> Result; + fn render(&self, path: &Path) -> Result; + fn child_object(&self, key: &str) -> Result, ()>; + fn ensure_child_object(&mut self, key: &str) -> Result<&mut Self, ()>; + fn matches_codeint_mcp(&self) -> bool; + fn write_codeint_mcp(&mut self); +} + +impl ConfigDocument for JsonMap { + const MCP_KEY: &'static str = JSON_MCP_KEY; + + fn empty() -> Self { + JsonMap::new() + } + + fn parse(path: &Path, raw: &str) -> Result { + let parsed: JsonValue = + serde_json::from_str(raw).map_err(|source| AgentError::InvalidJson { + path: path.to_path_buf(), + source, + })?; + match parsed { + JsonValue::Object(map) => Ok(map), + _ => Err(AgentError::ExpectedRootObject { + path: path.to_path_buf(), + }), + } + } + + fn render(&self, path: &Path) -> Result { + let mut rendered = + serde_json::to_string_pretty(&JsonValue::Object(self.clone())).map_err(|source| { + AgentError::SerializeJson { + path: path.to_path_buf(), + source, + } + })?; + rendered.push('\n'); + Ok(rendered) + } + + fn child_object(&self, key: &str) -> Result, ()> { + match self.get(key) { + None => Ok(None), + Some(JsonValue::Object(map)) => Ok(Some(map)), + Some(_) => Err(()), + } + } + + fn ensure_child_object(&mut self, key: &str) -> Result<&mut Self, ()> { + self.entry(key.to_owned()) + .or_insert_with(|| JsonValue::Object(JsonMap::new())) + .as_object_mut() + .ok_or(()) + } + + fn matches_codeint_mcp(&self) -> bool { + self.get("command") == Some(&JsonValue::String(CODEINT_COMMAND.to_owned())) + && self.get("args") == Some(&serde_json::json!([CODEINT_MCP_ARG])) + } + + fn write_codeint_mcp(&mut self) { + self.insert( + "command".to_owned(), + JsonValue::String(CODEINT_COMMAND.to_owned()), + ); + self.insert("args".to_owned(), serde_json::json!([CODEINT_MCP_ARG])); + } +} + +impl ConfigDocument for toml::Table { + const MCP_KEY: &'static str = TOML_MCP_KEY; + + fn empty() -> Self { + toml::Table::new() + } + + fn parse(path: &Path, raw: &str) -> Result { + toml::from_str::(raw).map_err(|source| AgentError::InvalidToml { + path: path.to_path_buf(), + source, + }) + } + + fn render(&self, path: &Path) -> Result { + let mut rendered = + toml::to_string_pretty(self).map_err(|source| AgentError::SerializeToml { + path: path.to_path_buf(), + source, + })?; + if !rendered.ends_with('\n') { + rendered.push('\n'); + } + Ok(rendered) + } + + fn child_object(&self, key: &str) -> Result, ()> { + self.get(key) + .map(|value| value.as_table().ok_or(())) + .transpose() + } + + fn ensure_child_object(&mut self, key: &str) -> Result<&mut Self, ()> { + if !self.contains_key(key) { + self.insert(key.to_owned(), toml::Value::Table(toml::Table::new())); + } + self.get_mut(key) + .and_then(toml::Value::as_table_mut) + .ok_or(()) + } + + fn matches_codeint_mcp(&self) -> bool { + matches!( + (self.get("command"), self.get("args")), + (Some(toml::Value::String(cmd)), Some(toml::Value::Array(args))) + if cmd == CODEINT_COMMAND + && args.len() == 1 + && args[0].as_str() == Some(CODEINT_MCP_ARG) + ) + } + + fn write_codeint_mcp(&mut self) { + let args = vec![toml::Value::from(CODEINT_MCP_ARG)]; + self.insert("command".to_owned(), toml::Value::from(CODEINT_COMMAND)); + self.insert("args".to_owned(), toml::Value::from(args)); + } +} + +pub(crate) fn status( + config_root: &Path, + selected: Option, +) -> Result { + let clients = selected.map_or_else(|| AgentClient::ALL.to_vec(), |client| vec![client]); + let mut agents = Vec::with_capacity(clients.len()); + for client in clients { + agents.push(inspect_client(config_root, client)?); + } + Ok(AgentStatusReport { + config_root: config_root.display().to_string(), + agents, + }) +} + +pub(crate) fn install( + config_root: &Path, + selected: Option, + dry_run: bool, +) -> Result { + let targets = resolve_install_targets(config_root, selected); + if targets.is_empty() { + return Ok(AgentInstallReport { + config_root: config_root.display().to_string(), + dry_run, + results: Vec::new(), + note: Some( + "No supported coding agents detected; pass --client to configure one explicitly." + .to_owned(), + ), + }); + } + let mut results = Vec::with_capacity(targets.len()); + for client in targets { + let plan = plan_client_update(config_root, client)?; + results.push(apply_or_preview(plan, dry_run)?); + } + Ok(AgentInstallReport { + config_root: config_root.display().to_string(), + dry_run, + results, + note: None, + }) +} + +fn resolve_install_targets(config_root: &Path, selected: Option) -> Vec { + match selected { + Some(client) => vec![client], + None => AgentClient::ALL + .into_iter() + .filter(|client| is_client_detected(config_root, *client)) + .collect(), + } +} + +fn apply_or_preview(plan: PlannedUpdate, dry_run: bool) -> Result { + let (written, preview) = if dry_run { + (false, plan.content) + } else if let Some(content) = plan.content { + atomic_write(&plan.config_path, content.as_bytes())?; + (true, None) + } else { + (false, None) + }; + Ok(AgentInstallEntry { + client: plan.client.as_str(), + name: plan.client.display_name(), + config_path: plan.config_path.display().to_string(), + action: plan.action, + written, + preview, + }) +} + +fn inspect_client(config_root: &Path, client: AgentClient) -> Result { + let config_path = client_config_path(config_root, client); + let detected = is_client_detected(config_root, client); + let config_exists = config_path.is_file(); + let registered = if config_exists { + let raw = read_config_file(&config_path)?; + match client_format(client) { + ConfigFormat::Json => { + is_registered_in_doc::>(&config_path, &raw)? + } + ConfigFormat::Toml => is_registered_in_doc::(&config_path, &raw)?, + } + } else { + false + }; + Ok(AgentStatusEntry { + client: client.as_str(), + name: client.display_name(), + config_path: config_path.display().to_string(), + detected, + config_exists, + registered, + }) +} + +fn plan_client_update( + config_root: &Path, + client: AgentClient, +) -> Result { + let config_path = client_config_path(config_root, client); + let existed = config_path.is_file(); + let existing = if existed { + Some(read_config_file(&config_path)?) + } else { + None + }; + let merge = match client_format(client) { + ConfigFormat::Json => { + merge_document::>(&config_path, existing.as_deref())? + } + ConfigFormat::Toml => merge_document::(&config_path, existing.as_deref())?, + }; + let (action, content) = match merge { + MergeOutcome::Unchanged => (AgentInstallAction::Unchanged, None), + MergeOutcome::Changed(rendered) => { + let action = if existed { + AgentInstallAction::Update + } else { + AgentInstallAction::Create + }; + (action, Some(rendered)) + } + }; + Ok(PlannedUpdate { + client, + config_path, + action, + content, + }) +} + +fn is_registered_in_doc(path: &Path, raw: &str) -> Result { + if raw.trim().is_empty() { + return Ok(false); + } + let root = D::parse(path, raw)?; + doc_has_codeint_mcp(path, &root) +} + +fn doc_has_codeint_mcp(path: &Path, root: &D) -> Result { + let Some(servers) = + root.child_object(D::MCP_KEY) + .map_err(|()| AgentError::InvalidMcpSection { + path: path.to_path_buf(), + key: D::MCP_KEY, + })? + else { + return Ok(false); + }; + let Ok(Some(entry)) = servers.child_object(CODEINT_SERVER_NAME) else { + return Ok(false); + }; + Ok(entry.matches_codeint_mcp()) +} + +fn merge_document( + path: &Path, + existing: Option<&str>, +) -> Result { + let mut root = match existing.map(str::trim).filter(|text| !text.is_empty()) { + Some(raw) => D::parse(path, raw)?, + None => D::empty(), + }; + if doc_has_codeint_mcp(path, &root)? { + return Ok(MergeOutcome::Unchanged); + } + let servers = + root.ensure_child_object(D::MCP_KEY) + .map_err(|()| AgentError::InvalidMcpSection { + path: path.to_path_buf(), + key: D::MCP_KEY, + })?; + let entry = servers + .ensure_child_object(CODEINT_SERVER_NAME) + .map_err(|()| AgentError::InvalidCodeintEntry { + path: path.to_path_buf(), + key: CODEINT_SERVER_NAME, + })?; + entry.write_codeint_mcp(); + Ok(MergeOutcome::Changed(root.render(path)?)) +} + +fn client_config_path(config_root: &Path, client: AgentClient) -> PathBuf { + match client { + AgentClient::ClaudeCode => config_root.join(".claude.json"), + AgentClient::Cursor => config_root.join(".cursor").join("mcp.json"), + AgentClient::Codex => config_root.join(".codex").join("config.toml"), + } +} + +fn is_client_detected(config_root: &Path, client: AgentClient) -> bool { + match client { + AgentClient::ClaudeCode => { + config_root.join(".claude.json").is_file() || config_root.join(".claude").is_dir() + } + AgentClient::Cursor => { + config_root.join(".cursor").is_dir() + || config_root.join(".cursor").join("mcp.json").is_file() + } + AgentClient::Codex => { + config_root.join(".codex").is_dir() + || config_root.join(".codex").join("config.toml").is_file() + } + } +} + +fn client_format(client: AgentClient) -> ConfigFormat { + match client { + AgentClient::ClaudeCode | AgentClient::Cursor => ConfigFormat::Json, + AgentClient::Codex => ConfigFormat::Toml, + } +} + +fn read_config_file(path: &Path) -> Result { + fs::read_to_string(path).map_err(|source| AgentError::Read { + path: path.to_path_buf(), + source, + }) +} + +fn atomic_write(target: &Path, bytes: &[u8]) -> Result<(), AgentError> { + let parent = target.parent().unwrap_or_else(|| Path::new(".")); + fs::create_dir_all(parent).map_err(|source| AgentError::CreateDir { + path: parent.to_path_buf(), + source, + })?; + let (temp_path, mut file) = create_temp_file(parent, target)?; + let commit = (|| -> std::io::Result<()> { + file.write_all(bytes)?; + file.sync_all()?; + drop(file); + fs::rename(&temp_path, target) + })(); + if let Err(source) = commit { + let _ = fs::remove_file(&temp_path); + return Err(AgentError::Write { + path: target.to_path_buf(), + source, + }); + } + Ok(()) +} + +fn create_temp_file(parent: &Path, target: &Path) -> Result<(PathBuf, fs::File), AgentError> { + let base_name = target + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("config"); + let pid = std::process::id(); + for _ in 0..64 { + let seq = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed); + let candidate = parent.join(format!(".{base_name}.codeint-tmp-{pid}-{seq}")); + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&candidate) + { + Ok(file) => return Ok((candidate, file)), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(source) => { + return Err(AgentError::Write { + path: target.to_path_buf(), + source, + }); + } + } + } + Err(AgentError::Write { + path: target.to_path_buf(), + source: std::io::Error::new( + std::io::ErrorKind::AlreadyExists, + "could not allocate a unique temporary file", + ), + }) +} diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index c3c9d6d..f3dda9c 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -1,5 +1,6 @@ #![forbid(unsafe_code)] +mod agent; mod check; mod commit_measurement; mod diff; @@ -16,15 +17,18 @@ use std::io::Write; use std::path::{Path, PathBuf}; use std::process::ExitCode; -use codeint_config::{Command, ConfigError, ReportDestination, read_invocation}; +use codeint_config::{AgentCommand, Command, ConfigError, ReportDestination, read_invocation}; use codeint_git::ResultCache; use codeint_report::ReportError; pub use codeint_config::{ - CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat, - TrendRange, + AgentClient, AgentFormat, CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, + ReportFormat, TrendFormat, TrendRange, +}; +pub use codeint_report::{ + AgentInstallAction, AgentInstallEntry, AgentInstallReport, AgentStatusEntry, AgentStatusReport, + DiffReport, GuardReport, Report, TrendReport, }; -pub use codeint_report::{DiffReport, GuardReport, Report, TrendReport}; const DEFAULT_WORST_FINDINGS: usize = 20; const DEFAULT_TREND_COMMITS: usize = 20; @@ -188,6 +192,23 @@ pub fn guard(folder: &Path, target: &Path) -> Result guard::guard(folder, target).map_err(|err| CodeintError::from_cli_error(CliError::Guard(err))) } +pub fn agent_status( + config_root: &Path, + client: Option, +) -> Result { + agent::status(config_root, client) + .map_err(|err| CodeintError::from_cli_error(CliError::Agent(err))) +} + +pub fn agent_install( + config_root: &Path, + client: Option, + dry_run: bool, +) -> Result { + agent::install(config_root, client, dry_run) + .map_err(|err| CodeintError::from_cli_error(CliError::Agent(err))) +} + #[derive(Debug, thiserror::Error)] enum CliError { #[error(transparent)] @@ -197,6 +218,8 @@ enum CliError { #[error(transparent)] Guard(#[from] guard::GuardError), #[error(transparent)] + Agent(#[from] agent::AgentError), + #[error(transparent)] Init(#[from] init::InitError), #[error(transparent)] Update(#[from] update::UpdateError), @@ -304,6 +327,31 @@ fn run() -> Result { target, format, } => run_guard(&folder, &target, format), + Command::Agent(command) => run_agent(command), + } +} + +fn run_agent(command: AgentCommand) -> Result { + match command { + AgentCommand::Status { + config_root, + client, + format, + } => { + let report = agent::status(&config_root, client)?; + print_report(&format!("{}\n", report.render(format)?))?; + Ok(Outcome::Passed) + } + AgentCommand::Install { + config_root, + client, + dry_run, + format, + } => { + let report = agent::install(&config_root, client, dry_run)?; + print_report(&format!("{}\n", report.render(format)?))?; + Ok(Outcome::Passed) + } } } diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 9747e89..6890a3c 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -4,6 +4,7 @@ use codeint_model::{MetricPluginError, WorkspaceError}; use codeint_plugin_host::PluginHostError; use crate::CliError; +use crate::agent::AgentError; use crate::check::CheckError; use crate::guard::GuardError; use crate::init::InitError; @@ -14,6 +15,7 @@ pub(crate) fn remedy(error: &CliError) -> &'static str { CliError::Config(error) => config_remedy(error), CliError::Check(error) => check_remedy(error), CliError::Guard(error) => guard_remedy(error), + CliError::Agent(error) => agent_remedy(error), CliError::Init(error) => init_remedy(error), CliError::Update(error) => update_remedy(error), CliError::Report(_) => { @@ -58,6 +60,25 @@ fn guard_remedy(error: &GuardError) -> &'static str { } } +fn agent_remedy(error: &AgentError) -> &'static str { + use AgentError as E; + match error { + E::Read { .. } | E::CreateDir { .. } | E::Write { .. } => { + "Check file and folder permissions for the agent configuration path, then retry." + } + E::InvalidJson { .. } + | E::ExpectedRootObject { .. } + | E::InvalidToml { .. } + | E::InvalidMcpSection { .. } + | E::InvalidCodeintEntry { .. } => { + "Fix the agent configuration file syntax and ensure its MCP servers section maps names to objects." + } + E::SerializeJson { .. } | E::SerializeToml { .. } => { + "This is a defect in codeint; report it at https://github.com/avidianity/codeint/issues." + } + } +} + fn init_remedy(error: &InitError) -> &'static str { match error { InitError::Git(GitError::NotInRepository { .. }) => { @@ -106,6 +127,9 @@ fn config_remedy(error: &ConfigError) -> &'static str { ConfigError::MissingOutputFolder { .. } => { "Create the folder first, or pass --output a file path in a folder that exists." } + ConfigError::MissingAgentHome => { + "Pass --config-root , or set CODEINT_AGENT_HOME or HOME." + } } } diff --git a/crates/cli/tests/agent.rs b/crates/cli/tests/agent.rs new file mode 100644 index 0000000..73e5227 --- /dev/null +++ b/crates/cli/tests/agent.rs @@ -0,0 +1,399 @@ +use std::fs; +use std::path::Path; +use std::process::{Command, Output}; + +use serde_json::{Value, json}; +use tempfile::TempDir; + +fn run_agent_cli(cwd: &Path, agent_home: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_codeint")) + .args(args) + .current_dir(cwd) + .env("CODEINT_AGENT_HOME", agent_home) + .output() + .expect("run codeint") +} + +fn run_ok_stdout(cwd: &Path, agent_home: &Path, args: &[&str]) -> String { + let output = run_agent_cli(cwd, agent_home, args); + assert_eq!( + output.status.code(), + Some(0), + "args={args:?} stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).expect("utf8 stdout") +} + +fn run_ok_json(cwd: &Path, agent_home: &Path, args: &[&str]) -> Value { + let raw = run_ok_stdout(cwd, agent_home, args); + serde_json::from_str(&raw).expect("valid JSON stdout") +} + +fn write_file(root: &Path, relative: &str, contents: &str) { + let target = root.join(relative); + if let Some(parent) = target.parent() { + fs::create_dir_all(parent).expect("create parent dirs"); + } + fs::write(target, contents).expect("write file"); +} + +fn assert_clean_temp_files(home: &Path) { + for rel in [".", ".cursor", ".codex"] { + let dir = home.join(rel); + if !dir.is_dir() { + continue; + } + for entry in fs::read_dir(&dir).expect("read dir") { + let name = entry.expect("dir entry").file_name(); + let text = name.to_string_lossy(); + assert!( + !text.contains(".codeint-tmp-"), + "unexpected leftover temp file {text} in {}", + dir.display() + ); + } + } +} + +fn assert_claude_preserved(doc: &Value) { + assert_eq!(doc["theme"], "dark"); + assert_eq!(doc["numStartups"], 7); + assert_eq!(doc["mcpServers"]["other-tool"]["command"], "npx"); + assert_eq!( + doc["mcpServers"]["codeint"], + json!({"command": "codeint", "args": ["mcp"]}) + ); +} + +fn seed_three_detected_agents(home: &Path) -> (String, String) { + let claude_initial = serde_json::to_string_pretty(&json!({ + "theme": "dark", + "numStartups": 7, + "mcpServers": { + "other-tool": { + "command": "npx", + "args": ["-y", "other-tool"] + } + } + })) + .expect("serialize claude"); + write_file(home, ".claude.json", &claude_initial); + fs::create_dir_all(home.join(".cursor")).expect("create cursor dir"); + + let codex_initial = concat!( + "model = \"gpt-5\"\n", + "\n", + "[mcp_servers.memory]\n", + "command = \"npx\"\n", + "args = [\"-y\", \"@modelcontextprotocol/server-memory\"]\n", + ) + .to_owned(); + write_file(home, ".codex/config.toml", &codex_initial); + (claude_initial, codex_initial) +} + +#[test] +fn agent_status_reports_detected_clients_and_registration_state() { + let home = TempDir::new().expect("create temp home"); + write_file( + home.path(), + ".claude.json", + &serde_json::to_string_pretty(&json!({ + "theme": "dark", + "mcpServers": { + "codeint": { + "command": "codeint", + "args": ["mcp"] + } + } + })) + .expect("serialize json"), + ); + fs::create_dir_all(home.path().join(".cursor")).expect("create cursor dir"); + + let payload = run_ok_json( + home.path(), + home.path(), + &["agent", "status", "--format", "json"], + ); + let agents = payload["agents"].as_array().expect("agents array"); + assert_eq!(agents.len(), 3); + + let claude = agents + .iter() + .find(|entry| entry["client"] == "claude-code") + .expect("claude-code entry"); + assert_eq!(claude["detected"], true); + assert_eq!(claude["config_exists"], true); + assert_eq!(claude["registered"], true); + + let cursor = agents + .iter() + .find(|entry| entry["client"] == "cursor") + .expect("cursor entry"); + assert_eq!(cursor["detected"], true); + assert_eq!(cursor["config_exists"], false); + assert_eq!(cursor["registered"], false); + + let codex = agents + .iter() + .find(|entry| entry["client"] == "codex") + .expect("codex entry"); + assert_eq!(codex["detected"], false); + assert_eq!(codex["config_exists"], false); + assert_eq!(codex["registered"], false); + + let text = run_ok_stdout(home.path(), home.path(), &["agent", "status"]); + assert!(text.contains("claude-code (Claude Code): detected, registered")); + assert!(text.contains("cursor (Cursor): detected, not registered")); + assert!(text.contains("codex (Codex): not detected, not registered")); + + let toon = run_ok_stdout( + home.path(), + home.path(), + &["agent", "status", "--format", "toon"], + ); + assert!(toon.contains("claude-code")); + assert!(toon.contains("cursor")); + assert!(toon.contains("codex")); +} + +#[test] +fn agent_install_dry_run_previews_exact_changes_without_writing_to_disk() { + let home = TempDir::new().expect("create temp home"); + let (claude_initial, codex_initial) = seed_three_detected_agents(home.path()); + + let payload = run_ok_json( + home.path(), + home.path(), + &["agent", "install", "--dry-run", "--format", "json"], + ); + assert_eq!(payload["dry_run"], true); + let results = payload["results"].as_array().expect("results array"); + assert_eq!(results.len(), 3); + for entry in results { + assert_eq!(entry["written"], false); + assert!(entry["preview"].as_str().is_some()); + } + + assert_eq!(results[0]["action"], "update"); + let claude_preview: Value = + serde_json::from_str(results[0]["preview"].as_str().expect("claude preview")) + .expect("valid claude JSON preview"); + assert_claude_preserved(&claude_preview); + + assert_eq!(results[1]["action"], "create"); + let cursor_preview: Value = + serde_json::from_str(results[1]["preview"].as_str().expect("cursor preview")) + .expect("valid cursor JSON preview"); + assert_eq!( + cursor_preview["mcpServers"]["codeint"], + json!({"command": "codeint", "args": ["mcp"]}) + ); + + assert_eq!(results[2]["action"], "update"); + let codex_preview = results[2]["preview"].as_str().expect("codex preview"); + assert!(codex_preview.contains("model = \"gpt-5\"")); + assert!(codex_preview.contains("[mcp_servers.memory]")); + assert!(codex_preview.contains("[mcp_servers.codeint]")); + + assert_eq!( + fs::read_to_string(home.path().join(".claude.json")).expect("read claude"), + claude_initial + ); + assert!(!home.path().join(".cursor/mcp.json").exists()); + assert_eq!( + fs::read_to_string(home.path().join(".codex/config.toml")).expect("read codex"), + codex_initial + ); + assert_clean_temp_files(home.path()); + + let text = run_ok_stdout(home.path(), home.path(), &["agent", "install", "--dry-run"]); + assert!(text.contains("mode: dry-run (no files modified)")); + assert!(text.contains("would update")); + assert!(text.contains("would create")); +} + +#[test] +fn agent_install_updates_atomically_preserves_settings_and_is_idempotent() { + let home = TempDir::new().expect("create temp home"); + seed_three_detected_agents(home.path()); + + let first = run_ok_json( + home.path(), + home.path(), + &["agent", "install", "--format", "json"], + ); + assert_eq!(first["dry_run"], false); + let first_results = first["results"].as_array().expect("results"); + assert_eq!(first_results.len(), 3); + assert_eq!(first_results[0]["action"], "update"); + assert_eq!(first_results[0]["written"], true); + assert_eq!(first_results[1]["action"], "create"); + assert_eq!(first_results[1]["written"], true); + assert_eq!(first_results[2]["action"], "update"); + assert_eq!(first_results[2]["written"], true); + + let claude_after_first = + fs::read_to_string(home.path().join(".claude.json")).expect("read claude"); + let cursor_after_first = + fs::read_to_string(home.path().join(".cursor/mcp.json")).expect("read cursor"); + let codex_after_first = + fs::read_to_string(home.path().join(".codex/config.toml")).expect("read codex"); + + let claude_json: Value = serde_json::from_str(&claude_after_first).expect("parse claude"); + assert_claude_preserved(&claude_json); + + let cursor_json: Value = serde_json::from_str(&cursor_after_first).expect("parse cursor"); + assert_eq!( + cursor_json["mcpServers"]["codeint"], + json!({"command": "codeint", "args": ["mcp"]}) + ); + + assert!(codex_after_first.contains("model = \"gpt-5\"")); + assert!(codex_after_first.contains("[mcp_servers.memory]")); + assert!(codex_after_first.contains("[mcp_servers.codeint]")); + assert!(codex_after_first.contains("command = \"codeint\"")); + assert_clean_temp_files(home.path()); + + let second = run_ok_json( + home.path(), + home.path(), + &["agent", "install", "--format", "json"], + ); + for entry in second["results"].as_array().expect("second results") { + assert_eq!(entry["action"], "unchanged"); + assert_eq!(entry["written"], false); + assert!(entry.get("preview").is_none()); + } + assert_eq!( + fs::read_to_string(home.path().join(".claude.json")).expect("re-read claude"), + claude_after_first + ); + assert_eq!( + fs::read_to_string(home.path().join(".cursor/mcp.json")).expect("re-read cursor"), + cursor_after_first + ); + assert_eq!( + fs::read_to_string(home.path().join(".codex/config.toml")).expect("re-read codex"), + codex_after_first + ); + + let status = run_ok_json( + home.path(), + home.path(), + &["agent", "status", "--format", "json"], + ); + for entry in status["agents"].as_array().expect("status agents") { + assert_eq!(entry["detected"], true); + assert_eq!(entry["config_exists"], true); + assert_eq!(entry["registered"], true); + } +} + +#[test] +fn agent_install_client_targets_single_agent_and_config_root_flag_overrides_env() { + let env_home = TempDir::new().expect("create env home"); + let flag_home = TempDir::new().expect("create flag home"); + + let empty = run_ok_json( + flag_home.path(), + env_home.path(), + &["agent", "install", "--format", "json"], + ); + assert_eq!(empty["results"], json!([])); + assert!( + empty["note"] + .as_str() + .unwrap_or_default() + .contains("--client") + ); + + let flag_root = flag_home.path().to_str().expect("utf8 path"); + let toon = run_ok_stdout( + flag_home.path(), + env_home.path(), + &[ + "agent", + "install", + "--client", + "codex", + "--config-root", + flag_root, + "--format", + "toon", + ], + ); + assert!(toon.contains("codex")); + assert!(toon.contains("create")); + + assert!(flag_home.path().join(".codex/config.toml").is_file()); + assert!(!flag_home.path().join(".claude.json").exists()); + assert!(!flag_home.path().join(".cursor/mcp.json").exists()); + assert!(!env_home.path().join(".codex/config.toml").exists()); + + let status = run_ok_json( + flag_home.path(), + env_home.path(), + &[ + "agent", + "status", + "--client", + "codex", + "--config-root", + flag_root, + "--format", + "json", + ], + ); + let agents = status["agents"].as_array().expect("agents"); + assert_eq!(agents.len(), 1); + assert_eq!(agents[0]["client"], "codex"); + assert_eq!(agents[0]["detected"], true); + assert_eq!(agents[0]["registered"], true); +} + +#[test] +fn agent_rejects_malformed_or_invalid_config_without_modifying_files() { + let home = TempDir::new().expect("create temp home"); + write_file(home.path(), ".claude.json", "{ broken json"); + write_file( + home.path(), + ".cursor/mcp.json", + "{\"mcpServers\": \"not-an-object\"}", + ); + write_file(home.path(), ".codex/config.toml", "[mcp_servers\nbroken"); + + let bad_json = run_agent_cli( + home.path(), + home.path(), + &["agent", "install", "--client", "claude-code"], + ); + assert_eq!(bad_json.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&bad_json.stderr).contains("not valid JSON")); + assert_eq!( + fs::read_to_string(home.path().join(".claude.json")).expect("read claude"), + "{ broken json" + ); + + let bad_section = run_agent_cli( + home.path(), + home.path(), + &["agent", "install", "--client", "cursor"], + ); + assert_eq!(bad_section.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&bad_section.stderr).contains("mcpServers")); + assert_eq!( + fs::read_to_string(home.path().join(".cursor/mcp.json")).expect("read cursor"), + "{\"mcpServers\": \"not-an-object\"}" + ); + + let bad_toml = run_agent_cli( + home.path(), + home.path(), + &["agent", "status", "--client", "codex"], + ); + assert_eq!(bad_toml.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&bad_toml.stderr).contains("not valid TOML")); +} diff --git a/crates/config/src/agent_home.rs b/crates/config/src/agent_home.rs new file mode 100644 index 0000000..e5c5638 --- /dev/null +++ b/crates/config/src/agent_home.rs @@ -0,0 +1,37 @@ +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +#[cfg(test)] +mod tests; + +pub(crate) const AGENT_HOME_VARIABLE: &str = "CODEINT_AGENT_HOME"; + +pub(crate) fn resolve_agent_home( + current_folder: &Path, + explicit: Option<&Path>, + is_windows: bool, + read_env: F, +) -> Option +where + F: Fn(&'static str) -> Option, +{ + if let Some(override_dir) = explicit { + return Some(current_folder.join(override_dir)); + } + if let Some(configured) = non_empty_var(&read_env, AGENT_HOME_VARIABLE) { + return Some(current_folder.join(configured)); + } + let fallback = if is_windows { + non_empty_var(&read_env, "USERPROFILE").or_else(|| non_empty_var(&read_env, "HOME")) + } else { + non_empty_var(&read_env, "HOME") + }; + fallback.map(PathBuf::from) +} + +fn non_empty_var(read_env: &F, key: &'static str) -> Option +where + F: Fn(&'static str) -> Option, +{ + read_env(key).filter(|val| !val.is_empty()) +} diff --git a/crates/config/src/agent_home/tests.rs b/crates/config/src/agent_home/tests.rs new file mode 100644 index 0000000..8b7b729 --- /dev/null +++ b/crates/config/src/agent_home/tests.rs @@ -0,0 +1,66 @@ +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +use super::{AGENT_HOME_VARIABLE, resolve_agent_home}; + +fn env_from<'a>( + entries: &'a [(&'a str, &'a str)], +) -> impl Fn(&'static str) -> Option + 'a { + move |name| { + entries + .iter() + .find(|(key, _)| *key == name) + .map(|(_, value)| OsString::from(value)) + } +} + +#[test] +fn explicit_config_root_wins_over_env_and_home() { + let cwd = Path::new("/work/repo"); + let resolved = resolve_agent_home( + cwd, + Some(Path::new("isolated-home")), + false, + env_from(&[(AGENT_HOME_VARIABLE, "/env/home"), ("HOME", "/real/home")]), + ); + assert_eq!(resolved, Some(PathBuf::from("/work/repo/isolated-home"))); +} + +#[test] +fn agent_home_env_var_wins_over_platform_home() { + let cwd = Path::new("/work/repo"); + let resolved = resolve_agent_home( + cwd, + None, + false, + env_from(&[(AGENT_HOME_VARIABLE, ".agent-home"), ("HOME", "/real/home")]), + ); + assert_eq!(resolved, Some(PathBuf::from("/work/repo/.agent-home"))); +} + +#[test] +fn falls_back_to_platform_home_when_override_is_unset_or_empty() { + let cwd = Path::new("/work/repo"); + let unix = resolve_agent_home( + cwd, + None, + false, + env_from(&[(AGENT_HOME_VARIABLE, ""), ("HOME", "/Users/dev")]), + ); + assert_eq!(unix, Some(PathBuf::from("/Users/dev"))); + + let windows = resolve_agent_home( + cwd, + None, + true, + env_from(&[("USERPROFILE", "C:\\Users\\dev")]), + ); + assert_eq!(windows, Some(PathBuf::from("C:\\Users\\dev"))); +} + +#[test] +fn returns_none_when_no_home_source_is_present() { + let cwd = Path::new("/work/repo"); + let resolved = resolve_agent_home(cwd, None, false, env_from(&[])); + assert_eq!(resolved, None); +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 642a0b3..688ce61 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -4,6 +4,7 @@ use std::path::{Path, PathBuf}; use clap::{Parser, Subcommand}; +mod agent_home; mod boundaries; mod calendar_day; mod codeint_json; @@ -67,6 +68,8 @@ pub enum ConfigError { folder.display() )] MissingOutputFolder { path: PathBuf, folder: PathBuf }, + #[error("cannot determine the home folder for agent configuration")] + MissingAgentHome, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -105,6 +108,59 @@ pub enum GuardFormat { Json, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] +pub enum AgentFormat { + Text, + Toon, + Json, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] +pub enum AgentClient { + ClaudeCode, + Cursor, + Codex, +} + +impl AgentClient { + pub const ALL: [AgentClient; 3] = [ + AgentClient::ClaudeCode, + AgentClient::Cursor, + AgentClient::Codex, + ]; + + pub fn as_str(self) -> &'static str { + match self { + AgentClient::ClaudeCode => "claude-code", + AgentClient::Cursor => "cursor", + AgentClient::Codex => "codex", + } + } + + pub fn display_name(self) -> &'static str { + match self { + AgentClient::ClaudeCode => "Claude Code", + AgentClient::Cursor => "Cursor", + AgentClient::Codex => "Codex", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AgentCommand { + Status { + config_root: PathBuf, + client: Option, + format: AgentFormat, + }, + Install { + config_root: PathBuf, + client: Option, + dry_run: bool, + format: AgentFormat, + }, +} + const LATEST_COMMITS_OF_A_TREND: usize = 20; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -158,6 +214,7 @@ pub enum Command { target: PathBuf, format: GuardFormat, }, + Agent(AgentCommand), } #[derive(Debug)] @@ -268,6 +325,62 @@ enum CommandArguments { )] format: GuardFormat, }, + #[command(about = "Inspect and configure codeint MCP integration for local coding agents")] + Agent { + #[command(subcommand)] + command: AgentSubcommandArguments, + }, +} + +#[derive(Debug, Subcommand)] +enum AgentSubcommandArguments { + #[command( + about = "Report detected local coding agents and whether codeint mcp is registered for each" + )] + Status { + #[arg(long, value_enum, help = "Inspect only this coding agent")] + client: Option, + #[arg( + long, + value_enum, + default_value_t = AgentFormat::Text, + help = "The format of the output" + )] + format: AgentFormat, + #[arg( + long, + value_name = "DIR", + help = "Override the home folder containing agent configuration files" + )] + config_root: Option, + }, + #[command(about = "Register codeint mcp in supported local coding agent configuration files")] + Install { + #[arg( + long, + help = "Preview exact configuration changes without modifying any files" + )] + dry_run: bool, + #[arg( + long, + value_enum, + help = "Configure only this coding agent instead of all detected ones" + )] + client: Option, + #[arg( + long, + value_enum, + default_value_t = AgentFormat::Text, + help = "The format of the output" + )] + format: AgentFormat, + #[arg( + long, + value_name = "DIR", + help = "Override the home folder containing agent configuration files" + )] + config_root: Option, + }, } #[derive(Debug, clap::Args)] @@ -328,9 +441,46 @@ fn build_command( target: path, format, }), + CommandArguments::Agent { command } => build_agent_command(current_folder, command), + } +} + +fn build_agent_command( + current_folder: &Path, + arguments: AgentSubcommandArguments, +) -> Result { + match arguments { + AgentSubcommandArguments::Status { + client, + format, + config_root, + } => Ok(Command::Agent(AgentCommand::Status { + config_root: agent_home_of_this_process(current_folder, config_root.as_deref())?, + client, + format, + })), + AgentSubcommandArguments::Install { + dry_run, + client, + format, + config_root, + } => Ok(Command::Agent(AgentCommand::Install { + config_root: agent_home_of_this_process(current_folder, config_root.as_deref())?, + client, + dry_run, + format, + })), } } +fn agent_home_of_this_process( + current_folder: &Path, + explicit: Option<&Path>, +) -> Result { + agent_home::resolve_agent_home(current_folder, explicit, cfg!(windows), std::env::var_os) + .ok_or(ConfigError::MissingAgentHome) +} + fn build_trend_command( current_folder: &Path, since: Option, diff --git a/crates/report/src/agent.rs b/crates/report/src/agent.rs new file mode 100644 index 0000000..04f5903 --- /dev/null +++ b/crates/report/src/agent.rs @@ -0,0 +1,132 @@ +use std::fmt::Write as _; + +use codeint_config::AgentFormat; +use serde::Serialize; + +use crate::ReportError; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AgentStatusReport { + pub config_root: String, + pub agents: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AgentStatusEntry { + pub client: &'static str, + pub name: &'static str, + pub config_path: String, + pub detected: bool, + pub config_exists: bool, + pub registered: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum AgentInstallAction { + Create, + Update, + Unchanged, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AgentInstallReport { + pub config_root: String, + pub dry_run: bool, + pub results: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub note: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AgentInstallEntry { + pub client: &'static str, + pub name: &'static str, + pub config_path: String, + pub action: AgentInstallAction, + pub written: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub preview: Option, +} + +impl AgentStatusReport { + pub fn render(&self, format: AgentFormat) -> Result { + render_agent_report(format, self, format_status_text) + } +} + +impl AgentInstallReport { + pub fn render(&self, format: AgentFormat) -> Result { + render_agent_report(format, self, format_install_text) + } +} + +fn render_agent_report( + format: AgentFormat, + report: &T, + to_text: fn(&T) -> String, +) -> Result { + match format { + AgentFormat::Json => serde_json::to_string_pretty(report).map_err(ReportError::Json), + AgentFormat::Toon => toon_format::encode_default(report).map_err(ReportError::Toon), + AgentFormat::Text => Ok(to_text(report)), + } +} + +fn format_status_text(report: &AgentStatusReport) -> String { + let mut lines = vec![format!("config_root: {}", report.config_root)]; + for entry in &report.agents { + let detection = if entry.detected { + "detected" + } else { + "not detected" + }; + let registration = if entry.registered { + "registered" + } else { + "not registered" + }; + lines.push(format!( + "{} ({}): {}, {} ({})", + entry.client, entry.name, detection, registration, entry.config_path + )); + } + lines.join("\n") +} + +fn format_install_text(report: &AgentInstallReport) -> String { + let mut buf = String::new(); + let mode = if report.dry_run { + "dry-run (no files modified)" + } else { + "apply" + }; + let _ = writeln!(buf, "mode: {mode}\nconfig_root: {}", report.config_root); + for entry in &report.results { + let verb = install_action_label(entry.action, report.dry_run); + let _ = writeln!( + buf, + "{} ({}): {} ({})", + entry.client, entry.name, verb, entry.config_path + ); + if let Some(preview) = &entry.preview { + for preview_line in preview.lines() { + let _ = writeln!(buf, " {preview_line}"); + } + } + } + if let Some(note) = &report.note { + let _ = writeln!(buf, "note: {note}"); + } + buf.trim_end_matches('\n').to_owned() +} + +fn install_action_label(action: AgentInstallAction, dry_run: bool) -> &'static str { + match (action, dry_run) { + (AgentInstallAction::Create, true) => "would create", + (AgentInstallAction::Create, false) => "created", + (AgentInstallAction::Update, true) => "would update", + (AgentInstallAction::Update, false) => "updated", + (AgentInstallAction::Unchanged, _) => "unchanged (already registered)", + } +} diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index ec6083c..04a2f45 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -18,6 +18,7 @@ use codeint_model::{ use serde::ser::SerializeMap; use serde::{Deserialize, Serialize, Serializer}; +mod agent; mod diff; mod guard; mod markdown; @@ -27,6 +28,9 @@ mod sarif; mod tests; mod trend; +pub use agent::{ + AgentInstallAction, AgentInstallEntry, AgentInstallReport, AgentStatusEntry, AgentStatusReport, +}; pub use diff::{BaseCommit, DiffReport, Head, HeadCommit}; pub use guard::{GuardAllowedTarget, GuardDeniedTarget, GuardReport}; pub use measurement::CommitMeasurement; diff --git a/docs/reference.md b/docs/reference.md index 92e93a0..9aa546a 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -30,6 +30,7 @@ The working tree adds `src/route.ts`, an eroded function that is not committed. | `update` | Update a standalone codeint binary in place from GitHub Releases; see [`codeint update`](#codeint-update) | | `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, `trend`, and `guard` tools; see [`codeint mcp`](#codeint-mcp) | | `guard` | Show the architectural boundary zone, allowed and denied target zones, `public_files` constraints, and allowed importers for a file path; see [`codeint guard`](#codeint-guard) | +| `agent` | Inspect and configure codeint MCP integration for local coding agents; see [`codeint agent`](#codeint-agent) | | `help` | Print the help of codeint, or of the command that follows it | | Option | Meaning | @@ -514,6 +515,31 @@ codeint guard src/route.ts --format toon codeint guard src/route.ts --format json ``` +### `codeint agent` + +| Command | Meaning | +| ------- | ------- | +| `status` | Report detected local coding agents and whether `codeint mcp` is registered for each | +| `install` | Register `codeint mcp` in supported local coding agent configuration files | +| `help` | Print the help of `codeint agent`, or of the subcommand that follows it | + +| Option | Meaning | +| ------ | ------- | +| `-h, --help` | Print the help of `codeint agent` | + +`codeint agent` manages local `codeint mcp` registration for Claude Code (`claude-code`, `.claude.json`), Cursor (`cursor`, `.cursor/mcp.json`), and Codex (`codex`, `.codex/config.toml`). +Both `status` and `install` accept `--client `, `--format `, and `--config-root ` (or the `CODEINT_AGENT_HOME` environment variable) to override the home folder. +`codeint agent install` also accepts `--dry-run` to preview the exact resulting configuration without modifying any file on disk. +When writing a configuration file, `codeint agent install` preserves unrelated keys and existing MCP servers, writes atomically via a temporary file rename, and leaves already-registered configurations untouched on repeated runs. + +```sh exit=0 +CODEINT_AGENT_HOME=.agent-home codeint agent status +CODEINT_AGENT_HOME=.agent-home codeint agent status --format json +CODEINT_AGENT_HOME=.agent-home codeint agent status --format toon +CODEINT_AGENT_HOME=.agent-home codeint agent install --dry-run --client claude-code +codeint agent help +``` + ## Exit codes | Exit code | Meaning | From 4a4e22357ddb1d58201891cd35499c98cebac71a Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 12:40:52 +0800 Subject: [PATCH 6/6] fix(cli): resolve Tier 3 interrogate findings on Spec #172 --- crates/cli/src/agent.rs | 144 ++++++++++++++---- crates/cli/src/config.rs | 47 +++++- crates/cli/src/doctor.rs | 78 ++++++++-- crates/cli/src/lib.rs | 4 +- crates/cli/src/remedy.rs | 11 +- crates/cli/tests/agent.rs | 194 +++++++++++++++++++++++++ crates/cli/tests/config.rs | 170 ++++++++++++++++++++++ crates/cli/tests/doctor.rs | 64 +++++++- crates/cli/tests/report.rs | 81 +++++++++++ crates/cli/tests/schema.rs | 10 ++ crates/config/src/codeint_json.rs | 137 ++++++++++++----- crates/config/src/config_error.rs | 36 ++++- crates/config/src/lib.rs | 2 +- crates/config/src/regression_limits.rs | 11 +- crates/config/src/resolved.rs | 8 +- crates/report/src/diff.rs | 2 +- crates/report/src/diff/markdown.rs | 2 +- crates/report/src/diff/tests.rs | 11 ++ crates/report/src/markdown.rs | 6 +- 19 files changed, 917 insertions(+), 101 deletions(-) diff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rs index 37c4bfd..100108c 100644 --- a/crates/cli/src/agent.rs +++ b/crates/cli/src/agent.rs @@ -1,5 +1,7 @@ use std::fs::{self, OpenOptions}; use std::io::Write; +#[cfg(unix)] +use std::os::unix::fs::OpenOptionsExt; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -64,6 +66,8 @@ pub(crate) enum AgentError { path.display() )] InvalidCodeintEntry { path: PathBuf, key: &'static str }, + #[error("agent configuration file {} is a dangling symlink", path.display())] + DanglingSymlink { path: PathBuf }, #[error("cannot create folder {}", path.display())] CreateDir { path: PathBuf, @@ -92,10 +96,16 @@ enum MergeOutcome { struct PlannedUpdate { client: AgentClient, config_path: PathBuf, + write_path: PathBuf, action: AgentInstallAction, content: Option, } +enum ConfigTarget { + Missing { write_path: PathBuf }, + Existing { write_path: PathBuf }, +} + trait ConfigDocument: Sized { const MCP_KEY: &'static str; @@ -260,9 +270,12 @@ pub(crate) fn install( ), }); } - let mut results = Vec::with_capacity(targets.len()); + let mut plans = Vec::with_capacity(targets.len()); for client in targets { - let plan = plan_client_update(config_root, client)?; + plans.push(plan_client_update(config_root, client)?); + } + let mut results = Vec::with_capacity(plans.len()); + for plan in plans { results.push(apply_or_preview(plan, dry_run)?); } Ok(AgentInstallReport { @@ -287,7 +300,7 @@ fn apply_or_preview(plan: PlannedUpdate, dry_run: bool) -> Result Result Result { let config_path = client_config_path(config_root, client); let detected = is_client_detected(config_root, client); - let config_exists = config_path.is_file(); - let registered = if config_exists { - let raw = read_config_file(&config_path)?; - match client_format(client) { - ConfigFormat::Json => { - is_registered_in_doc::>(&config_path, &raw)? - } - ConfigFormat::Toml => is_registered_in_doc::(&config_path, &raw)?, + let (config_exists, registered) = match resolve_config_target(&config_path)? { + ConfigTarget::Missing { .. } => (false, false), + ConfigTarget::Existing { write_path } => { + let raw = read_config_file(&write_path)?; + let registered = match client_format(client) { + ConfigFormat::Json => { + is_registered_in_doc::>(&config_path, &raw)? + } + ConfigFormat::Toml => is_registered_in_doc::(&config_path, &raw)?, + }; + (true, registered) } - } else { - false }; Ok(AgentStatusEntry { client: client.as_str(), @@ -332,11 +346,12 @@ fn plan_client_update( client: AgentClient, ) -> Result { let config_path = client_config_path(config_root, client); - let existed = config_path.is_file(); - let existing = if existed { - Some(read_config_file(&config_path)?) - } else { - None + let (existed, write_path, existing) = match resolve_config_target(&config_path)? { + ConfigTarget::Missing { write_path } => (false, write_path, None), + ConfigTarget::Existing { write_path } => { + let raw = read_config_file(&write_path)?; + (true, write_path, Some(raw)) + } }; let merge = match client_format(client) { ConfigFormat::Json => { @@ -358,6 +373,7 @@ fn plan_client_update( Ok(PlannedUpdate { client, config_path, + write_path, action, content, }) @@ -381,7 +397,13 @@ fn doc_has_codeint_mcp(path: &Path, root: &D) -> Result PathBuf { fn is_client_detected(config_root: &Path, client: AgentClient) -> bool { match client { AgentClient::ClaudeCode => { - config_root.join(".claude.json").is_file() || config_root.join(".claude").is_dir() + config_entry_present(&config_root.join(".claude.json")) + || config_root.join(".claude").is_dir() } AgentClient::Cursor => { config_root.join(".cursor").is_dir() - || config_root.join(".cursor").join("mcp.json").is_file() + || config_entry_present(&config_root.join(".cursor").join("mcp.json")) } AgentClient::Codex => { config_root.join(".codex").is_dir() - || config_root.join(".codex").join("config.toml").is_file() + || config_entry_present(&config_root.join(".codex").join("config.toml")) } } } +fn config_entry_present(path: &Path) -> bool { + path.is_file() || fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink()) +} + +fn resolve_config_target(path: &Path) -> Result { + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return Ok(ConfigTarget::Missing { + write_path: path.to_path_buf(), + }); + } + Err(source) => { + return Err(AgentError::Read { + path: path.to_path_buf(), + source, + }); + } + }; + if !metadata.file_type().is_symlink() { + return Ok(ConfigTarget::Existing { + write_path: path.to_path_buf(), + }); + } + resolve_symlink_target(path) +} + +fn resolve_symlink_target(path: &Path) -> Result { + match fs::metadata(path) { + Ok(_) => { + let write_path = fs::canonicalize(path).map_err(|source| AgentError::Read { + path: path.to_path_buf(), + source, + })?; + Ok(ConfigTarget::Existing { write_path }) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + Err(AgentError::DanglingSymlink { + path: path.to_path_buf(), + }) + } + Err(source) => Err(AgentError::Read { + path: path.to_path_buf(), + source, + }), + } +} + fn client_format(client: AgentClient) -> ConfigFormat { match client { AgentClient::ClaudeCode | AgentClient::Cursor => ConfigFormat::Json, @@ -458,9 +529,13 @@ fn atomic_write(target: &Path, bytes: &[u8]) -> Result<(), AgentError> { path: parent.to_path_buf(), source, })?; + let existing_permissions = existing_file_permissions(target)?; let (temp_path, mut file) = create_temp_file(parent, target)?; let commit = (|| -> std::io::Result<()> { file.write_all(bytes)?; + if let Some(permissions) = existing_permissions { + file.set_permissions(permissions)?; + } file.sync_all()?; drop(file); fs::rename(&temp_path, target) @@ -475,6 +550,25 @@ fn atomic_write(target: &Path, bytes: &[u8]) -> Result<(), AgentError> { Ok(()) } +fn existing_file_permissions(target: &Path) -> Result, AgentError> { + match fs::metadata(target) { + Ok(metadata) => Ok(Some(metadata.permissions())), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(source) => Err(AgentError::Write { + path: target.to_path_buf(), + source, + }), + } +} + +fn temp_file_open_options() -> OpenOptions { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + options.mode(0o600); + options +} + fn create_temp_file(parent: &Path, target: &Path) -> Result<(PathBuf, fs::File), AgentError> { let base_name = target .file_name() @@ -484,11 +578,7 @@ fn create_temp_file(parent: &Path, target: &Path) -> Result<(PathBuf, fs::File), for _ in 0..64 { let seq = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed); let candidate = parent.join(format!(".{base_name}.codeint-tmp-{pid}-{seq}")); - match OpenOptions::new() - .write(true) - .create_new(true) - .open(&candidate) - { + match temp_file_open_options().open(&candidate) { Ok(file) => return Ok((candidate, file)), Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(source) => { diff --git a/crates/cli/src/config.rs b/crates/cli/src/config.rs index 11861e2..68be716 100644 --- a/crates/cli/src/config.rs +++ b/crates/cli/src/config.rs @@ -1,9 +1,13 @@ use std::path::Path; -use codeint_config::{ConfigOverrides, ConfigurationFileError, read_resolved_configuration}; +use codeint_config::{ + ConfigOverrides, Configuration, ConfigurationFileError, PluginKind, read_resolved_configuration, +}; use codeint_git::{GitError, Repository}; use codeint_report::ConfigReport; +use crate::check::BUILT_IN_LANGUAGE_PLUGINS; + #[derive(Debug, thiserror::Error)] pub(crate) enum ConfigCommandError { #[error(transparent)] @@ -18,5 +22,46 @@ pub(crate) fn resolved_config( ) -> Result { let repository = Repository::discover(folder)?; let resolved = read_resolved_configuration(repository.root(), overrides)?; + validate_resolved_configuration(&resolved.configuration, overrides)?; Ok(ConfigReport::from_resolved(&resolved)) } + +fn validate_resolved_configuration( + configuration: &Configuration, + overrides: &ConfigOverrides, +) -> Result<(), ConfigurationFileError> { + let language_names = known_language_plugin_names(configuration); + configuration.languages.coverage_of(&language_names)?; + let owned_metric_keys = configured_metric_keys(configuration); + let metric_keys: Vec<&str> = owned_metric_keys.iter().map(String::as_str).collect(); + configuration.validate_cli_budget_metrics(&overrides.budgets, &metric_keys)?; + configuration.validate_metrics(&metric_keys)?; + Ok(()) +} + +fn known_language_plugin_names(configuration: &Configuration) -> Vec<&str> { + let mut names: Vec<&str> = BUILT_IN_LANGUAGE_PLUGINS + .iter() + .map(|plugin| plugin.name) + .collect(); + for plugin in &configuration.plugins { + if plugin.kind == PluginKind::Language && !names.contains(&plugin.name.as_str()) { + names.push(plugin.name.as_str()); + } + } + names +} + +fn configured_metric_keys(configuration: &Configuration) -> Vec { + let mut keys = Vec::new(); + for plugin in &configuration.plugins { + if plugin.kind == PluginKind::Metric { + keys.push(plugin.name.clone()); + let snake = plugin.name.replace('-', "_"); + if snake != plugin.name { + keys.push(snake); + } + } + } + keys +} diff --git a/crates/cli/src/doctor.rs b/crates/cli/src/doctor.rs index 5bbbd76..57f6a97 100644 --- a/crates/cli/src/doctor.rs +++ b/crates/cli/src/doctor.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use codeint_config::{ Configuration, ConfigurationInspection, LanguageCoverage, PluginDeclaration, PluginHostConfig, - PluginKind, PluginSource, SchemaVersionStatus, inspect_configuration, + PluginKind, PluginSource, SchemaVersionStatus, inspect_configuration, is_broken_symlink, }; use codeint_git::{GitError, Repository, Snapshot}; use codeint_plugin_host::{sha256, sha256_hex}; @@ -20,7 +20,7 @@ pub(crate) fn doctor(folder: &Path, plugin_host: &PluginHostConfig) -> DoctorRep let (git_check, repository, root) = check_git(folder); checks.push(git_check); - let (config_checks, configuration) = check_configuration(&root); + let (config_checks, configuration, config_missing) = check_configuration(&root); checks.extend(config_checks); if let Some(repository) = &repository { @@ -32,7 +32,7 @@ pub(crate) fn doctor(folder: &Path, plugin_host: &PluginHostConfig) -> DoctorRep if let Some(configuration) = &configuration { checks.extend(check_plugins(&root, configuration, plugin_host)); - } else if repository.is_some() && !root.join("codeint.json").exists() { + } else if repository.is_some() && config_missing { checks.push(DoctorCheck::pass( "plugins", "No external Wasm Plugins configured", @@ -71,13 +71,13 @@ fn check_git(folder: &Path) -> (DoctorCheck, Option, PathBuf) { } } -fn check_configuration(root: &Path) -> (Vec, Option) { +fn check_configuration(root: &Path) -> (Vec, Option, bool) { match inspect_configuration(root) { ConfigurationInspection::Missing { .. } => { let check = DoctorCheck::warn("config", "No codeint.json found; using built-in defaults") .with_remedy("Run codeint init to write a starter codeint.json."); - (vec![check], None) + (vec![check], None, true) } ConfigurationInspection::Valid { schema, @@ -85,7 +85,7 @@ fn check_configuration(root: &Path) -> (Vec, Option) .. } => { let checks = valid_configuration_checks(&schema, &configuration); - (checks, Some(*configuration)) + (checks, Some(*configuration), false) } ConfigurationInspection::Invalid { schema, error, .. } => { let config_check = DoctorCheck::error("config", describe(&error)) @@ -94,7 +94,7 @@ fn check_configuration(root: &Path) -> (Vec, Option) if let Some(schema_status) = schema { checks.push(schema_check(&schema_status)); } - (checks, None) + (checks, None, false) } } } @@ -353,15 +353,9 @@ fn check_remote_plugin( .as_ref() .map(|dir| dir.join(format!("{expected}.wasm"))); if let Some(path) = cached_path - && path.exists() + && let Some(check) = inspect_cached_plugin(&id, declaration, url, &path, &expected) { - return verify_plugin_file( - id, - &declaration.name, - &path, - &expected, - &format!("cached from {url}"), - ); + return check; } DoctorCheck::warn( id, @@ -376,6 +370,51 @@ fn check_remote_plugin( .with_remedy("Run codeint check to download and verify this plugin into the local cache.") } +fn inspect_cached_plugin( + id: &str, + declaration: &PluginDeclaration, + url: &str, + path: &Path, + expected: &str, +) -> Option { + match std::fs::symlink_metadata(path) { + Ok(_) if is_broken_symlink(path) => Some( + DoctorCheck::error( + id.to_owned(), + format!( + "Cached external Wasm Plugin {:?} at {} is a broken symlink", + declaration.name, + path.display() + ), + ) + .with_remedy( + "Remove the broken symlink in the plugin cache directory, then run codeint check to re-download the plugin.", + ), + ), + Ok(_) => Some(verify_plugin_file( + id.to_owned(), + &declaration.name, + path, + expected, + &format!("cached from {url}"), + )), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => Some( + DoctorCheck::error( + id.to_owned(), + format!( + "Cannot inspect cached external Wasm Plugin {:?} at {}: {error}", + declaration.name, + path.display() + ), + ) + .with_remedy( + "Check permissions on the plugin cache directory, or set CODEINT_CACHE_DIR to a readable folder.", + ), + ), + } +} + fn verify_plugin_file( id: String, name: &str, @@ -383,6 +422,15 @@ fn verify_plugin_file( expected_hex: &str, label: &str, ) -> DoctorCheck { + if is_broken_symlink(resolved_path) { + return DoctorCheck::error( + id, + format!("External Wasm Plugin {name:?} at {label} is a broken symlink"), + ) + .with_remedy( + "Point the plugin symlink to an existing WebAssembly component file, or fix the path in codeint.json.", + ); + } let bytes = match std::fs::read(resolved_path) { Ok(bytes) => bytes, Err(error) => { diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index c4099bc..3e8b141 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -315,12 +315,12 @@ fn exit_codes() -> Vec { ExitCodeSchema { code: SUCCESS, name: "success", - description: "The run succeeded, and no Budget or Regression failed.", + description: "The run succeeded, and no Budget, Regression, or codeint doctor blocking error failed.", }, ExitCodeSchema { code: BUDGET_OR_REGRESSION_FAILED, name: "budget_or_regression_failed", - description: "The run succeeded, and at least one Budget or Regression failed.", + description: "The run succeeded, and at least one Budget, Regression, or codeint doctor blocking error failed.", }, ExitCodeSchema { code: OPERATIONAL_ERROR, diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 3e75558..17a1ef8 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -110,6 +110,9 @@ fn agent_remedy(error: &AgentError) -> &'static str { E::Read { .. } | E::CreateDir { .. } | E::Write { .. } => { "Check file and folder permissions for the agent configuration path, then retry." } + E::DanglingSymlink { .. } => { + "Point the symlink to an existing configuration file, or remove the dangling symlink and retry." + } E::InvalidJson { .. } | E::ExpectedRootObject { .. } | E::InvalidToml { .. } @@ -257,6 +260,9 @@ fn file_access_remedy(error: &ConfigurationFileError) -> Option<&'static str> { E::Unreadable(_) => Some( "Check that codeint.json is a file you have permission to read, then run codeint again.", ), + E::BrokenSymlink => Some( + "Point the codeint.json symlink to an existing file, or remove the broken symlink and run codeint again.", + ), E::NotJson(_) => Some("Fix the JSON syntax of codeint.json at that line and column."), E::NewerSchemaVersion { .. } => Some( "Run codeint update (or upgrade the codeint npm package) to match or exceed the $schema version, or lower the $schema tag in codeint.json.", @@ -269,6 +275,9 @@ fn json_shape_remedy(error: &ConfigurationFileError) -> Option<&'static str> { use ConfigurationFileError::*; Some(match error { UnknownKey { .. } => "Remove the key, or correct its spelling to one of the allowed keys.", + UnknownCliBudgetMetric { .. } => { + "Pass one of the allowed Metric names to --budget, such as production.erosion=0.25." + } WrongType { .. } => { "Change the value to the expected type; the JSON schema that $schema links to describes every key." } @@ -324,7 +333,7 @@ fn plugin_config_remedy(error: &ConfigurationFileError) -> Option<&'static str> UnknownLanguagePlugin { .. } => { "Name one of the Language plugins listed, or remove the entry from languages." } - InvalidGlob { .. } => { + InvalidGlob { .. } | InvalidCliGlob { .. } => { "Fix the glob: * matches within one folder, ** matches across folders, and {a,b} matches either a or b." } InvalidSha256 { .. } => { diff --git a/crates/cli/tests/agent.rs b/crates/cli/tests/agent.rs index 73e5227..144084e 100644 --- a/crates/cli/tests/agent.rs +++ b/crates/cli/tests/agent.rs @@ -397,3 +397,197 @@ fn agent_rejects_malformed_or_invalid_config_without_modifying_files() { assert_eq!(bad_toml.status.code(), Some(2)); assert!(String::from_utf8_lossy(&bad_toml.stderr).contains("not valid TOML")); } + +#[test] +fn agent_install_validates_all_clients_before_writing_any_file() { + let home = TempDir::new().expect("create temp home"); + let claude_initial = serde_json::to_string_pretty(&json!({ + "theme": "dark", + "mcpServers": {} + })) + .expect("serialize claude"); + write_file(home.path(), ".claude.json", &claude_initial); + write_file(home.path(), ".cursor/mcp.json", "{ broken json"); + + let output = run_agent_cli(home.path(), home.path(), &["agent", "install"]); + assert_eq!(output.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&output.stderr).contains("not valid JSON")); + assert_eq!( + fs::read_to_string(home.path().join(".claude.json")).expect("read claude"), + claude_initial + ); + assert_eq!( + fs::read_to_string(home.path().join(".cursor/mcp.json")).expect("read cursor"), + "{ broken json" + ); + assert_clean_temp_files(home.path()); +} + +#[test] +fn agent_status_and_install_both_reject_non_object_codeint_entry() { + let home = TempDir::new().expect("create temp home"); + write_file( + home.path(), + ".claude.json", + r#"{"mcpServers":{"codeint":"not-an-object"}}"#, + ); + write_file( + home.path(), + ".codex/config.toml", + "[mcp_servers]\ncodeint = \"not-an-object\"\n", + ); + + for (subcommand, client) in [ + ("status", "claude-code"), + ("install", "claude-code"), + ("status", "codex"), + ("install", "codex"), + ] { + let output = run_agent_cli( + home.path(), + home.path(), + &["agent", subcommand, "--client", client], + ); + assert_eq!( + output.status.code(), + Some(2), + "expected exit 2 for agent {subcommand} --client {client}" + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("non-object codeint"), + "unexpected stderr for {subcommand}/{client}: {stderr}" + ); + } +} + +#[cfg(unix)] +#[test] +fn agent_install_preserves_existing_file_permissions_and_creates_private_new_files() { + use std::os::unix::fs::PermissionsExt; + + let home = TempDir::new().expect("create temp home"); + seed_three_detected_agents(home.path()); + + let claude_path = home.path().join(".claude.json"); + let codex_path = home.path().join(".codex/config.toml"); + let cursor_path = home.path().join(".cursor/mcp.json"); + + fs::set_permissions(&claude_path, fs::Permissions::from_mode(0o600)).expect("chmod claude"); + fs::set_permissions(&codex_path, fs::Permissions::from_mode(0o640)).expect("chmod codex"); + + run_ok_json( + home.path(), + home.path(), + &["agent", "install", "--format", "json"], + ); + + let claude_mode = fs::metadata(&claude_path) + .expect("stat claude") + .permissions() + .mode() + & 0o777; + let codex_mode = fs::metadata(&codex_path) + .expect("stat codex") + .permissions() + .mode() + & 0o777; + let cursor_mode = fs::metadata(&cursor_path) + .expect("stat cursor") + .permissions() + .mode() + & 0o777; + + assert_eq!(claude_mode, 0o600); + assert_eq!(codex_mode, 0o640); + assert_eq!(cursor_mode, 0o600); +} + +#[cfg(unix)] +#[test] +fn agent_install_and_status_preserve_symlinks_and_reject_dangling_symlinks() { + use std::os::unix::fs::symlink; + + let home = TempDir::new().expect("create temp home"); + let dotfiles = TempDir::new().expect("create dotfiles"); + + let claude_target = dotfiles.path().join("claude.json"); + let cursor_target = dotfiles.path().join("cursor-mcp.json"); + let codex_target = dotfiles.path().join("codex-config.toml"); + + fs::write(&claude_target, r#"{"theme":"dark"}"#).expect("write claude target"); + fs::write(&cursor_target, r#"{"mcpServers":{}}"#).expect("write cursor target"); + fs::write(&codex_target, "model = \"gpt-5\"\n").expect("write codex target"); + + fs::create_dir_all(home.path().join(".cursor")).expect("mkdir .cursor"); + fs::create_dir_all(home.path().join(".codex")).expect("mkdir .codex"); + + let claude_link = home.path().join(".claude.json"); + let cursor_link = home.path().join(".cursor/mcp.json"); + let codex_link = home.path().join(".codex/config.toml"); + + symlink(&claude_target, &claude_link).expect("symlink claude"); + symlink(&cursor_target, &cursor_link).expect("symlink cursor"); + symlink(&codex_target, &codex_link).expect("symlink codex"); + + run_ok_json( + home.path(), + home.path(), + &["agent", "install", "--format", "json"], + ); + + for link in [&claude_link, &cursor_link, &codex_link] { + assert!( + fs::symlink_metadata(link) + .expect("lstat link") + .file_type() + .is_symlink(), + "{} must remain a symlink", + link.display() + ); + } + + let claude_doc: Value = + serde_json::from_str(&fs::read_to_string(&claude_target).expect("read claude target")) + .expect("parse claude target"); + assert_eq!(claude_doc["theme"], "dark"); + assert_eq!( + claude_doc["mcpServers"]["codeint"], + json!({"command": "codeint", "args": ["mcp"]}) + ); + let cursor_doc: Value = + serde_json::from_str(&fs::read_to_string(&cursor_target).expect("read cursor target")) + .expect("parse cursor target"); + assert_eq!( + cursor_doc["mcpServers"]["codeint"], + json!({"command": "codeint", "args": ["mcp"]}) + ); + let codex_doc = fs::read_to_string(&codex_target).expect("read codex target"); + assert!(codex_doc.contains("[mcp_servers.codeint]")); + + let dangling_home = TempDir::new().expect("create dangling home"); + let dangling_link = dangling_home.path().join(".claude.json"); + symlink(dotfiles.path().join("does-not-exist.json"), &dangling_link) + .expect("create dangling symlink"); + + for subcommand in ["status", "install"] { + let output = run_agent_cli( + dangling_home.path(), + dangling_home.path(), + &["agent", subcommand], + ); + assert_eq!(output.status.code(), Some(2)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("dangling symlink"), + "unexpected stderr for {subcommand}: {stderr}" + ); + } + assert!( + fs::symlink_metadata(&dangling_link) + .expect("lstat dangling link") + .file_type() + .is_symlink() + ); + assert!(!dangling_link.exists()); +} diff --git a/crates/cli/tests/config.rs b/crates/cli/tests/config.rs index 39158c0..4d98fb8 100644 --- a/crates/cli/tests/config.rs +++ b/crates/cli/tests/config.rs @@ -271,3 +271,173 @@ fn config_resolved_accepts_subdirectory_path_argument() { assert_eq!(payload["config_file_present"], true); assert_setting(&payload, "plugin_limits.memory_mb", json!(96), "file"); } + +fn assert_config_rejected( + cwd: &Path, + args: &[&str], + expected_stderr: &str, + forbidden_stderr: Option<&str>, +) { + let output = invoke(cwd, args); + assert_eq!(output.status.code(), Some(2), "args={args:?}"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains(expected_stderr), + "expected {expected_stderr:?} in stderr: {stderr}" + ); + if let Some(forbidden) = forbidden_stderr { + assert!( + !stderr.contains(forbidden), + "did not expect {forbidden:?} in stderr: {stderr}" + ); + } +} + +#[test] +fn config_resolved_tracks_boundary_provenance_normalizes_negative_zero_and_validates_keys() { + let empty_boundaries = init_repo_with_config(Some(json!({ "boundaries": {} }))); + let empty_payload = resolved_json(empty_boundaries.path(), &[]); + assert_setting(&empty_payload, "boundaries.preset", Value::Null, "default"); + assert_setting(&empty_payload, "boundaries.zones", json!({}), "default"); + assert_setting(&empty_payload, "boundaries.rules", json!([]), "default"); + + let zones_only = init_repo_with_config(Some(json!({ + "boundaries": { + "zones": { + "core": { "patterns": ["src/**"] } + } + } + }))); + let zones_payload = resolved_json(zones_only.path(), &[]); + assert_setting( + &zones_payload, + "boundaries.zones", + json!({ "core": { "patterns": ["src/**"] } }), + "file", + ); + assert_setting(&zones_payload, "boundaries.rules", json!([]), "default"); + + let neg_zero_repo = init_repo_with_config(None); + fs::write( + neg_zero_repo.path().join("codeint.json"), + r#"{"budgets":{"production":{"erosion":-0.0}},"regression_limits":{"production":{"erosion":{"ratio_rise":-0.0}}}}"#, + ) + .expect("write negative zero config"); + let neg_stdout = invoke_ok_stdout( + neg_zero_repo.path(), + &[ + "config", + "--resolved", + "--format", + "json", + "--budget", + "production.duplication=-0.0", + ], + ); + assert!( + !neg_stdout.contains("-0.0"), + "unexpected -0.0: {neg_stdout}" + ); + let neg_payload: Value = serde_json::from_str(&neg_stdout).expect("valid json"); + assert_setting( + &neg_payload, + "budgets.production.erosion", + json!(0.0), + "file", + ); + assert_setting( + &neg_payload, + "budgets.production.duplication", + json!(0.0), + "cli", + ); + assert_setting( + &neg_payload, + "regression_limits.production.erosion.ratio_rise", + json!(0.0), + "file", + ); + + let unknown_file_metric = init_repo_with_config(Some(json!({ + "budgets": { "production": { "bogus_metric": 0.2 } } + }))); + assert_config_rejected( + unknown_file_metric.path(), + &["config", "--resolved"], + "bogus_metric", + None, + ); + + let unknown_lang = init_repo_with_config(Some(json!({ + "languages": [{ "plugin": "nonexistent-lang", "include": ["src/**"] }] + }))); + assert_config_rejected( + unknown_lang.path(), + &["config", "--resolved"], + "nonexistent-lang", + None, + ); + + let with_metric_plugin = init_repo_with_config(Some(json!({ + "plugins": [{ + "name": "long-functions", + "kind": "metric", + "path": "plugins/long_functions.wasm", + "sha256": "0000000000000000000000000000000000000000000000000000000000000000" + }], + "budgets": { "production": { "long_functions": 0.25 } } + }))); + let plugin_payload = resolved_json(with_metric_plugin.path(), &[]); + assert_setting( + &plugin_payload, + "budgets.production.long_functions", + json!(0.25), + "file", + ); + + let clean_repo = init_repo_with_config(None); + assert_config_rejected( + clean_repo.path(), + &["config", "--resolved", "--budget", "production.bogus=0.2"], + "--budget", + Some("codeint.json"), + ); + assert_config_rejected( + clean_repo.path(), + &[ + "config", + "--resolved", + "--budget", + "production. erosion =0.2", + ], + "not a valid Metric key", + None, + ); + assert_config_rejected( + clean_repo.path(), + &["config", "--resolved", "--source-set", "test=[unclosed"], + "not a valid glob", + Some("codeint.json"), + ); +} + +#[cfg(unix)] +#[test] +fn config_resolved_reports_broken_symlink_for_codeint_json() { + use std::os::unix::fs::symlink; + + let repo = init_repo_with_config(None); + symlink( + repo.path().join("missing-target.json"), + repo.path().join("codeint.json"), + ) + .expect("create broken codeint.json symlink"); + + let output = invoke(repo.path(), &["config", "--resolved"]); + assert_eq!(output.status.code(), Some(2)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("broken symlink"), + "expected broken symlink error, got: {stderr}" + ); +} diff --git a/crates/cli/tests/doctor.rs b/crates/cli/tests/doctor.rs index 29eee88..dddddcd 100644 --- a/crates/cli/tests/doctor.rs +++ b/crates/cli/tests/doctor.rs @@ -69,6 +69,15 @@ impl DoctorFixture { })); } + fn write_sample_remote_metric_plugin(&self, sha256: &str) { + self.write_plugin_config(json!({ + "name": "remote-plugin", + "kind": "metric", + "url": "https://example.invalid/plugins/remote.wasm", + "sha256": sha256 + })); + } + fn run(&self, args: &[&str]) -> Output { let mut command = Command::new(env!("CARGO_BIN_EXE_codeint")); command.current_dir(self.dir.path()); @@ -323,12 +332,7 @@ fn doctor_verifies_external_wasm_plugins_and_fails_on_missing_or_mismatched_sha2 "pass" ); - fixture.write_plugin_config(json!({ - "name": "remote-plugin", - "kind": "metric", - "url": "https://example.invalid/plugins/remote.wasm", - "sha256": actual_hash - })); + fixture.write_sample_remote_metric_plugin(&actual_hash); let remote_report = fixture.run_json(&[], 0); assert_eq!(remote_report["status"], "warn"); assert_eq!( @@ -343,3 +347,51 @@ fn doctor_verifies_external_wasm_plugins_and_fails_on_missing_or_mismatched_sha2 "doctor must not write to cache directory" ); } + +#[cfg(unix)] +#[test] +fn doctor_reports_broken_symlink_for_codeint_json_and_cached_remote_plugin() { + use std::os::unix::fs::symlink; + + let broken_config_fixture = DoctorFixture::git_repo_with_ts(); + symlink( + broken_config_fixture.root().join("missing-config.json"), + broken_config_fixture.root().join("codeint.json"), + ) + .expect("create broken codeint.json symlink"); + + let broken_config_report = broken_config_fixture.run_json(&[], 1); + assert_eq!(broken_config_report["status"], "error"); + assert_check_field( + &broken_config_report, + "config", + "error", + "summary", + "broken symlink", + ); + let checks = broken_config_report["checks"] + .as_array() + .expect("checks array"); + assert!(!checks.iter().any(|check| check["id"] == "plugins")); + + let remote_fixture = DoctorFixture::git_repo_with_ts(); + let expected_hash = "0000000000000000000000000000000000000000000000000000000000000000"; + remote_fixture.write_sample_remote_metric_plugin(expected_hash); + let plugins_cache_dir = remote_fixture.cache.path().join("plugins"); + fs::create_dir_all(&plugins_cache_dir).expect("create plugins cache dir"); + symlink( + plugins_cache_dir.join("missing.wasm"), + plugins_cache_dir.join(format!("{expected_hash}.wasm")), + ) + .expect("create broken cached plugin symlink"); + + let broken_cache_report = remote_fixture.run_json(&[], 1); + assert_eq!(broken_cache_report["status"], "error"); + assert_check_field( + &broken_cache_report, + "plugin:remote-plugin", + "error", + "summary", + "broken symlink", + ); +} diff --git a/crates/cli/tests/report.rs b/crates/cli/tests/report.rs index b293943..0719bf7 100644 --- a/crates/cli/tests/report.rs +++ b/crates/cli/tests/report.rs @@ -363,3 +363,84 @@ fn rerenders_multilanguage_boundaries_and_unresolved_imports_losslessly() { "multi-diff.json", ); } + +fn assert_markdown_handles_max_left_out( + dir: &Path, + cache: &Path, + source_args: &[&str], + expected_code: i32, + left_out_field: &str, +) { + let raw_json = invoke(dir, cache, source_args, None); + assert_eq!(raw_json.status.code(), Some(expected_code)); + let mut doc: serde_json::Value = + serde_json::from_slice(&raw_json.stdout).expect("valid report json"); + doc["source_sets"]["production"]["boundaries"][left_out_field] = serde_json::json!(usize::MAX); + let payload = serde_json::to_vec(&doc).expect("serialize report json"); + let rendered = invoke( + dir, + cache, + &["report", "-", "--format", "markdown"], + Some(&payload), + ); + assert_eq!( + rendered.status.code(), + Some(0), + "stderr: {}", + utf8(&rendered.stderr) + ); + assert!(utf8(&rendered.stdout).contains(&usize::MAX.to_string())); +} + +#[test] +fn rerenders_markdown_without_overflow_when_left_out_is_usize_max() { + let (dir, cache) = setup_workspace(&[ + ( + "codeint.json", + r#"{ + "boundaries": { + "zones": { + "domain": { "patterns": ["src/domain/**"] }, + "infra": { "patterns": ["src/infra/**"] } + }, + "rules": [ + { "from": "domain", "deny": ["infra"] } + ] + } +} +"#, + ), + ( + "src/infra/db.ts", + "export function query(): number {\n return 1;\n}\n", + ), + ( + "src/domain/service.ts", + "import { query } from \"../infra/db\";\nexport const run = (): number => query();\n", + ), + ]); + commit_all(dir.path(), "base"); + + assert_markdown_handles_max_left_out( + dir.path(), + cache.path(), + &["check", "--format", "json"], + 0, + "findings_left_out", + ); + + populate( + dir.path(), + &[( + "src/domain/extra.ts", + "import { query } from \"../infra/db\";\nexport const extra = (): number => query();\n", + )], + ); + assert_markdown_handles_max_left_out( + dir.path(), + cache.path(), + &["diff", "main", "--format", "json"], + 1, + "new_left_out", + ); +} diff --git a/crates/cli/tests/schema.rs b/crates/cli/tests/schema.rs index 018ec2c..486d5ed 100644 --- a/crates/cli/tests/schema.rs +++ b/crates/cli/tests/schema.rs @@ -206,6 +206,16 @@ fn schema_matches_live_cli_commands_flags_metrics_formats_mcp_tools_version_and_ .map(|entry| entry["code"].as_i64().expect("exit code integer")) .collect(); assert_eq!(exit_codes, [0, 1, 2]); + let exit_one = manifest["exit_codes"] + .as_array() + .expect("exit_codes array") + .iter() + .find(|entry| entry["code"].as_i64() == Some(1)) + .expect("exit code 1 entry"); + let exit_one_desc = exit_one["description"].as_str().unwrap_or_default(); + assert!(exit_one_desc.contains("Budget")); + assert!(exit_one_desc.contains("Regression")); + assert!(exit_one_desc.contains("doctor")); } #[test] diff --git a/crates/config/src/codeint_json.rs b/crates/config/src/codeint_json.rs index f93eb6d..9c546e8 100644 --- a/crates/config/src/codeint_json.rs +++ b/crates/config/src/codeint_json.rs @@ -6,7 +6,8 @@ use codeint_model::{Metric, RepoPath, SourceSet}; use crate::RegressionLimits; use crate::boundaries::{Boundaries, BoundariesFile}; use crate::config_error::{ - CONFIGURATION_FILE_NAME, ConfigurationFileError, JsonType, KeyPath, KeySegment, glob_set, + CONFIGURATION_FILE_NAME, ConfigurationFileError, JsonType, KeyPath, KeySegment, compile_glob, + glob_set, }; use crate::regression_limits::RegressionLimitSetting; use crate::resolved::{ @@ -128,39 +129,43 @@ pub struct PluginDeclaration { } impl Configuration { + pub fn validate_cli_budget_metrics( + &self, + overrides: &[BudgetOverride], + external_metric_keys: &[&str], + ) -> Result<(), ConfigurationFileError> { + for entry in overrides { + if !is_known_metric(&entry.metric, external_metric_keys) { + return Err(ConfigurationFileError::UnknownCliBudgetMetric { + source_set: entry.source_set, + metric: entry.metric.clone(), + allowed: allowed_metric_keys(external_metric_keys), + }); + } + } + Ok(()) + } + pub fn validate_metrics( &self, external_metric_keys: &[&str], ) -> Result<(), ConfigurationFileError> { - let allowed_metrics = || -> Vec { - Metric::BUILT_IN_KEYS - .iter() - .chain(["boundaries"].iter()) - .chain(external_metric_keys.iter()) - .map(|key| (*key).to_owned()) - .collect() - }; - let is_known = |key: &str| { - Metric::BUILT_IN_KEYS.contains(&key) - || key == "boundaries" - || external_metric_keys.contains(&key) - }; for (source_set, metric_key, _) in &self.budgets.set { - if !is_known(metric_key) { + if !is_known_metric(metric_key, external_metric_keys) { return Err(ConfigurationFileError::UnknownKey { key: KeyPath::default() .child(KeySegment::Key("budgets".to_owned())) .child(KeySegment::Key(source_set.key().to_owned())) .child(KeySegment::Key(metric_key.clone())), - allowed: allowed_metrics(), + allowed: allowed_metric_keys(external_metric_keys), }); } } for (source_set, metric_key) in self.regression_limits.metric_keys() { - if !is_known(metric_key) { + if !is_known_metric(metric_key, external_metric_keys) { let mut path = KeyPath::default().child(KeySegment::Key("regression_limits".to_owned())); - let mut allowed = allowed_metrics(); + let mut allowed = allowed_metric_keys(external_metric_keys); if let Some(source_set) = source_set { path = path.child(KeySegment::Key(source_set.key().to_owned())); } else { @@ -180,6 +185,21 @@ impl Configuration { } } +fn allowed_metric_keys(external_metric_keys: &[&str]) -> Vec { + Metric::BUILT_IN_KEYS + .iter() + .chain(["boundaries"].iter()) + .chain(external_metric_keys.iter()) + .map(|key| (*key).to_owned()) + .collect() +} + +fn is_known_metric(key: &str, external_metric_keys: &[&str]) -> bool { + Metric::BUILT_IN_KEYS.contains(&key) + || key == "boundaries" + || external_metric_keys.contains(&key) +} + impl Serialize for Configuration { fn serialize(&self, serializer: S) -> Result { self.effective.serialize(serializer) @@ -191,10 +211,21 @@ pub struct Budgets { set: Vec<(SourceSet, String, Budget)>, } -#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize, JsonSchema)] +#[derive(Debug, Clone, Copy, PartialEq, Serialize, JsonSchema)] #[serde(transparent)] pub struct Budget(#[schemars(range(min = 0, max = 1))] f64); +impl<'de> Deserialize<'de> for Budget { + fn deserialize>(deserializer: D) -> Result { + let value = f64::deserialize(deserializer)?; + Ok(Budget(normalize_zero(value))) + } +} + +fn normalize_zero(value: f64) -> f64 { + if value == 0.0 { 0.0 } else { value } +} + impl Budgets { pub fn budget(&self, source_set: SourceSet, metric: Metric) -> Option { self.budget_for_key(source_set, metric.key()) @@ -210,15 +241,15 @@ impl Budgets { impl Budget { pub fn new(ratio: f64) -> Option { - (ratio.is_finite() && (0.0..=1.0).contains(&ratio)).then_some(Budget(ratio)) + (ratio.is_finite() && (0.0..=1.0).contains(&ratio)).then_some(Budget(normalize_zero(ratio))) } pub fn ratio(self) -> f64 { - self.0 + normalize_zero(self.0) } pub fn admits(self, ratio: f64) -> bool { - ratio <= self.0 + ratio <= self.ratio() } } @@ -633,32 +664,49 @@ pub fn read_configuration(repository_root: &Path) -> Result Result, ConfigurationFileError> { + match std::fs::read_to_string(path) { + Ok(text) => Ok(Some(text)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + if is_broken_symlink(path) { + Err(ConfigurationFileError::BrokenSymlink) + } else { + Ok(None) + } + } + Err(error) => Err(ConfigurationFileError::Unreadable(error)), + } +} + +pub fn is_broken_symlink(path: &Path) -> bool { + std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink()) + && matches!( + std::fs::metadata(path), + Err(error) if error.kind() == std::io::ErrorKind::NotFound + ) +} + pub fn read_resolved_configuration( repository_root: &Path, overrides: &ConfigOverrides, ) -> Result { let config_file = repository_root.join(CONFIGURATION_FILE_NAME); - match std::fs::read_to_string(&config_file) { - Ok(text) => parse_with_overrides(config_file, true, Some(&text), overrides), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - parse_with_overrides(config_file, false, None, overrides) - } - Err(error) => Err(ConfigurationFileError::Unreadable(error)), + match read_config_file_if_present(&config_file)? { + Some(text) => parse_with_overrides(config_file, true, Some(&text), overrides), + None => parse_with_overrides(config_file, false, None, overrides), } } pub fn inspect_configuration(repository_root: &Path) -> ConfigurationInspection { let path = repository_root.join(CONFIGURATION_FILE_NAME); - let text = match std::fs::read_to_string(&path) { - Ok(text) => text, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - return ConfigurationInspection::Missing { path }; - } + let text = match read_config_file_if_present(&path) { + Ok(Some(text)) => text, + Ok(None) => return ConfigurationInspection::Missing { path }, Err(error) => { return ConfigurationInspection::Invalid { path, schema: None, - error: ConfigurationFileError::Unreadable(error), + error, }; } }; @@ -812,6 +860,13 @@ fn merge_source_sets( overrides: &[SourceSetOverride], settings: &mut Vec, ) -> Result { + for entry in overrides { + compile_glob(&entry.glob).map_err(|source| ConfigurationFileError::InvalidCliGlob { + source_set: entry.source_set, + glob: entry.glob.clone(), + source, + })?; + } let cli_by_set = group_source_set_overrides(overrides); let slots = [ (SourceSet::Production, &mut globs.production), @@ -1048,17 +1103,27 @@ fn append_boundaries_settings( json!(boundaries.source_set_keys()), source_sets_source, ); + let zones_source = if has_json_path(raw, &["boundaries", "zones"]) { + ConfigProvenance::File + } else { + ConfigProvenance::Default + }; push_setting( settings, "boundaries.zones", boundaries.resolved_zones_json(), - ConfigProvenance::File, + zones_source, ); + let rules_source = if has_json_path(raw, &["boundaries", "rules"]) { + ConfigProvenance::File + } else { + ConfigProvenance::Default + }; push_setting( settings, "boundaries.rules", boundaries.resolved_rules_json(), - ConfigProvenance::File, + rules_source, ); } diff --git a/crates/config/src/config_error.rs b/crates/config/src/config_error.rs index 1b2a8a2..55c5ba6 100644 --- a/crates/config/src/config_error.rs +++ b/crates/config/src/config_error.rs @@ -1,6 +1,7 @@ use std::fmt; -use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; +use codeint_model::SourceSet; +use globset::{Glob, GlobBuilder, GlobSet, GlobSetBuilder}; use serde_json::Value; pub(crate) const CONFIGURATION_FILE_NAME: &str = "codeint.json"; @@ -29,6 +30,8 @@ pub struct KeyPath(Vec); pub enum ConfigurationFileError { #[error("cannot read {CONFIGURATION_FILE_NAME}")] Unreadable(#[source] std::io::Error), + #[error("{CONFIGURATION_FILE_NAME} is a broken symlink")] + BrokenSymlink, #[error("{CONFIGURATION_FILE_NAME} is not valid JSON")] NotJson(#[source] serde_json::Error), #[error( @@ -36,6 +39,16 @@ pub enum ConfigurationFileError { allowed.join(", ") )] UnknownKey { key: KeyPath, allowed: Vec }, + #[error( + "--budget {}.{metric} names an unknown Metric {metric:?}; the Metrics allowed are {}", + source_set.key(), + allowed.join(", ") + )] + UnknownCliBudgetMetric { + source_set: SourceSet, + metric: String, + allowed: Vec, + }, #[error( "{CONFIGURATION_FILE_NAME}: {key} must be {}, not {}", any_of(expected), @@ -81,6 +94,13 @@ pub enum ConfigurationFileError { #[source] source: globset::Error, }, + #[error("--source-set {}: {glob:?} is not a valid glob", source_set.key())] + InvalidCliGlob { + source_set: SourceSet, + glob: String, + #[source] + source: globset::Error, + }, #[error( "{CONFIGURATION_FILE_NAME}: {key} must be a 64-character hexadecimal SHA-256 digest, not {found:?}" )] @@ -137,14 +157,18 @@ pub enum ConfigurationFileError { ConflictingBoundaryDirectives { key: KeyPath, from: String }, } +pub(crate) fn compile_glob(glob: &str) -> Result { + GlobBuilder::new(glob) + .literal_separator(true) + .backslash_escape(true) + .build() +} + pub(crate) fn glob_set(key: &KeyPath, globs: &[String]) -> Result { let mut builder = GlobSetBuilder::new(); for (index, glob) in globs.iter().enumerate() { - let compiled = GlobBuilder::new(glob) - .literal_separator(true) - .backslash_escape(true) - .build() - .map_err(|source| ConfigurationFileError::InvalidGlob { + let compiled = + compile_glob(glob).map_err(|source| ConfigurationFileError::InvalidGlob { key: key.child(KeySegment::Index(index)), source, })?; diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 22d7e4b..a67299f 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -25,7 +25,7 @@ pub use codeint_json::{ Budget, Budgets, Configuration, ConfigurationInspection, DetectedLanguage, LanguageCoverage, Languages, PluginDeclaration, PluginKind, PluginLimits, PluginSource, SchemaVersionStatus, Sha256Digest, SourceSetOverrides, StarterConfigurationError, configuration_schema, - inspect_configuration, published_schema_address, read_configuration, + inspect_configuration, is_broken_symlink, published_schema_address, read_configuration, read_resolved_configuration, write_starter_configuration, }; pub use config_error::{ConfigurationFileError, JsonType, KeyPath, KeySegment}; diff --git a/crates/config/src/regression_limits.rs b/crates/config/src/regression_limits.rs index e9238f1..4ce8d4f 100644 --- a/crates/config/src/regression_limits.rs +++ b/crates/config/src/regression_limits.rs @@ -7,10 +7,17 @@ use serde::{Deserialize, Serialize}; use crate::ConfigProvenance; use crate::resolved::resolve_with_provenance; -#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Serialize)] #[serde(transparent)] pub struct RatioRise(f64); +impl<'de> Deserialize<'de> for RatioRise { + fn deserialize>(deserializer: D) -> Result { + let value = f64::deserialize(deserializer)?; + Ok(RatioRise(if value == 0.0 { 0.0 } else { value })) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum NewFindingsRule { @@ -53,7 +60,7 @@ impl RatioRise { pub const DEFAULT: RatioRise = RatioRise(0.01); pub fn ratio(self) -> f64 { - self.0 + if self.0 == 0.0 { 0.0 } else { self.0 } } pub fn admits(self, displayed_rise: f64) -> bool { diff --git a/crates/config/src/resolved.rs b/crates/config/src/resolved.rs index 853242f..4658e9a 100644 --- a/crates/config/src/resolved.rs +++ b/crates/config/src/resolved.rs @@ -79,7 +79,11 @@ impl FromStr for BudgetOverride { format!("{target:?} must name SOURCE_SET.METRIC, such as production.erosion") })?; let source_set = parse_source_set(source_set_text)?; - if metric.trim().is_empty() || metric.contains('.') { + if metric.is_empty() + || metric.trim() != metric + || metric.contains('.') + || metric.chars().any(char::is_whitespace) + { return Err(format!("{metric:?} is not a valid Metric key in {raw:?}")); } let ratio: f64 = ratio_text @@ -106,6 +110,8 @@ impl FromStr for SourceSetOverride { if glob.trim().is_empty() { return Err(format!("glob in {raw:?} must not be empty")); } + crate::config_error::compile_glob(glob) + .map_err(|error| format!("glob {glob:?} in {raw:?} is not a valid glob: {error}"))?; Ok(SourceSetOverride { source_set, glob: glob.to_owned(), diff --git a/crates/report/src/diff.rs b/crates/report/src/diff.rs index 357bc00..923c477 100644 --- a/crates/report/src/diff.rs +++ b/crates/report/src/diff.rs @@ -416,7 +416,7 @@ impl MetricChanges { } fn new_findings(&self) -> usize { - self.new.listed.len() + self.new.left_out + self.new.listed.len().saturating_add(self.new.left_out) } fn compared_values(&self, rule: RegressionRule) -> (Decimal, Decimal) { diff --git a/crates/report/src/diff/markdown.rs b/crates/report/src/diff/markdown.rs index 4d75479..b4d5975 100644 --- a/crates/report/src/diff/markdown.rs +++ b/crates/report/src/diff/markdown.rs @@ -94,7 +94,7 @@ fn metric_row(source_set: &str, metric: &str, changes: &MetricChanges) -> } fn count(findings: &Findings) -> usize { - findings.listed.len() + findings.left_out + findings.listed.len().saturating_add(findings.left_out) } fn findings_blocks(changes: &SourceSetChanges) -> Vec { diff --git a/crates/report/src/diff/tests.rs b/crates/report/src/diff/tests.rs index afeba2c..d4cdceb 100644 --- a/crates/report/src/diff/tests.rs +++ b/crates/report/src/diff/tests.rs @@ -34,3 +34,14 @@ fn a_displayed_rise_of_0_0101_is_a_regression() { assert!(changes.breaks(RegressionRule::RatioRise, RegressionLimit::DEFAULT)); } + +#[test] +fn new_findings_saturates_when_left_out_is_usize_max() { + let mut changes = ratio_changes(0.0, 0.0); + changes.new = Findings { + listed: vec![()], + left_out: usize::MAX, + }; + + assert_eq!(changes.new_findings(), usize::MAX); +} diff --git a/crates/report/src/markdown.rs b/crates/report/src/markdown.rs index ed4ea67..bd6b828 100644 --- a/crates/report/src/markdown.rs +++ b/crates/report/src/markdown.rs @@ -289,7 +289,11 @@ fn metric_rows(source_set: &str, section: &SourceSetSection) -> Vec> ), ]; if let Some(boundaries) = §ion.boundaries { - let total_findings = boundaries.findings.listed.len() + boundaries.findings.left_out; + let total_findings = boundaries + .findings + .listed + .len() + .saturating_add(boundaries.findings.left_out); rows.push(vec![ source_set.to_string(), "Boundaries".to_string(),