From 7c08fed4691dcef05346e3c4f42e0374823027cb Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 09:52:05 +0800 Subject: [PATCH 1/5] feat(host): upgrade plugin contract to codeint:plugin@0.2.0 Upgrade wit/language.wit and wit/metric.wit to codeint:plugin@0.2.0, adding function name and cognitive-complexity fields, external(string) and builtin resolution variants, declared-dependencies, and entry-points. Bind 0.2.0 in crates/model and crates/plugin-host, detect incompatible WIT contract versions (such as 0.1.0) with an actionable IncompatibleContractVersion error, add compiling 0.2.0 stubs across all five built-in Language plugins, update the sample Wasm Plugin and sandbox probes, add 0.2.0 contract and 0.1.0 rejection tests, and update Plugin documentation. Closes #190 --- crates/cli/src/check/tests.rs | 34 ++- crates/cli/src/remedy.rs | 44 ++-- crates/metrics/src/import_cycles.rs | 4 +- crates/metrics/src/import_cycles/tests.rs | 4 +- crates/model/HOW-TO.md | 23 +- crates/model/src/lib.rs | 16 +- crates/model/src/runtime_imports.rs | 6 +- crates/model/src/runtime_imports/tests.rs | 28 ++- crates/model/src/scan.rs | 6 +- crates/model/src/tests.rs | 12 +- crates/plugin-host/HOW-TO.md | 1 + crates/plugin-host/src/lib.rs | 24 +- crates/plugin-host/src/wasm.rs | 179 ++++++++++++-- crates/plugin-host/src/wasm_metric.rs | 89 ++++--- crates/plugin-host/tests/conformance.rs | 22 +- .../tests/fixtures/sample-plugin/src/lib.rs | 230 +++++++++++++----- .../tests/fixtures/sandbox-probes/Cargo.lock | 16 ++ .../tests/fixtures/sandbox-probes/Cargo.toml | 2 + .../sandbox-probes/clock-reader/src/lib.rs | 10 +- .../sandbox-probes/file-reader/src/lib.rs | 10 +- .../legacy-v0-1-0-language/Cargo.toml | 12 + .../legacy-v0-1-0-language/src/lib.rs | 150 ++++++++++++ .../legacy-v0-1-0-metric/Cargo.toml | 12 + .../legacy-v0-1-0-metric/src/lib.rs | 137 +++++++++++ .../sandbox-probes/loop-language/src/lib.rs | 12 +- .../memory-hog-language/src/lib.rs | 12 +- .../sandbox-probes/socket-opener/src/lib.rs | 10 +- crates/plugin-host/tests/load.rs | 165 ++++++++++++- docs/plugins.md | 31 +-- plugins/languages/dart/src/lib.rs | 12 +- plugins/languages/dart/src/resolution.rs | 8 +- plugins/languages/dart/tests/conformance.rs | 33 ++- plugins/languages/php/src/lib.rs | 12 +- plugins/languages/php/src/resolution.rs | 6 +- plugins/languages/php/tests/conformance.rs | 6 +- plugins/languages/python/src/lib.rs | 12 +- plugins/languages/python/src/resolution.rs | 6 +- plugins/languages/python/tests/conformance.rs | 4 +- plugins/languages/rust/src/functions.rs | 2 + plugins/languages/rust/src/lib.rs | 12 +- plugins/languages/rust/src/resolution.rs | 18 +- plugins/languages/rust/tests/conformance.rs | 8 +- plugins/languages/ts/src/functions.rs | 2 + plugins/languages/ts/src/lib.rs | 10 +- plugins/languages/ts/src/resolution.rs | 53 ++-- plugins/languages/ts/tests/conformance.rs | 37 ++- wit/language.wit | 45 +++- wit/metric.wit | 2 +- 48 files changed, 1321 insertions(+), 268 deletions(-) create mode 100644 crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/Cargo.toml create mode 100644 crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/src/lib.rs create mode 100644 crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/Cargo.toml create mode 100644 crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/src/lib.rs diff --git a/crates/cli/src/check/tests.rs b/crates/cli/src/check/tests.rs index 82ccf77..f03a548 100644 --- a/crates/cli/src/check/tests.rs +++ b/crates/cli/src/check/tests.rs @@ -5,8 +5,8 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use codeint_config::{FindingsShown, ReportFormat}; use codeint_model::language::{ - FileModel, FlaggedLine, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, - SourceSet, WorkspaceError, + DeclaredDep, FileModel, FlaggedLine, Guest, ImportRequest, LowerError, Manifest, + ReferenceRange, Resolution, SourceSet, WorkspaceError, }; use codeint_model::{InvalidReferenceRange, LanguagePlugin, ReferenceRanges, RepoPath}; use serde_json::Value; @@ -89,7 +89,18 @@ macro_rules! every_import_is_external { _manifests: Vec, requests: Vec, ) -> Vec { - requests.iter().map(|_| Resolution::External).collect() + requests + .iter() + .map(|_| Resolution::External(String::new())) + .collect() + } + + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() } }; } @@ -766,7 +777,22 @@ impl LanguagePlugin for ParallelProofPlugin { _manifests: Vec, requests: Vec, ) -> Vec { - requests.iter().map(|_| Resolution::External).collect() + requests + .iter() + .map(|_| Resolution::External(String::new())) + .collect() + } + + fn declared_dependencies(&self, _manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points( + &self, + _repository_paths: &[RepoPath], + _manifests: Vec, + ) -> Vec { + Vec::new() } fn reference_ranges(&self) -> Result { diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 9747e89..8be9546 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -260,7 +260,11 @@ fn plugin_config_remedy(error: &ConfigurationFileError) -> Option<&'static str> } fn plugin_host_remedy(error: &PluginHostError) -> &'static str { - match error { + plugin_load_remedy(error).unwrap_or_else(|| plugin_runtime_remedy(error)) +} + +fn plugin_load_remedy(error: &PluginHostError) -> Option<&'static str> { + Some(match error { PluginHostError::Read { .. } => { "Check that the plugin path in codeint.json points to an existing readable WebAssembly component file." } @@ -268,11 +272,32 @@ fn plugin_host_remedy(error: &PluginHostError) -> &'static str { "Verify the plugin file has not been modified, then update sha256 in codeint.json to match the trusted file." } PluginHostError::Compile { .. } => { - "Build the plugin as a WebAssembly component targeting codeint:plugin@0.1.0." + "Build the plugin as a WebAssembly component targeting codeint:plugin@0.2.0." } PluginHostError::Instantiate { .. } => { - "Ensure the plugin exports codeint:plugin/language@0.1.0 or codeint:plugin/metric@0.1.0 and imports no host capabilities." + "Ensure the plugin exports codeint:plugin/language@0.2.0 or codeint:plugin/metric@0.2.0 and imports no host capabilities." + } + PluginHostError::IncompatibleContractVersion { .. } => { + "Rebuild the plugin against codeint:plugin@0.2.0 and update its sha256 in codeint.json." + } + PluginHostError::NonHttpsUrl { .. } => { + "Use an https:// URL for the plugin in codeint.json; plain HTTP and other schemes are refused." + } + PluginHostError::MissingCacheDir { .. } => { + "Set CODEINT_CACHE_DIR, XDG_CACHE_HOME, HOME, or LOCALAPPDATA so codeint can cache downloaded plugins." + } + PluginHostError::CacheWrite { .. } => { + "Check that you have permission to write to the codeint plugin cache directory, or set CODEINT_CACHE_DIR to a writable folder." + } + PluginHostError::Download { .. } => { + "Check that curl is installed, the HTTPS URL is reachable, and its TLS certificate is valid." } + _ => return None, + }) +} + +fn plugin_runtime_remedy(error: &PluginHostError) -> &'static str { + match error { PluginHostError::Call { .. } => { "Fix the defect in the external Plugin, or report it to the plugin's author." } @@ -288,18 +313,7 @@ fn plugin_host_remedy(error: &PluginHostError) -> &'static str { PluginHostError::DuplicateMetricKey { .. } => { "Remove one of the Metric plugins that declare the same Metric key." } - PluginHostError::NonHttpsUrl { .. } => { - "Use an https:// URL for the plugin in codeint.json; plain HTTP and other schemes are refused." - } - PluginHostError::MissingCacheDir { .. } => { - "Set CODEINT_CACHE_DIR, XDG_CACHE_HOME, HOME, or LOCALAPPDATA so codeint can cache downloaded plugins." - } - PluginHostError::CacheWrite { .. } => { - "Check that you have permission to write to the codeint plugin cache directory, or set CODEINT_CACHE_DIR to a writable folder." - } - PluginHostError::Download { .. } => { - "Check that curl is installed, the HTTPS URL is reachable, and its TLS certificate is valid." - } + _ => "Check the plugin configuration in codeint.json.", } } diff --git a/crates/metrics/src/import_cycles.rs b/crates/metrics/src/import_cycles.rs index d8f30bb..e3b04d6 100644 --- a/crates/metrics/src/import_cycles.rs +++ b/crates/metrics/src/import_cycles.rs @@ -162,7 +162,9 @@ fn unresolved_imports(model: &CodeModel) -> Vec { specifier: runtime_import.specifier.clone(), reason: reason.clone(), }), - ImportResolution::Resolved(_) | ImportResolution::External => None, + ImportResolution::Resolved(_) + | ImportResolution::External(_) + | ImportResolution::Builtin => None, }) .collect(); unresolved.sort_by(|left, right| left.importer.cmp(&right.importer)); diff --git a/crates/metrics/src/import_cycles/tests.rs b/crates/metrics/src/import_cycles/tests.rs index 3eeaf6e..9074fd2 100644 --- a/crates/metrics/src/import_cycles/tests.rs +++ b/crates/metrics/src/import_cycles/tests.rs @@ -107,7 +107,7 @@ fn imports_of_files_that_are_not_modules_and_unresolved_imports_add_no_edge() { model.runtime_imports.push(RuntimeImport { importer: path("b.ts"), specifier: "a".to_owned(), - resolution: ImportResolution::External, + resolution: ImportResolution::External("a".to_owned()), }); let cycles = ImportCycles::measure(&model); @@ -161,7 +161,7 @@ fn unresolved_imports_are_listed_by_importer_in_source_order_and_others_are_not( RuntimeImport { importer: path("a.ts"), specifier: "lodash".to_owned(), - resolution: ImportResolution::External, + resolution: ImportResolution::External("lodash".to_owned()), }, unresolved("b.ts", "./first"), ]); diff --git a/crates/model/HOW-TO.md b/crates/model/HOW-TO.md index c85c19e..fabc417 100644 --- a/crates/model/HOW-TO.md +++ b/crates/model/HOW-TO.md @@ -4,8 +4,8 @@ ```rust use codeint_model::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, - Token, TokenKind, WorkspaceError, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + SourceSet, Token, TokenKind, WorkspaceError, }; use codeint_model::token_text_hash; @@ -60,7 +60,18 @@ impl Guest for Plain { _manifests: Vec, requests: Vec, ) -> Vec { - requests.iter().map(|_| Resolution::External).collect() + requests + .iter() + .map(|request| Resolution::External(request.specifier.clone())) + .collect() + } + + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() } fn reference_ranges() -> Vec { @@ -74,7 +85,7 @@ impl Guest for Plain { } ``` -- The interface is defined once, in [wit/language.wit](../../wit/language.wit), as the versioned package `codeint:plugin@0.1.0`. +- The interface is defined once, in [wit/language.wit](../../wit/language.wit), as the versioned package `codeint:plugin@0.2.0`. - `codeint_model::language` holds the Rust types that wit-bindgen generates from that file. Never write a second Rust copy of a WIT type. - A built-in Language plugin implements the generated `Guest` trait, so it compiles against the same interface as an external WebAssembly Plugin. @@ -121,7 +132,9 @@ impl Guest for Plain { Name only paths from `repository_paths`; which files matter is a rule of the Language plugin, never of the core. It is the one way a Language plugin asks the host for files, so the host reads each file once. - `resolve_imports` receives every file path of the repository snapshot and each file that `manifest_paths` chose as a `Manifest` with its text, because a Plugin cannot read the file system. - Return one `Resolution` per request, in request order: `Resolved` with a path from `repository_paths`, `External` for a package or built-in module, or `Unresolved` with the reason. + Return one `Resolution` per request, in request order: `Resolved` with a path from `repository_paths`, `External` with the canonical third-party package name, `Builtin` for a standard-library or runtime built-in module, or `Unresolved` with the reason. +- `declared_dependencies` extracts external dependencies declared in `manifests`, each with its `package-root`, normalized `name`, and `kind` (`Runtime`, `Dev`, or `Optional`). +- `entry_points` discovers standard entry-point source files from `repository_paths` and `manifests`, naming only paths from `repository_paths`. ## Lower files in the core diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index f4f1735..88bb53b 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -23,7 +23,9 @@ mod bindings { } pub use bindings::exports::codeint::plugin::language; -pub use language::{FileModel, Manifest, ReferenceRange, SourceSet, Token, TokenKind}; +pub use language::{ + DeclaredDep, DepKind, FileModel, Manifest, ReferenceRange, SourceSet, Token, TokenKind, +}; pub use metric::{ ExternalFinding, ExternalMetricMeasurement, Metric, MetricPlugin, MetricPluginError, }; @@ -318,6 +320,10 @@ pub trait LanguagePlugin: Sync { requests: Vec, ) -> Vec; + fn declared_dependencies(&self, manifests: Vec) -> Vec; + + fn entry_points(&self, repository_paths: &[RepoPath], manifests: Vec) -> Vec; + fn reference_ranges(&self) -> Result; } @@ -353,6 +359,14 @@ impl LanguagePlugin for Plugin { Plugin::resolve_imports(owned_paths(repository_paths), manifests, requests) } + fn declared_dependencies(&self, manifests: Vec) -> Vec { + Plugin::declared_dependencies(manifests) + } + + fn entry_points(&self, repository_paths: &[RepoPath], manifests: Vec) -> Vec { + Plugin::entry_points(owned_paths(repository_paths), manifests) + } + fn reference_ranges(&self) -> Result { ReferenceRanges::new(Plugin::reference_ranges()) } diff --git a/crates/model/src/runtime_imports.rs b/crates/model/src/runtime_imports.rs index f4ad77b..ea4b640 100644 --- a/crates/model/src/runtime_imports.rs +++ b/crates/model/src/runtime_imports.rs @@ -8,7 +8,8 @@ mod tests; #[derive(Clone, Debug, PartialEq, Eq)] pub enum ImportResolution { Resolved(RepoPath), - External, + External(String), + Builtin, Unresolved { reason: String }, } @@ -101,7 +102,8 @@ pub fn resolve_runtime_imports( target, }); } - language::Resolution::External => ImportResolution::External, + language::Resolution::External(package) => ImportResolution::External(package), + language::Resolution::Builtin => ImportResolution::Builtin, language::Resolution::Unresolved(reason) => ImportResolution::Unresolved { reason }, }; Ok(RuntimeImport { diff --git a/crates/model/src/runtime_imports/tests.rs b/crates/model/src/runtime_imports/tests.rs index 1d901f5..289f1a8 100644 --- a/crates/model/src/runtime_imports/tests.rs +++ b/crates/model/src/runtime_imports/tests.rs @@ -1,4 +1,4 @@ -use crate::language::{ImportRequest, Resolution, SourceSet}; +use crate::language::{DeclaredDep, ImportRequest, Resolution, SourceSet}; use crate::{ FileModel, InvalidReferenceRange, LanguagePlugin, LowerError, Manifest, ReferenceRanges, RepoPath, SourceFile, WorkspaceError, @@ -11,6 +11,18 @@ use super::{ struct Answering(Vec); impl LanguagePlugin for Answering { + fn declared_dependencies(&self, _manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points( + &self, + _repository_paths: &[RepoPath], + _manifests: Vec, + ) -> Vec { + Vec::new() + } + fn extensions(&self) -> Vec { vec!["ts".to_owned()] } @@ -66,10 +78,11 @@ fn importer(name: &str, specifiers: &[&str]) -> SourceFile { fn each_runtime_import_keeps_its_importer_specifier_and_resolution() { let plugin = Answering(vec![ Resolution::Resolved("b.ts".to_owned()), - Resolution::External, + Resolution::External("react".to_owned()), + Resolution::Builtin, Resolution::Unresolved("gone".to_owned()), ]); - let a = importer("a.ts", &["./b", "react"]); + let a = importer("a.ts", &["./b", "react", "node:fs"]); let b = importer("b.ts", &["./gone"]); let imports = resolve_runtime_imports( @@ -91,7 +104,12 @@ fn each_runtime_import_keeps_its_importer_specifier_and_resolution() { RuntimeImport { importer: path("a.ts"), specifier: "react".to_owned(), - resolution: ImportResolution::External, + resolution: ImportResolution::External("react".to_owned()), + }, + RuntimeImport { + importer: path("a.ts"), + specifier: "node:fs".to_owned(), + resolution: ImportResolution::Builtin, }, RuntimeImport { importer: path("b.ts"), @@ -106,7 +124,7 @@ fn each_runtime_import_keeps_its_importer_specifier_and_resolution() { #[test] fn a_plugin_that_answers_the_wrong_number_of_requests_is_an_error() { - let plugin = Answering(vec![Resolution::External]); + let plugin = Answering(vec![Resolution::External("react".to_owned())]); let a = importer("a.ts", &["react", "vue"]); let result = resolve_runtime_imports(&plugin, &[path("a.ts")], Vec::new(), &[&a]); diff --git a/crates/model/src/scan.rs b/crates/model/src/scan.rs index d36451f..c35ac27 100644 --- a/crates/model/src/scan.rs +++ b/crates/model/src/scan.rs @@ -201,6 +201,8 @@ pub fn score_function_spans( end_line, decision_points: decisions, source_lines: code_lines.range(start_line..=end_line).count() as u32, + name: None, + cognitive_complexity: 0, } }) .collect(); @@ -295,11 +297,11 @@ pub fn resolve_relative_file( return Resolution::Unresolved(format!("{rel_uri:?} leads outside the repository")); }; if ignore_vendor && joined.split('/').any(|seg| seg == "vendor") { - return Resolution::External; + return Resolution::External(String::new()); } if files.contains(&joined) { if joined == importer { - Resolution::External + Resolution::External(String::new()) } else { Resolution::Resolved(joined) } diff --git a/crates/model/src/tests.rs b/crates/model/src/tests.rs index 8478ccd..909adba 100644 --- a/crates/model/src/tests.rs +++ b/crates/model/src/tests.rs @@ -1,6 +1,6 @@ use super::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, - WorkspaceError, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + SourceSet, WorkspaceError, }; use super::{ CodeModel, ImportResolution, InvalidReferenceRange, LanguagePlugin, Package, ReferenceRanges, @@ -84,6 +84,14 @@ impl Guest for MeasuredLanguage { .collect() } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn reference_ranges() -> Vec { vec![range("erosion", 0.12, 0.56, "Measured panel, Table 1")] } diff --git a/crates/plugin-host/HOW-TO.md b/crates/plugin-host/HOW-TO.md index 3cf7836..7f89ea9 100644 --- a/crates/plugin-host/HOW-TO.md +++ b/crates/plugin-host/HOW-TO.md @@ -15,6 +15,7 @@ let external = load_language_plugins(repository.root(), &configuration.plugins, - Relative paths in `PluginSource::Path` resolve against `repository_root`; absolute paths are used as given. - `PluginSource::HttpsUrl` downloads through `curl` with `--proto =https --tlsv1.2 --proto-redir =https`, verifies the SHA-256 digest of the downloaded bytes before atomically renaming into `/.wasm`, and reuses a valid cached entry without network I/O. - Every `WasmLanguagePlugin` is instantiated with an empty `wasmtime::component::Linker` with zero host capabilities (no WASI, no filesystem, no network, no environment variables, no clocks). A component that imports any host interface fails to instantiate with `PluginHostError::Instantiate`. +- Every `WasmLanguagePlugin` and `WasmMetricPlugin` validates its exported WIT interface version against `codeint:plugin@0.2.0` before instantiation; an incompatible version (such as `codeint:plugin@0.1.0`) fails with `PluginHostError::IncompatibleContractVersion`. - Every `WasmLanguagePlugin` and `WasmMetricPlugin` enforces `codeint_config::PluginLimits` (linear memory cap via `wasmtime::ResourceLimiter` and wall-clock time limit via `wasmtime` epoch interruption). Use `load_language_plugins_with_limits` and `load_metric_plugins_with_limits` to pass configured limits from `codeint.json`. - `WasmLanguagePlugin` implements `codeint_model::LanguagePlugin: Sync` using an internal pool of pre-instantiated component instances, so callers can invoke `lower` concurrently across threads. diff --git a/crates/plugin-host/src/lib.rs b/crates/plugin-host/src/lib.rs index e403d53..cf9c323 100644 --- a/crates/plugin-host/src/lib.rs +++ b/crates/plugin-host/src/lib.rs @@ -5,9 +5,9 @@ use std::path::{Path, PathBuf}; use codeint_config::{PluginDeclaration, PluginHostConfig, PluginKind, PluginLimits, PluginSource}; use codeint_model::{ - CodeModel, ExternalMetricMeasurement, FileModel, InvalidReferenceRange, LanguagePlugin, - LowerError, Manifest, MetricPlugin, MetricPluginError, ReferenceRanges, RepoPath, - WorkspaceError, language, + CodeModel, DeclaredDep, ExternalMetricMeasurement, FileModel, InvalidReferenceRange, + LanguagePlugin, LowerError, Manifest, MetricPlugin, MetricPluginError, ReferenceRanges, + RepoPath, WorkspaceError, language, }; mod fetch; @@ -51,6 +51,16 @@ pub enum PluginHostError { path: PathBuf, reason: String, }, + #[error( + "Plugin {name:?} at {} targets incompatible WIT contract {found}, but this version of codeint requires {expected}; rebuild the Plugin against {expected} and update its sha256 in codeint.json", + path.display() + )] + IncompatibleContractVersion { + name: String, + path: PathBuf, + expected: &'static str, + found: String, + }, #[error("Plugin {name:?} failed during {call}: {reason}")] Call { name: String, @@ -268,6 +278,14 @@ impl LanguagePlugin for WasmLanguagePlugin { self.resolve_imports_impl(repository_paths, manifests, requests) } + fn declared_dependencies(&self, manifests: Vec) -> Vec { + self.declared_dependencies_impl(manifests) + } + + fn entry_points(&self, repository_paths: &[RepoPath], manifests: Vec) -> Vec { + self.entry_points_impl(repository_paths, manifests) + } + fn reference_ranges(&self) -> Result { self.reference_ranges_impl() } diff --git a/crates/plugin-host/src/wasm.rs b/crates/plugin-host/src/wasm.rs index 8275c58..91d484e 100644 --- a/crates/plugin-host/src/wasm.rs +++ b/crates/plugin-host/src/wasm.rs @@ -4,8 +4,8 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use codeint_config::PluginLimits; use codeint_model::{ - FileModel, InvalidReferenceRange, LowerError, Manifest, ReferenceRange, ReferenceRanges, - RepoPath, SourceSet, Token, TokenKind, WorkspaceError, language, + DeclaredDep, DepKind, FileModel, InvalidReferenceRange, LowerError, Manifest, ReferenceRange, + ReferenceRanges, RepoPath, SourceSet, Token, TokenKind, WorkspaceError, language, }; use wasmtime::component::{Component, Linker}; use wasmtime::{Config, Engine, Store}; @@ -24,6 +24,40 @@ mod bindings { use bindings::exports::codeint::plugin::language as guest; +pub(crate) struct ContractSpec { + pub(crate) interface_prefix: &'static str, + pub(crate) expected_interface: &'static str, +} + +const LANGUAGE_CONTRACT: ContractSpec = ContractSpec { + interface_prefix: "codeint:plugin/language@", + expected_interface: "codeint:plugin/language@0.2.0", +}; + +pub(crate) fn check_contract_version( + name: &str, + path: &Path, + engine: &Engine, + instance_pre: &wasmtime::component::InstancePre, + spec: ContractSpec, +) -> Result<(), PluginHostError> { + let component_type = instance_pre.component().component_type(); + for (export_name, _) in component_type.exports(engine) { + if export_name == spec.expected_interface { + return Ok(()); + } + if export_name.starts_with(spec.interface_prefix) { + return Err(PluginHostError::IncompatibleContractVersion { + name: name.to_owned(), + path: path.to_path_buf(), + expected: spec.expected_interface, + found: export_name.to_owned(), + }); + } + } + Ok(()) +} + struct PluginInstance { store: Store, bindings: bindings::LanguagePlugin, @@ -71,6 +105,45 @@ pub(crate) fn compile_sandboxed_component( Ok((engine, instance_pre)) } +pub(crate) struct InstantiatedComponent { + pub(crate) engine: Engine, + pub(crate) ticker: EpochTicker, + pub(crate) pre: Pre, + pub(crate) store: Store, + pub(crate) bindings: Bindings, +} + +pub(crate) fn instantiate_sandboxed_component( + name: &str, + path: &Path, + bytes: &[u8], + limits: PluginLimits, + spec: ContractSpec, + bind: impl FnOnce( + wasmtime::component::InstancePre, + ) -> Result, + instantiate: impl FnOnce(&Pre, &mut Store) -> Result, +) -> Result, PluginHostError> { + let (engine, instance_pre) = compile_sandboxed_component(name, path, bytes)?; + check_contract_version(name, path, &engine, &instance_pre, spec)?; + let ticker = EpochTicker::start(engine.clone()); + let pre = bind(instance_pre).map_err(|error| PluginHostError::Instantiate { + name: name.to_owned(), + path: path.to_path_buf(), + reason: error.to_string(), + })?; + let mut store = new_limited_store(&engine, limits); + let bindings = instantiate(&pre, &mut store) + .map_err(|error| map_host_trap(name, path, None, limits, &store, error))?; + Ok(InstantiatedComponent { + engine, + ticker, + pre, + store, + bindings, + }) +} + impl WasmLanguagePlugin { pub(crate) fn from_verified_bytes( name: String, @@ -78,35 +151,42 @@ impl WasmLanguagePlugin { bytes: &[u8], limits: PluginLimits, ) -> Result { - let (engine, instance_pre) = compile_sandboxed_component(&name, path, bytes)?; - let ticker = EpochTicker::start(engine.clone()); - let pre = bindings::LanguagePluginPre::new(instance_pre).map_err(|error| { - PluginHostError::Instantiate { - name: name.clone(), - path: path.to_path_buf(), - reason: error.to_string(), - } - })?; - let mut store = new_limited_store(&engine, limits); - let bindings = pre - .instantiate(&mut store) - .map_err(|error| map_host_trap(&name, path, None, limits, &store, error))?; - arm_call_deadline(&mut store, limits); - let extensions = bindings + let mut component = instantiate_sandboxed_component( + &name, + path, + bytes, + limits, + LANGUAGE_CONTRACT, + bindings::LanguagePluginPre::new, + |pre, store| pre.instantiate(store), + )?; + arm_call_deadline(&mut component.store, limits); + let extensions = component + .bindings .codeint_plugin_language() - .call_extensions(&mut store) + .call_extensions(&mut component.store) .map_err(|error| { - map_host_trap(&name, path, Some("extensions"), limits, &store, error) + map_host_trap( + &name, + path, + Some("extensions"), + limits, + &component.store, + error, + ) })?; - let peak_memory_bytes = AtomicUsize::new(store.data().peak_memory_bytes()); + let peak_memory_bytes = AtomicUsize::new(component.store.data().peak_memory_bytes()); Ok(WasmLanguagePlugin { name, limits, - engine, - _ticker: ticker, - pre, + engine: component.engine, + _ticker: component.ticker, + pre: component.pre, extensions, - pool: Mutex::new(vec![PluginInstance { store, bindings }]), + pool: Mutex::new(vec![PluginInstance { + store: component.store, + bindings: component.bindings, + }]), peak_memory_bytes, }) } @@ -265,6 +345,40 @@ impl WasmLanguagePlugin { .unwrap_or_default() } + pub(crate) fn declared_dependencies_impl(&self, manifests: Vec) -> Vec { + let host_manifests: Vec = manifests + .into_iter() + .map(|manifest| guest::Manifest { + path: manifest.path, + text: manifest.text, + }) + .collect(); + self.with_instance("declared-dependencies", |api, store| { + api.call_declared_dependencies(store, &host_manifests) + }) + .map(|deps| deps.into_iter().map(convert_declared_dep).collect()) + .unwrap_or_default() + } + + pub(crate) fn entry_points_impl( + &self, + repository_paths: &[RepoPath], + manifests: Vec, + ) -> Vec { + let paths = owned_paths(repository_paths); + let host_manifests: Vec = manifests + .into_iter() + .map(|manifest| guest::Manifest { + path: manifest.path, + text: manifest.text, + }) + .collect(); + self.with_instance("entry-points", |api, store| { + api.call_entry_points(store, &paths, &host_manifests) + }) + .unwrap_or_default() + } + pub(crate) fn reference_ranges_impl(&self) -> Result { let ranges = self .with_instance("reference-ranges", |api, store| { @@ -302,6 +416,8 @@ fn convert_file_model(model: guest::FileModel) -> FileModel { end_line: function.end_line, decision_points: function.decision_points, source_lines: function.source_lines, + name: function.name, + cognitive_complexity: function.cognitive_complexity, }) .collect(), tokens: model @@ -355,11 +471,24 @@ fn convert_lower_error(error: guest::LowerError) -> LowerError { fn convert_resolution(resolution: guest::Resolution) -> language::Resolution { match resolution { guest::Resolution::Resolved(path) => language::Resolution::Resolved(path), - guest::Resolution::External => language::Resolution::External, + guest::Resolution::External(package) => language::Resolution::External(package), + guest::Resolution::Builtin => language::Resolution::Builtin, guest::Resolution::Unresolved(reason) => language::Resolution::Unresolved(reason), } } +fn convert_declared_dep(dep: guest::DeclaredDep) -> DeclaredDep { + DeclaredDep { + package_root: dep.package_root, + name: dep.name, + kind: match dep.kind { + guest::DepKind::Runtime => DepKind::Runtime, + guest::DepKind::Dev => DepKind::Dev, + guest::DepKind::Optional => DepKind::Optional, + }, + } +} + pub(crate) fn map_host_trap( name: &str, path: &Path, diff --git a/crates/plugin-host/src/wasm_metric.rs b/crates/plugin-host/src/wasm_metric.rs index 888c19c..2408541 100644 --- a/crates/plugin-host/src/wasm_metric.rs +++ b/crates/plugin-host/src/wasm_metric.rs @@ -13,7 +13,12 @@ use crate::PluginHostError; use crate::limits::{ EpochTicker, LimitTrap, PluginStoreState, arm_call_deadline, classify_trap, new_limited_store, }; -use crate::wasm::{compile_sandboxed_component, map_host_trap}; +use crate::wasm::{ContractSpec, instantiate_sandboxed_component, map_host_trap}; + +const METRIC_CONTRACT: ContractSpec = ContractSpec { + interface_prefix: "codeint:plugin/metric@", + expected_interface: "codeint:plugin/metric@0.2.0", +}; mod bindings { wasmtime::component::bindgen!({ @@ -52,56 +57,71 @@ impl WasmMetricPlugin { bytes: &[u8], limits: PluginLimits, ) -> Result { - let (engine, instance_pre) = compile_sandboxed_component(&plugin_name, path, bytes)?; - let ticker = EpochTicker::start(engine.clone()); - let pre = bindings::MetricPluginPre::new(instance_pre).map_err(|error| { - PluginHostError::Instantiate { - name: plugin_name.clone(), - path: path.to_path_buf(), - reason: error.to_string(), - } - })?; - let mut store = new_limited_store(&engine, limits); - let bindings = pre - .instantiate(&mut store) - .map_err(|error| map_host_trap(&plugin_name, path, None, limits, &store, error))?; - let api = bindings.codeint_plugin_metric(); - arm_call_deadline(&mut store, limits); - let key = api.call_key(&mut store).map_err(|error| { - map_host_trap(&plugin_name, path, Some("key"), limits, &store, error) + let mut component = instantiate_sandboxed_component( + &plugin_name, + path, + bytes, + limits, + METRIC_CONTRACT, + bindings::MetricPluginPre::new, + |pre, store| pre.instantiate(store), + )?; + let api = component.bindings.codeint_plugin_metric(); + arm_call_deadline(&mut component.store, limits); + let key = api.call_key(&mut component.store).map_err(|error| { + map_host_trap( + &plugin_name, + path, + Some("key"), + limits, + &component.store, + error, + ) })?; validate_metric_key(&plugin_name, &key)?; - arm_call_deadline(&mut store, limits); - let display_name = api.call_name(&mut store).map_err(|error| { - map_host_trap(&plugin_name, path, Some("name"), limits, &store, error) - })?; - arm_call_deadline(&mut store, limits); - let description = api.call_description(&mut store).map_err(|error| { + arm_call_deadline(&mut component.store, limits); + let display_name = api.call_name(&mut component.store).map_err(|error| { map_host_trap( &plugin_name, path, - Some("description"), + Some("name"), limits, - &store, + &component.store, error, ) })?; + arm_call_deadline(&mut component.store, limits); + let description = api + .call_description(&mut component.store) + .map_err(|error| { + map_host_trap( + &plugin_name, + path, + Some("description"), + limits, + &component.store, + error, + ) + })?; let display_name = if display_name.trim().is_empty() { key.clone() } else { display_name }; - let peak_memory_bytes = AtomicUsize::new(store.data().peak_memory_bytes()); + let peak_memory_bytes = AtomicUsize::new(component.store.data().peak_memory_bytes()); Ok(WasmMetricPlugin { plugin_name, limits, key, display_name, description, - engine, - _ticker: ticker, - pre, - pool: Mutex::new(vec![MetricPluginInstance { store, bindings }]), + engine: component.engine, + _ticker: component.ticker, + pre: component.pre, + pool: Mutex::new(vec![MetricPluginInstance { + store: component.store, + bindings: component.bindings, + }]), peak_memory_bytes, }) } @@ -244,7 +264,10 @@ fn to_guest_code_model(model: &CodeModel) -> guest_metric::CodeModel { ImportResolution::Resolved(path) => { guest_language::Resolution::Resolved(path.as_str().to_owned()) } - ImportResolution::External => guest_language::Resolution::External, + ImportResolution::External(package) => { + guest_language::Resolution::External(package.clone()) + } + ImportResolution::Builtin => guest_language::Resolution::Builtin, ImportResolution::Unresolved { reason } => { guest_language::Resolution::Unresolved(reason.clone()) } @@ -276,6 +299,8 @@ fn to_guest_file_model(model: &FileModel) -> guest_language::FileModel { end_line: function.end_line, decision_points: function.decision_points, source_lines: function.source_lines, + name: function.name.clone(), + cognitive_complexity: function.cognitive_complexity, }) .collect(), tokens: model diff --git a/crates/plugin-host/tests/conformance.rs b/crates/plugin-host/tests/conformance.rs index 2c0b11e..18e5e3f 100644 --- a/crates/plugin-host/tests/conformance.rs +++ b/crates/plugin-host/tests/conformance.rs @@ -203,7 +203,7 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF specifier: (*specifier).to_owned(), }) .collect(); - let resolutions = plugin.resolve_imports(&repo_paths, valid_manifest, requests); + let resolutions = plugin.resolve_imports(&repo_paths, valid_manifest.clone(), requests); assert_eq!( resolutions.len(), fixture.import_requests.len(), @@ -214,10 +214,13 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF Resolution::Resolved(fixture.expected_resolved_target.to_owned()), "{label}: first import resolves" ); - assert_eq!( - resolutions[1], - Resolution::External, - "{label}: second import is external" + assert!( + matches!( + resolutions[1], + Resolution::External(_) | Resolution::Builtin + ), + "{label}: second import is external or builtin, got {:?}", + resolutions[1] ); assert!( matches!(resolutions[2], Resolution::Unresolved(_)), @@ -225,6 +228,15 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF resolutions[2] ); + let _deps = plugin.declared_dependencies(valid_manifest.clone()); + let entry_points = plugin.entry_points(&repo_paths, valid_manifest); + for entry in &entry_points { + assert!( + fixture.repository_paths.contains(&entry.as_str()), + "{label}: entry_points returned {entry:?} outside repository_paths" + ); + } + let ranges = plugin .reference_ranges() .unwrap_or_else(|error| panic!("{label}: reference_ranges failed: {error}")); diff --git a/crates/plugin-host/tests/fixtures/sample-plugin/src/lib.rs b/crates/plugin-host/tests/fixtures/sample-plugin/src/lib.rs index c12f58d..aedf9bd 100644 --- a/crates/plugin-host/tests/fixtures/sample-plugin/src/lib.rs +++ b/crates/plugin-host/tests/fixtures/sample-plugin/src/lib.rs @@ -156,8 +156,8 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, FlaggedLine, Function, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, - Resolution, SourceSet, Token, TokenKind, WorkspaceError, + DeclaredDep, DepKind, FileModel, FlaggedLine, Function, Guest, ImportRequest, LowerError, + Manifest, ReferenceRange, Resolution, SourceSet, Token, TokenKind, WorkspaceError, }; struct SampleMiniPlugin; @@ -186,9 +186,7 @@ fn strip_comment(line: &str) -> &str { fn source_set_of(path: &str) -> SourceSet { let file_name = path.rsplit('/').next().unwrap_or(path); - if file_name.ends_with(".test.mini") - || path.split('/').any(|segment| segment == "tests") - { + if file_name.ends_with(".test.mini") || path.split('/').any(|segment| segment == "tests") { SourceSet::Test } else { SourceSet::Production @@ -252,7 +250,10 @@ fn tokenize_line(code: &str, line_number: u32, is_import: bool, tokens: &mut Vec let text = &code[start..index]; let kind = if is_import { TokenKind::ImportOrExport - } else if matches!(text, "fn" | "if" | "else" | "while" | "return" | "let" | "pass") { + } else if matches!( + text, + "fn" | "if" | "else" | "while" | "return" | "let" | "pass" + ) { TokenKind::Other } else { TokenKind::Identifier @@ -284,14 +285,116 @@ fn extract_import_specifier(trimmed: &str) -> Option { Some(inner.to_string()) } +fn extract_function_name(trimmed: &str) -> Option { + let rest = trimmed.strip_prefix("fn")?.trim_start(); + let end = rest + .find(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_') + .unwrap_or(rest.len()); + let name = &rest[..end]; + if name.is_empty() { + None + } else { + Some(name.to_string()) + } +} + struct OpenFunction { slot: usize, + name: Option, line: u32, brace_depth: u32, decision_points: u32, + cognitive_complexity: u32, source_lines: u32, } +fn is_workspace_directive(trimmed: &str) -> bool { + ["dep:", "dev-dep:", "opt-dep:", "entry:"] + .iter() + .any(|prefix| trimmed.starts_with(prefix)) +} + +fn push_function_header( + trimmed: &str, + line_number: u32, + functions: &mut Vec, + stack: &mut Vec, +) { + let opens_fn = + (trimmed.starts_with("fn ") || trimmed.starts_with("fn(")) && trimmed.contains('{'); + if !opens_fn { + return; + } + let slot = functions.len(); + let name = extract_function_name(trimmed); + functions.push(Function { + line: line_number, + end_line: line_number, + decision_points: 0, + source_lines: 0, + name: name.clone(), + cognitive_complexity: 0, + }); + stack.push(OpenFunction { + slot, + name, + line: line_number, + brace_depth: 0, + decision_points: 0, + cognitive_complexity: 0, + source_lines: 0, + }); +} + +fn update_function_stack( + code: &str, + trimmed: &str, + line_number: u32, + functions: &mut [Function], + stack: &mut Vec, +) -> Result<(), LowerError> { + let Some(current) = stack.last_mut() else { + if code.contains('}') { + return Err(LowerError::Unparsable(format!( + "unmatched closing brace at line {line_number}" + ))); + } + return Ok(()); + }; + current.source_lines += 1; + let nesting = current.brace_depth.saturating_sub(1); + for word in trimmed.split(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_') { + if matches!(word, "if" | "while") { + current.decision_points += 1; + current.cognitive_complexity += 1 + nesting; + } + } + for byte in code.bytes() { + if byte == b'{' { + current.brace_depth += 1; + } else if byte == b'}' { + if current.brace_depth == 0 { + return Err(LowerError::Unparsable(format!( + "unmatched closing brace at line {line_number}" + ))); + } + current.brace_depth -= 1; + } + } + if current.brace_depth == 0 { + let finished = stack.pop().unwrap(); + functions[finished.slot] = Function { + line: finished.line, + end_line: line_number, + decision_points: finished.decision_points, + source_lines: finished.source_lines, + name: finished.name, + cognitive_complexity: finished.cognitive_complexity, + }; + } + Ok(()) +} + impl Guest for SampleMiniPlugin { fn extensions() -> Vec { vec!["mini".to_string()] @@ -344,62 +447,14 @@ impl Guest for SampleMiniPlugin { } tokenize_line(code, line_number, is_import, &mut tokens); - - let opens_fn = trimmed.starts_with("fn ") && trimmed.contains('{'); - if opens_fn { - let slot = functions.len(); - functions.push(Function { - line: line_number, - end_line: line_number, - decision_points: 0, - source_lines: 0, - }); - stack.push(OpenFunction { - slot, - line: line_number, - brace_depth: 0, - decision_points: 0, - source_lines: 0, - }); - } - - if let Some(current) = stack.last_mut() { - current.source_lines += 1; - for word in trimmed.split(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_') { - if matches!(word, "if" | "while") { - current.decision_points += 1; - } - } - for byte in code.bytes() { - if byte == b'{' { - current.brace_depth += 1; - } else if byte == b'}' { - if current.brace_depth == 0 { - return Err(LowerError::Unparsable(format!( - "unmatched closing brace at line {line_number}" - ))); - } - current.brace_depth -= 1; - } - } - if current.brace_depth == 0 { - let finished = stack.pop().unwrap(); - functions[finished.slot] = Function { - line: finished.line, - end_line: line_number, - decision_points: finished.decision_points, - source_lines: finished.source_lines, - }; - } - } else if code.contains('}') { - return Err(LowerError::Unparsable(format!( - "unmatched closing brace at line {line_number}" - ))); - } + push_function_header(trimmed, line_number, &mut functions, &mut stack); + update_function_stack(code, trimmed, line_number, &mut functions, &mut stack)?; } if !stack.is_empty() { - return Err(LowerError::Unparsable("unclosed function block".to_string())); + return Err(LowerError::Unparsable( + "unclosed function block".to_string(), + )); } Ok(FileModel { @@ -427,7 +482,8 @@ impl Guest for SampleMiniPlugin { } for line in manifest.text.lines() { let trimmed = line.trim(); - if trimmed.is_empty() || trimmed.starts_with('#') { + if trimmed.is_empty() || trimmed.starts_with('#') || is_workspace_directive(trimmed) + { continue; } if let Some(message) = trimmed.strip_prefix("INVALID:") { @@ -450,8 +506,11 @@ impl Guest for SampleMiniPlugin { requests .into_iter() .map(|request| { + if request.specifier.starts_with("std:") { + return Resolution::Builtin; + } if !request.specifier.starts_with("./") { - return Resolution::External; + return Resolution::External(request.specifier); } let relative = request.specifier.trim_start_matches("./"); let folder = match request.importer.rsplit_once('/') { @@ -479,6 +538,55 @@ impl Guest for SampleMiniPlugin { .collect() } + fn declared_dependencies(manifests: Vec) -> Vec { + let mut deps = Vec::new(); + for manifest in manifests { + if manifest.path != "mini.workspace" { + continue; + } + for line in manifest.text.lines() { + let trimmed = line.trim(); + let entry = if let Some(name) = trimmed.strip_prefix("dep:") { + Some((name.trim(), DepKind::Runtime)) + } else if let Some(name) = trimmed.strip_prefix("dev-dep:") { + Some((name.trim(), DepKind::Dev)) + } else { + trimmed + .strip_prefix("opt-dep:") + .map(|name| (name.trim(), DepKind::Optional)) + }; + if let Some((name, kind)) = entry + && !name.is_empty() + { + deps.push(DeclaredDep { + package_root: String::new(), + name: name.to_string(), + kind, + }); + } + } + } + deps + } + + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + let mut entries = Vec::new(); + for manifest in manifests { + if manifest.path != "mini.workspace" { + continue; + } + for line in manifest.text.lines() { + if let Some(entry) = line.trim().strip_prefix("entry:") { + let candidate = entry.trim(); + if repository_paths.iter().any(|path| path == candidate) { + entries.push(candidate.to_string()); + } + } + } + } + entries + } + fn reference_ranges() -> Vec { vec![ReferenceRange { metric: "erosion".to_string(), diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.lock b/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.lock index 71ec695..4145a66 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.lock +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.lock @@ -87,6 +87,22 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" +[[package]] +name = "legacy-v0-1-0-language-plugin" +version = "0.1.0" +dependencies = [ + "probe-runtime", + "wit-bindgen", +] + +[[package]] +name = "legacy-v0-1-0-metric-plugin" +version = "0.1.0" +dependencies = [ + "probe-runtime", + "wit-bindgen", +] + [[package]] name = "log" version = "0.4.35" diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml index 62122b3..9c7462d 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml @@ -8,6 +8,8 @@ members = [ "loop-language", "memory-hog-language", "loop-metric", + "legacy-v0-1-0-language", + "legacy-v0-1-0-metric", ] [workspace.package] diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/clock-reader/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/clock-reader/src/lib.rs index f7b9f05..d8d1c1b 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/clock-reader/src/lib.rs +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/clock-reader/src/lib.rs @@ -31,7 +31,7 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, WorkspaceError, }; @@ -65,6 +65,14 @@ impl Guest for ClockReaderPlugin { Vec::new() } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn reference_ranges() -> Vec { Vec::new() } diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/file-reader/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/file-reader/src/lib.rs index 85486a2..ab20732 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/file-reader/src/lib.rs +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/file-reader/src/lib.rs @@ -26,7 +26,7 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, WorkspaceError, }; @@ -59,6 +59,14 @@ impl Guest for FileReaderPlugin { Vec::new() } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn reference_ranges() -> Vec { Vec::new() } diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/Cargo.toml new file mode 100644 index 0000000..4cd7a46 --- /dev/null +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "legacy-v0-1-0-language-plugin" +version.workspace = true +edition.workspace = true +publish.workspace = true + +[lib] +crate-type = ["cdylib"] + +[dependencies] +probe-runtime.workspace = true +wit-bindgen.workspace = true diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/src/lib.rs new file mode 100644 index 0000000..3b68e81 --- /dev/null +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-language/src/lib.rs @@ -0,0 +1,150 @@ +#![no_std] + +extern crate alloc; +extern crate probe_runtime; + +use alloc::string::{String, ToString}; +use alloc::vec; +use alloc::vec::Vec; + +wit_bindgen::generate!({ + world: "language-plugin", + inline: " + package codeint:plugin@0.1.0; + + interface language { + record function { + line: u32, + end-line: u32, + decision-points: u32, + source-lines: u32, + } + + enum token-kind { + identifier, + literal, + other, + import-or-export, + } + + enum source-set { + production, + test, + generated, + vendored, + } + + record token { + kind: token-kind, + text-hash: u64, + line: u32, + } + + record flagged-line { + line: u32, + rule: string, + } + + record file-model { + source-set: source-set, + source-lines: u32, + functions: list, + tokens: list, + flagged-lines: list, + runtime-imports: list, + } + + record import-request { + importer: string, + specifier: string, + } + + variant resolution { + resolved(string), + external, + unresolved(string), + } + + variant lower-error { + unparsable(string), + unsupported-file(string), + too-large, + declaration-only, + } + + record manifest { + path: string, + text: string, + } + + record workspace-error { + path: string, + message: string, + } + + record reference-range { + metric: string, + low: f64, + high: f64, + source: string, + } + + extensions: func() -> list; + lower: func(path: string, text: string) -> result; + manifest-paths: func(repository-paths: list) -> list; + workspace-packages: func(manifests: list) -> result, workspace-error>; + resolve-imports: func(repository-paths: list, manifests: list, requests: list) -> list; + reference-ranges: func() -> list; + } + + world language-plugin { + export language; + } + ", +}); + +use exports::codeint::plugin::language::{ + FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, + WorkspaceError, +}; + +struct LegacyLanguagePlugin; + +export!(LegacyLanguagePlugin); + +impl Guest for LegacyLanguagePlugin { + fn extensions() -> Vec { + vec!["legacy".to_string()] + } + + fn lower(_path: String, _text: String) -> Result { + Ok(FileModel { + source_set: SourceSet::Production, + source_lines: 0, + functions: Vec::new(), + tokens: Vec::new(), + flagged_lines: Vec::new(), + runtime_imports: Vec::new(), + }) + } + + fn manifest_paths(_repository_paths: Vec) -> Vec { + Vec::new() + } + + fn workspace_packages(_manifests: Vec) -> Result, WorkspaceError> { + Ok(Vec::new()) + } + + fn resolve_imports( + _repository_paths: Vec, + _manifests: Vec, + _requests: Vec, + ) -> Vec { + Vec::new() + } + + fn reference_ranges() -> Vec { + Vec::new() + } +} diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/Cargo.toml new file mode 100644 index 0000000..835c4c9 --- /dev/null +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "legacy-v0-1-0-metric-plugin" +version.workspace = true +edition.workspace = true +publish.workspace = true + +[lib] +crate-type = ["cdylib"] + +[dependencies] +probe-runtime.workspace = true +wit-bindgen.workspace = true diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/src/lib.rs new file mode 100644 index 0000000..949b65d --- /dev/null +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-1-0-metric/src/lib.rs @@ -0,0 +1,137 @@ +#![no_std] + +extern crate alloc; +extern crate probe_runtime; + +use alloc::string::{String, ToString}; +use alloc::vec::Vec; + +wit_bindgen::generate!({ + world: "metric-plugin", + inline: " + package codeint:plugin@0.1.0; + + interface language { + record function { + line: u32, + end-line: u32, + decision-points: u32, + source-lines: u32, + } + + enum token-kind { + identifier, + literal, + other, + import-or-export, + } + + enum source-set { + production, + test, + generated, + vendored, + } + + record token { + kind: token-kind, + text-hash: u64, + line: u32, + } + + record flagged-line { + line: u32, + rule: string, + } + + record file-model { + source-set: source-set, + source-lines: u32, + functions: list, + tokens: list, + flagged-lines: list, + runtime-imports: list, + } + + variant resolution { + resolved(string), + external, + unresolved(string), + } + } + + interface metric { + use language.{file-model, resolution}; + + record source-file { + path: string, + model: file-model, + } + + record runtime-import { + importer: string, + specifier: string, + resolution: resolution, + } + + record code-model { + files: list, + runtime-imports: list, + workspace-packages: list, + } + + record finding { + id: string, + path: string, + line: u32, + end-line: option, + message: string, + } + + record measurement { + ratio: f64, + numerator: f64, + denominator: f64, + findings: list, + } + + key: func() -> string; + name: func() -> string; + description: func() -> string; + measure: func(model: code-model) -> measurement; + } + + world metric-plugin { + export metric; + } + ", +}); + +use exports::codeint::plugin::metric::{CodeModel, Guest, Measurement}; + +struct LegacyMetricPlugin; + +export!(LegacyMetricPlugin); + +impl Guest for LegacyMetricPlugin { + fn key() -> String { + "legacy_metric".to_string() + } + + fn name() -> String { + "Legacy metric".to_string() + } + + fn description() -> String { + "Test Metric plugin targeting codeint:plugin@0.1.0".to_string() + } + + fn measure(_model: CodeModel) -> Measurement { + Measurement { + ratio: 0.0, + numerator: 0.0, + denominator: 0.0, + findings: Vec::new(), + } + } +} diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/loop-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/loop-language/src/lib.rs index 01ccb0a..96774ad 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/loop-language/src/lib.rs +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/loop-language/src/lib.rs @@ -13,8 +13,8 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, - WorkspaceError, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + SourceSet, WorkspaceError, }; struct LoopLanguagePlugin; @@ -58,6 +58,14 @@ impl Guest for LoopLanguagePlugin { Vec::new() } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn reference_ranges() -> Vec { Vec::new() } diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/memory-hog-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/memory-hog-language/src/lib.rs index 2c4edac..a2d2736 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/memory-hog-language/src/lib.rs +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/memory-hog-language/src/lib.rs @@ -13,8 +13,8 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, - WorkspaceError, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + SourceSet, WorkspaceError, }; struct MemoryHogLanguagePlugin; @@ -67,6 +67,14 @@ impl Guest for MemoryHogLanguagePlugin { Vec::new() } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn reference_ranges() -> Vec { Vec::new() } diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/socket-opener/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/socket-opener/src/lib.rs index e0ec236..e783d68 100644 --- a/crates/plugin-host/tests/fixtures/sandbox-probes/socket-opener/src/lib.rs +++ b/crates/plugin-host/tests/fixtures/sandbox-probes/socket-opener/src/lib.rs @@ -65,7 +65,7 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, WorkspaceError, }; @@ -101,6 +101,14 @@ impl Guest for SocketOpenerPlugin { Vec::new() } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn reference_ranges() -> Vec { Vec::new() } diff --git a/crates/plugin-host/tests/load.rs b/crates/plugin-host/tests/load.rs index 0e4e38b..ed001b4 100644 --- a/crates/plugin-host/tests/load.rs +++ b/crates/plugin-host/tests/load.rs @@ -6,7 +6,7 @@ use std::sync::OnceLock; use codeint_config::{ PluginDeclaration, PluginHostConfig, PluginKind, PluginLimits, PluginSource, Sha256Digest, }; -use codeint_model::language::{Function, ImportRequest, Resolution}; +use codeint_model::language::{DeclaredDep, DepKind, Function, ImportRequest, Resolution}; use codeint_model::{ CodeModel, FileModel, LanguagePlugin, LowerError, Manifest, MetricPlugin, MetricPluginError, RepoPath, SourceFile, SourceSet, Token, TokenKind, token_text_hash, @@ -90,7 +90,9 @@ fn loads_sample_external_plugin_with_zero_capabilities_and_valid_hash() { assert_eq!(model.source_set, SourceSet::Production); assert_eq!(model.source_lines, 6); assert_eq!(model.functions.len(), 1); + assert_eq!(model.functions[0].name.as_deref(), Some("main")); assert_eq!(model.functions[0].decision_points, 1); + assert_eq!(model.functions[0].cognitive_complexity, 1); assert_eq!(model.runtime_imports, vec!["./util"]); assert_eq!(model.flagged_lines.len(), 1); assert_eq!(model.flagged_lines[0].rule, "redundant-pass"); @@ -126,13 +128,18 @@ fn loads_sample_external_plugin_with_zero_capabilities_and_valid_hash() { importer: "src/app.mini".to_owned(), specifier: "external-pkg".to_owned(), }, + ImportRequest { + importer: "src/app.mini".to_owned(), + specifier: "std:io".to_owned(), + }, ], ); assert_eq!( resolutions, vec![ Resolution::Resolved("src/util.mini".to_owned()), - Resolution::External, + Resolution::External("external-pkg".to_owned()), + Resolution::Builtin, ] ); } @@ -205,12 +212,16 @@ fn loads_sample_external_metric_plugin_with_zero_capabilities_and_measures_code_ end_line: 3, decision_points: 0, source_lines: 3, + name: Some("brief".to_owned()), + cognitive_complexity: 0, }, Function { line: 5, end_line: 18, decision_points: 1, source_lines: 14, + name: Some("verbose".to_owned()), + cognitive_complexity: 1, }, ], tokens: vec![Token { @@ -559,3 +570,153 @@ fn built_in_and_sample_plugins_fit_comfortably_within_default_limits() { assert!(metric_peak < defaults.memory_bytes()); assert!(metric_elapsed.as_millis() < u128::from(defaults.timeout_ms)); } + +#[test] +fn verifies_0_2_0_contract_fields_and_methods_across_wasm_boundary() { + let wasm_path = sample_plugin_wasm(); + let declaration = declaration_for("sample-mini", wasm_path); + let plugin = load_language_plugin(Path::new("."), &declaration, &PluginHostConfig::default()) + .expect("0.2.0 sample plugin loads"); + + let lowered = plugin + .lower( + &RepoPath::new("src/main.mini").expect("valid repo path"), + "fn outer(x) {\n if x {\n while x {\n return x\n }\n }\n}\nfn() {\n return 1\n}\n", + ) + .expect("lowers named and anonymous functions"); + assert_eq!(lowered.functions.len(), 2); + assert_eq!(lowered.functions[0].name.as_deref(), Some("outer")); + assert_eq!(lowered.functions[0].decision_points, 2); + assert_eq!(lowered.functions[0].cognitive_complexity, 3); + assert_eq!(lowered.functions[1].name, None); + assert_eq!(lowered.functions[1].cognitive_complexity, 0); + + let repo_paths = vec![ + RepoPath::new("mini.workspace").expect("valid repo path"), + RepoPath::new("src/main.mini").expect("valid repo path"), + RepoPath::new("src/util.mini").expect("valid repo path"), + ]; + let manifests = vec![Manifest { + path: "mini.workspace".to_owned(), + text: "packages/core\ndep:serde\ndev-dep:testkit\nopt-dep:extras\nentry:src/main.mini\nentry:src/missing.mini\n".to_owned(), + }]; + + assert_eq!( + plugin.declared_dependencies(manifests.clone()), + vec![ + DeclaredDep { + package_root: String::new(), + name: "serde".to_owned(), + kind: DepKind::Runtime, + }, + DeclaredDep { + package_root: String::new(), + name: "testkit".to_owned(), + kind: DepKind::Dev, + }, + DeclaredDep { + package_root: String::new(), + name: "extras".to_owned(), + kind: DepKind::Optional, + }, + ] + ); + assert_eq!( + plugin.entry_points(&repo_paths, manifests.clone()), + vec!["src/main.mini"] + ); + assert_eq!( + plugin.resolve_imports( + &repo_paths, + manifests, + vec![ + ImportRequest { + importer: "src/main.mini".to_owned(), + specifier: "./util".to_owned(), + }, + ImportRequest { + importer: "src/main.mini".to_owned(), + specifier: "serde".to_owned(), + }, + ImportRequest { + importer: "src/main.mini".to_owned(), + specifier: "std:fs".to_owned(), + }, + ImportRequest { + importer: "src/main.mini".to_owned(), + specifier: "./missing".to_owned(), + }, + ], + ), + vec![ + Resolution::Resolved("src/util.mini".to_owned()), + Resolution::External("serde".to_owned()), + Resolution::Builtin, + Resolution::Unresolved("cannot find src/missing.mini".to_owned()), + ] + ); +} + +fn assert_incompatible_contract_error( + error: PluginHostError, + plugin_name: &str, + expected_interface: &str, + found_interface: &str, +) { + assert!( + matches!( + &error, + PluginHostError::IncompatibleContractVersion { + name, + expected, + found, + .. + } if name == plugin_name + && *expected == expected_interface + && found == found_interface + ), + "expected IncompatibleContractVersion, got: {error}" + ); + let rendered = error.to_string(); + assert!( + rendered.contains(plugin_name) + && rendered.contains(found_interface) + && rendered.contains(expected_interface) + && rendered.contains("rebuild"), + "expected actionable version-mismatch error, got: {rendered}" + ); +} + +#[test] +fn rejects_v0_1_0_language_plugin_with_actionable_version_mismatch_error() { + let wasm_path = sandbox_probe_wasm("legacy_v0_1_0_language_plugin.wasm"); + let declaration = declaration_for("legacy-lang", &wasm_path); + + let error = load_language_plugin(Path::new("."), &declaration, &PluginHostConfig::default()) + .err() + .expect("0.1.0 Language plugin must be rejected by 0.2.0 host"); + + assert_incompatible_contract_error( + error, + "legacy-lang", + "codeint:plugin/language@0.2.0", + "codeint:plugin/language@0.1.0", + ); +} + +#[test] +fn rejects_v0_1_0_metric_plugin_with_actionable_version_mismatch_error() { + let wasm_path = sandbox_probe_wasm("legacy_v0_1_0_metric_plugin.wasm"); + let declaration = declaration_with_kind("legacy-metric", PluginKind::Metric, &wasm_path); + + let error = load_metric_plugin(Path::new("."), &declaration, &PluginHostConfig::default()) + .err() + .expect("0.1.0 Metric plugin must be rejected by 0.2.0 host"); + + assert_incompatible_contract_error( + error, + "legacy-metric", + "codeint:plugin/metric@0.2.0", + "codeint:plugin/metric@0.1.0", + ); +} diff --git a/docs/plugins.md b/docs/plugins.md index 075f9b7..24cb702 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -6,11 +6,11 @@ This guide explains how to build, hash, declare, and test a Language plugin and ## Versioned WIT contract -codeint defines its Plugin contract in `package codeint:plugin@0.1.0`. +codeint defines its Plugin contract in `package codeint:plugin@0.2.0`. Two WIT files hold the contract: -- [wit/language.wit](../wit/language.wit) defines `codeint:plugin/language@0.1.0` and the `language-plugin` world. -- [wit/metric.wit](../wit/metric.wit) defines `codeint:plugin/metric@0.1.0` and the `metric-plugin` world. +- [wit/language.wit](../wit/language.wit) defines `codeint:plugin/language@0.2.0` and the `language-plugin` world. +- [wit/metric.wit](../wit/metric.wit) defines `codeint:plugin/metric@0.2.0` and the `metric-plugin` world. The `metric` interface reuses `file-model` and `resolution` from `language`. A Language plugin exports `language` and lowers source files into the Code model. @@ -70,8 +70,8 @@ wit_bindgen::generate!({ }); use exports::codeint::plugin::language::{ - FileModel, FlaggedLine, Function, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, - Resolution, SourceSet, Token, TokenKind, WorkspaceError, + DeclaredDep, DepKind, FileModel, FlaggedLine, Function, Guest, ImportRequest, LowerError, + Manifest, ReferenceRange, Resolution, SourceSet, Token, TokenKind, WorkspaceError, }; struct SampleMiniPlugin; @@ -81,23 +81,25 @@ export!(SampleMiniPlugin); ### Required functions -Implement all six functions on `Guest`: +Implement all eight functions on `Guest`: | Function | Responsibility | | -------- | -------------- | | `extensions() -> list` | Return file extensions without a leading dot, such as `["mini"]`. | -| `lower(path, text) -> result` | Lower one file into its `source-set`, `source-lines`, `functions`, `tokens`, `flagged-lines`, and `runtime-imports`. Return `declaration-only`, `unparsable`, `unsupported-file`, or `too-large` on error. | +| `lower(path, text) -> result` | Lower one file into its `source-set`, `source-lines`, `functions` (each with optional `name` and nesting-weighted `cognitive-complexity`), `tokens`, `flagged-lines`, and `runtime-imports`. Return `declaration-only`, `unparsable`, `unsupported-file`, or `too-large` on error. | | `manifest-paths(repository-paths) -> list` | Select manifest paths from `repository-paths` that the host reads once on the Plugin's behalf. | | `workspace-packages(manifests) -> result, workspace-error>` | Return relative Workspace package roots from the manifest contents, or an empty list for a single-package repository. | -| `resolve-imports(repository-paths, manifests, requests) -> list` | Return one `resolved`, `external`, or `unresolved` entry per request, in request order. | +| `resolve-imports(repository-paths, manifests, requests) -> list` | Return one `resolved(string)`, `external(string)` (carrying the canonical package name), `builtin` (for standard-library or runtime built-ins), or `unresolved(string)` entry per request, in request order. | +| `declared-dependencies(manifests) -> list` | Extract manifest-declared external dependencies (`package-root`, normalized `name`, and `kind` of `runtime`, `dev`, or `optional`). | +| `entry-points(repository-paths, manifests) -> list` | Discover standard entry-point source files from `repository-paths` and `manifests`, returning only paths from `repository-paths`. | | `reference-ranges() -> list` | Return published Reference ranges for this language, at most one per Metric. | Follow these invariants in `lower`: -- Keep `functions` sorted by start `line` (`line >= 1` and `line <= end-line`). +- Keep `functions` sorted by start `line` (`line >= 1` and `line <= end-line`), with `name` set to `none` for anonymous lambdas or closures. - Keep `tokens` sorted by 1-based `line`, with 64-bit FNV-1a `text-hash` values of each token's UTF-8 text. - Produce identical `source-lines` and `functions` for LF and CRLF line endings. -- Do not count nested functions' decision points or source lines in their enclosing function. +- Do not count nested functions' decision points, cognitive complexity, or source lines in their enclosing function. ### Compile the sample Language plugin @@ -261,7 +263,8 @@ The suite verifies: - Ordered `functions` and `tokens`, valid 1-based line spans, and non-empty Flagged line rules. - `manifest-paths` returning only paths from `repository-paths`. - `workspace-packages` parsing valid manifests and returning `WorkspaceError::Manifest` on invalid manifests. -- `resolve-imports` returning one `Resolved`, `External`, or `Unresolved` result per request in request order. +- `resolve-imports` returning one `Resolved`, `External`, `Builtin`, or `Unresolved` result per request in request order. +- `declared-dependencies` returning manifest-declared dependencies and `entry-points` returning only paths from `repository-paths`. - `reference-ranges` returning valid ranges. - Safe concurrent `lower` calls across threads. @@ -301,10 +304,10 @@ cargo test --locked -p codeint-cli --test plugins The WIT package declaration carries a Semantic Versioning number: ```wit -package codeint:plugin@0.1.0; +package codeint:plugin@0.2.0; ``` -This version identifies the exported interfaces `codeint:plugin/language@0.1.0` and `codeint:plugin/metric@0.1.0` in the compiled WebAssembly component. +This version identifies the exported interfaces `codeint:plugin/language@0.2.0` and `codeint:plugin/metric@0.2.0` in the compiled WebAssembly component. ### Compatibility rules @@ -319,6 +322,6 @@ This version identifies the exported interfaces `codeint:plugin/language@0.1.0` `wasmtime::component::bindgen!` binds the codeint host to the exact WIT interface version compiled into the binary. At load time, wasmtime checks that the component's exported interface name and version match what the host expects. -- A Plugin built against an incompatible WIT version fails to instantiate with exit code 2, and the error names the mismatched interface version. +- A Plugin built against an incompatible WIT version (such as `codeint:plugin@0.1.0`) fails at load time with exit code 2, naming the plugin, its found interface version, the required `0.2.0` interface version, and how to rebuild it. - Rebuild the Plugin against the updated `wit/` files and update its `sha256` in `codeint.json` when upgrading to a breaking WIT version. - Never silently mutate an existing released WIT version in place; every breaking change gets a new version number. diff --git a/plugins/languages/dart/src/lib.rs b/plugins/languages/dart/src/lib.rs index e75d065..9179e00 100644 --- a/plugins/languages/dart/src/lib.rs +++ b/plugins/languages/dart/src/lib.rs @@ -11,8 +11,8 @@ mod workspaces; use std::collections::BTreeSet; use codeint_model::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, Token, - TokenKind, WorkspaceError, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + Token, TokenKind, WorkspaceError, }; use codeint_model::token_text_hash; @@ -71,6 +71,10 @@ fn lower_dart(path: &str, text: &str) -> Result { } impl Guest for Dart { + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + fn workspace_packages(manifests: Vec) -> Result, WorkspaceError> { workspaces::discover(&manifests) } @@ -91,6 +95,10 @@ impl Guest for Dart { lower_dart(&path, &text) } + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn extensions() -> Vec { vec!["dart".to_owned()] } diff --git a/plugins/languages/dart/src/resolution.rs b/plugins/languages/dart/src/resolution.rs index decdd34..3477ce9 100644 --- a/plugins/languages/dart/src/resolution.rs +++ b/plugins/languages/dart/src/resolution.rs @@ -55,7 +55,7 @@ fn resolve_one( ) -> Resolution { let spec = request.specifier.as_str(); if spec.starts_with("dart:") { - return Resolution::External; + return Resolution::Builtin; } if let Some(pkg_rest) = spec.strip_prefix("package:") { return resolve_package_uri(files, packages, &request.importer, pkg_rest); @@ -70,10 +70,10 @@ fn resolve_package_uri( pkg_rest: &str, ) -> Resolution { let Some((pkg_name, rel_path)) = pkg_rest.split_once('/') else { - return Resolution::External; + return Resolution::External(String::new()); }; let Some(pkg_dir) = packages.get(pkg_name) else { - return Resolution::External; + return Resolution::External(String::new()); }; let candidate = if pkg_dir.is_empty() { format!("lib/{rel_path}") @@ -82,7 +82,7 @@ fn resolve_package_uri( }; if files.contains(&candidate) { if candidate == importer { - Resolution::External + Resolution::External(String::new()) } else { Resolution::Resolved(candidate) } diff --git a/plugins/languages/dart/tests/conformance.rs b/plugins/languages/dart/tests/conformance.rs index 145de3b..7f5f719 100644 --- a/plugins/languages/dart/tests/conformance.rs +++ b/plugins/languages/dart/tests/conformance.rs @@ -30,6 +30,17 @@ fn dart_contract_basics() { ); } +fn func(line: u32, end_line: u32, decision_points: u32, source_lines: u32) -> Function { + Function { + line, + end_line, + decision_points, + source_lines, + name: None, + cognitive_complexity: 0, + } +} + #[test] fn dart_functions_and_decisions() { let model = lower( @@ -43,23 +54,7 @@ fn dart_functions_and_decisions() { }\n", ) .unwrap(); - assert_eq!( - model.functions, - [ - Function { - line: 1, - end_line: 7, - decision_points: 6, - source_lines: 7 - }, - Function { - line: 5, - end_line: 5, - decision_points: 1, - source_lines: 1 - }, - ] - ); + assert_eq!(model.functions, [func(1, 7, 6, 7), func(5, 5, 1, 1)]); } #[test] @@ -106,8 +101,8 @@ fn dart_directives_and_resolution() { ); assert_eq!(res[0], Resolution::Resolved("lib/u.dart".into())); assert_eq!(res[1], Resolution::Resolved("lib/h.dart".into())); - assert_eq!(res[2], Resolution::External); - assert_eq!(res[3], Resolution::External); + assert_eq!(res[2], Resolution::Builtin); + assert_eq!(res[3], Resolution::External(String::new())); assert!(matches!(res[4], Resolution::Unresolved(_))); } diff --git a/plugins/languages/php/src/lib.rs b/plugins/languages/php/src/lib.rs index f2433f6..f95671e 100644 --- a/plugins/languages/php/src/lib.rs +++ b/plugins/languages/php/src/lib.rs @@ -11,8 +11,8 @@ mod workspaces; use std::collections::BTreeSet; use codeint_model::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, Token, - TokenKind, WorkspaceError, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + Token, TokenKind, WorkspaceError, }; use codeint_model::token_text_hash; @@ -97,4 +97,12 @@ impl Guest for Php { ) -> Vec { resolution::resolve_batch(&repository_paths, &manifests, &requests) } + + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } } diff --git a/plugins/languages/php/src/resolution.rs b/plugins/languages/php/src/resolution.rs index e50e821..27bdb6b 100644 --- a/plugins/languages/php/src/resolution.rs +++ b/plugins/languages/php/src/resolution.rs @@ -47,7 +47,7 @@ impl PhpResolver { match request.specifier.split_once(':') { Some(("use", ns_path)) => self.resolve_psr4(&request.importer, ns_path), Some(("req", req_path)) => self.resolve_require(&request.importer, req_path), - _ => Resolution::External, + _ => Resolution::External(String::new()), } } @@ -63,13 +63,13 @@ impl PhpResolver { let rel = rest.replace('\\', "/"); if let Some(hit) = self.first_matching_file(&rule.dirs, &rel) { return if hit == importer { - Resolution::External + Resolution::External(String::new()) } else { Resolution::Resolved(hit) }; } } - Resolution::External + Resolution::External(String::new()) } fn first_matching_file(&self, dirs: &[String], rel: &str) -> Option { diff --git a/plugins/languages/php/tests/conformance.rs b/plugins/languages/php/tests/conformance.rs index 382b1ef..5c0d791 100644 --- a/plugins/languages/php/tests/conformance.rs +++ b/plugins/languages/php/tests/conformance.rs @@ -75,12 +75,16 @@ fn php_decision_points_cover_control_flow_match_and_arrow_functions() { end_line: 16, decision_points: 8, source_lines: 15, + name: None, + cognitive_complexity: 0, }, Function { line: 10, end_line: 10, decision_points: 1, source_lines: 1, + name: None, + cognitive_complexity: 0, }, ] ); @@ -197,6 +201,6 @@ fn php_resolver_handles_psr4_and_static_require() { Resolution::Resolved("app/Models/Order.php".to_owned()) ); assert_eq!(out[1], Resolution::Resolved("app/helpers.php".to_owned())); - assert_eq!(out[2], Resolution::External); + assert_eq!(out[2], Resolution::External(String::new())); assert!(matches!(out[3], Resolution::Unresolved(_))); } diff --git a/plugins/languages/python/src/lib.rs b/plugins/languages/python/src/lib.rs index b061293..5916f89 100644 --- a/plugins/languages/python/src/lib.rs +++ b/plugins/languages/python/src/lib.rs @@ -9,8 +9,8 @@ mod source_set; mod workspaces; use codeint_model::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, Token, - TokenKind, WorkspaceError, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + Token, TokenKind, WorkspaceError, }; use codeint_model::scan::build_reference_ranges; use codeint_model::token_text_hash; @@ -52,6 +52,14 @@ impl Guest for Python { resolution::resolve_all(&repository_paths, &manifests, &requests) } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn lower(path: String, text: String) -> Result { if !path.ends_with(".py") { return Err(LowerError::UnsupportedFile(format!( diff --git a/plugins/languages/python/src/resolution.rs b/plugins/languages/python/src/resolution.rs index 62a3d46..3551769 100644 --- a/plugins/languages/python/src/resolution.rs +++ b/plugins/languages/python/src/resolution.rs @@ -74,11 +74,11 @@ fn resolve_one( } if let Some(target) = module_map.get(specifier) { if target == importer { - return Resolution::External; + return Resolution::External(String::new()); } return Resolution::Resolved(target.clone()); } - Resolution::External + Resolution::External(String::new()) } fn resolve_relative(py_files: &HashSet, importer: &str, specifier: &str) -> Resolution { @@ -107,7 +107,7 @@ fn resolve_relative(py_files: &HashSet, importer: &str, specifier: &str) for candidate in candidates { if py_files.contains(&candidate) { if candidate == importer { - return Resolution::External; + return Resolution::External(String::new()); } return Resolution::Resolved(candidate); } diff --git a/plugins/languages/python/tests/conformance.rs b/plugins/languages/python/tests/conformance.rs index 5ccd9ed..9e6bfed 100644 --- a/plugins/languages/python/tests/conformance.rs +++ b/plugins/languages/python/tests/conformance.rs @@ -56,6 +56,8 @@ fn python_functions_decisions_and_source_sets() { end_line: 10, decision_points: 4, source_lines: 10, + name: None, + cognitive_complexity: 0, } ); assert_eq!(model.functions[1].decision_points, 1); @@ -143,7 +145,7 @@ fn python_imports_type_checking_resolution_and_workspaces() { resolutions[1], Resolution::Resolved("src/demo/utils.py".into()) ); - assert_eq!(resolutions[2], Resolution::External); + assert_eq!(resolutions[2], Resolution::External(String::new())); assert!(matches!(resolutions[3], Resolution::Unresolved(_))); let packages = Python diff --git a/plugins/languages/rust/src/functions.rs b/plugins/languages/rust/src/functions.rs index 1aa23fe..1c85547 100644 --- a/plugins/languages/rust/src/functions.rs +++ b/plugins/languages/rust/src/functions.rs @@ -227,6 +227,8 @@ impl FunctionCollector<'_> { end_line, decision_points, source_lines, + name: None, + cognitive_complexity: 0, }); } } diff --git a/plugins/languages/rust/src/lib.rs b/plugins/languages/rust/src/lib.rs index 790e5f9..10f2c5e 100644 --- a/plugins/languages/rust/src/lib.rs +++ b/plugins/languages/rust/src/lib.rs @@ -12,8 +12,8 @@ mod workspaces; use std::collections::BTreeSet; use codeint_model::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, - WorkspaceError, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + SourceSet, WorkspaceError, }; use crate::cfg_test::excluded_cfg_test_lines; @@ -65,6 +65,14 @@ impl Guest for Rust { }) } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn manifest_paths(repository_paths: Vec) -> Vec { manifest_paths(&repository_paths) } diff --git a/plugins/languages/rust/src/resolution.rs b/plugins/languages/rust/src/resolution.rs index fd0d4d9..db655ab 100644 --- a/plugins/languages/rust/src/resolution.rs +++ b/plugins/languages/rust/src/resolution.rs @@ -47,14 +47,14 @@ impl RustResolver { if let Some(use_path) = request.specifier.strip_prefix(USE_PREFIX) { return self.resolve_use(&request.importer, use_path); } - Resolution::External + Resolution::External(String::new()) } fn resolve_mod(&self, importer: &str, mod_name: &str) -> Resolution { let base_dir = module_child_dir(importer); match self.find_module_file(&base_dir, &[mod_name]) { Some(target) if target != importer => Resolution::Resolved(target), - Some(_) => Resolution::External, + Some(_) => Resolution::External(String::new()), None => Resolution::Unresolved(format!( "no module file found for `mod {mod_name}` from {importer}" )), @@ -64,15 +64,15 @@ impl RustResolver { fn resolve_use(&self, importer: &str, use_path: &str) -> Resolution { let segments: Vec<&str> = use_path.split("::").filter(|s| !s.is_empty()).collect(); let Some(&first) = segments.first() else { - return Resolution::External; + return Resolution::External(String::new()); }; if STD_CRATES.contains(&first) { - return Resolution::External; + return Resolution::Builtin; } match first { "crate" => { let Some(src_dir) = self.crate_src_dir(importer) else { - return Resolution::External; + return Resolution::External(String::new()); }; self.resolve_longest_module(importer, &src_dir, &segments[1..]) } @@ -91,11 +91,11 @@ impl RustResolver { return self .resolve_dir_to_file(¤t) .filter(|target| target != importer) - .map_or(Resolution::External, Resolution::Resolved); + .map_or_else(|| Resolution::External(String::new()), Resolution::Resolved); } self.resolve_longest_module(importer, ¤t, &segments[idx..]) } - _ => Resolution::External, + _ => Resolution::External(String::new()), } } @@ -108,7 +108,7 @@ impl RustResolver { for len in (1..=segments.len()).rev() { if let Some(target) = self.find_module_file(base_dir, &segments[..len]) { return if target == importer { - Resolution::External + Resolution::External(String::new()) } else { Resolution::Resolved(target) }; @@ -119,7 +119,7 @@ impl RustResolver { { return Resolution::Resolved(root_file); } - Resolution::External + Resolution::External(String::new()) } fn find_module_file(&self, base_dir: &str, segments: &[&str]) -> Option { diff --git a/plugins/languages/rust/tests/conformance.rs b/plugins/languages/rust/tests/conformance.rs index f78540f..5483038 100644 --- a/plugins/languages/rust/tests/conformance.rs +++ b/plugins/languages/rust/tests/conformance.rs @@ -73,12 +73,16 @@ fn counts_decision_points_and_nested_functions_separately() { end_line: 16, decision_points: 7, source_lines: 16, + name: None, + cognitive_complexity: 0, }, Function { line: 7, end_line: 9, decision_points: 2, source_lines: 3, + name: None, + cognitive_complexity: 0, }, ] ); @@ -251,8 +255,8 @@ fn resolves_intra_crate_mod_and_use_imports_and_marks_external_crates() { Resolution::Resolved("src/beta/mod.rs".to_owned()), Resolution::Resolved("src/beta/child.rs".to_owned()), Resolution::Resolved("src/alpha.rs".to_owned()), - Resolution::External, - Resolution::External, + Resolution::Builtin, + Resolution::External(String::new()), ] ); } diff --git a/plugins/languages/ts/src/functions.rs b/plugins/languages/ts/src/functions.rs index 0291722..3d02b5b 100644 --- a/plugins/languages/ts/src/functions.rs +++ b/plugins/languages/ts/src/functions.rs @@ -117,6 +117,8 @@ impl FunctionCollector<'_> { self.code_lines .count_between(first_line_index, last_line_index), ), + name: None, + cognitive_complexity: 0, }); } diff --git a/plugins/languages/ts/src/lib.rs b/plugins/languages/ts/src/lib.rs index 81da2d3..c40cc53 100644 --- a/plugins/languages/ts/src/lib.rs +++ b/plugins/languages/ts/src/lib.rs @@ -13,7 +13,7 @@ mod workspaces; use std::collections::BTreeSet; use codeint_model::language::{ - FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, + DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, WorkspaceError, }; use oxc_allocator::Allocator; @@ -74,6 +74,14 @@ impl Guest for TypeScriptAndJavaScript { .collect() } + fn declared_dependencies(_manifests: Vec) -> Vec { + Vec::new() + } + + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + Vec::new() + } + fn reference_ranges() -> Vec { [ ("erosion", 0.352, 0.600), diff --git a/plugins/languages/ts/src/resolution.rs b/plugins/languages/ts/src/resolution.rs index 0ae812d..b2a3f84 100644 --- a/plugins/languages/ts/src/resolution.rs +++ b/plugins/languages/ts/src/resolution.rs @@ -76,26 +76,35 @@ impl ProjectResolver { pub(crate) fn resolve(&self, request: &ImportRequest) -> Resolution { let specifier = request.specifier.as_str(); - if specifier.starts_with('/') { - return Resolution::Unresolved(format!( - "{specifier:?} is an absolute path, which depends on the machine" - )); - } - if is_relative(specifier) && leaves_the_repository(&request.importer, specifier) { - return Resolution::Unresolved(format!("{specifier:?} leads outside the repository")); - } - if is_bun_builtin(specifier) { - return Resolution::External; + if let Some(early) = precheck_specifier(&request.importer, specifier) { + return early; } let importer = snapshot::absolute(&request.importer); - let resolved = match self.resolver.resolve_file(&importer, specifier) { + let resolved = self.resolve_with_fallback(&importer, specifier); + self.classify_resolution(&importer, specifier, resolved) + } + + fn resolve_with_fallback( + &self, + importer: &std::path::Path, + specifier: &str, + ) -> Result { + match self.resolver.resolve_file(importer, specifier) { Err(error) if is_project_configuration_error(&error) => { importer.parent().map_or(Err(error), |folder| { self.resolver.resolve(folder, specifier) }) } result => result, - }; + } + } + + fn classify_resolution( + &self, + importer: &std::path::Path, + specifier: &str, + resolved: Result, + ) -> Resolution { match resolved { Ok(resolution) => snapshot::repository_path(resolution.path()).map_or_else( || { @@ -106,8 +115,10 @@ impl ProjectResolver { }, Resolution::Resolved, ), - Err(ResolveError::Builtin { .. }) => Resolution::External, - Err(_) if self.names_an_outside_module(&importer, specifier) => Resolution::External, + Err(ResolveError::Builtin { .. }) => Resolution::Builtin, + Err(_) if self.names_an_outside_module(importer, specifier) => { + Resolution::External(package_name(specifier).to_owned()) + } Err(ResolveError::NotFound(_)) => { Resolution::Unresolved(format!("no file of the repository matches {specifier:?}")) } @@ -133,6 +144,20 @@ impl ProjectResolver { } } +fn precheck_specifier(importer: &str, specifier: &str) -> Option { + if specifier.starts_with('/') { + return Some(Resolution::Unresolved(format!( + "{specifier:?} is an absolute path, which depends on the machine" + ))); + } + if is_relative(specifier) && leaves_the_repository(importer, specifier) { + return Some(Resolution::Unresolved(format!( + "{specifier:?} leads outside the repository" + ))); + } + is_bun_builtin(specifier).then_some(Resolution::Builtin) +} + fn is_project_configuration_error(error: &ResolveError) -> bool { matches!( error, diff --git a/plugins/languages/ts/tests/conformance.rs b/plugins/languages/ts/tests/conformance.rs index c73c598..181d0fe 100644 --- a/plugins/languages/ts/tests/conformance.rs +++ b/plugins/languages/ts/tests/conformance.rs @@ -324,6 +324,8 @@ fn function(line: u32, end_line: u32, decision_points: u32, source_lines: u32) - end_line, decision_points, source_lines, + name: None, + cognitive_complexity: 0, } } @@ -1166,10 +1168,18 @@ fn a_relative_specifier_resolves_to_the_first_matching_file_in_typescript_order( #[test] fn a_bare_specifier_names_a_module_outside_the_repository() { - for specifier in ["react", "@scope/package/sub", "node:path", "fs"] { + for (specifier, expected) in [ + ("react", Resolution::External("react".to_owned())), + ( + "@scope/package/sub", + Resolution::External("@scope/package".to_owned()), + ), + ("node:path", Resolution::Builtin), + ("fs", Resolution::Builtin), + ] { assert_eq!( resolve(&["src/main.ts"], "src/main.ts", specifier), - Resolution::External, + expected, "{specifier}" ); } @@ -1216,7 +1226,7 @@ fn resolutions_come_back_one_per_request_in_request_order() { resolutions, [ resolved("b.ts"), - Resolution::External, + Resolution::External("react".to_owned()), resolved("a.ts"), Resolution::Unresolved("no file of the repository matches \"./c\"".to_owned()), ] @@ -1314,10 +1324,17 @@ fn a_path_alias_without_a_matching_file_is_unresolved_and_other_bare_specifiers_ matches!(&missing, Resolution::Unresolved(reason) if reason.contains("@/views/missing")), "{missing:?}" ); - for specifier in ["react", "@scope/package", "node:fs"] { + for (specifier, expected) in [ + ("react", Resolution::External("react".to_owned())), + ( + "@scope/package", + Resolution::External("@scope/package".to_owned()), + ), + ("node:fs", Resolution::Builtin), + ] { assert_eq!( resolve_in_project(&ALIASED_PROJECT, "src/main.ts", specifier), - Resolution::External, + expected, "{specifier}" ); } @@ -1336,7 +1353,7 @@ fn a_tsconfig_that_does_not_include_the_importer_does_not_alias_its_imports() { assert_eq!( resolve_in_project(&files, "scripts/build.ts", "@/util"), - Resolution::External + Resolution::External("@/util".to_owned()) ); } @@ -1357,7 +1374,7 @@ fn imports_still_resolve_when_a_tsconfig_extends_a_config_outside_the_repository ); assert_eq!( resolve_in_project(&files, "src/main.ts", "react"), - Resolution::External + Resolution::External("react".to_owned()) ); } @@ -1428,7 +1445,7 @@ fn a_named_package_outside_the_declared_workspaces_is_not_linked() { for specifier in ["scripts", "retired"] { assert_eq!( resolve_in_project(&files, "packages/app/src/main.ts", specifier), - Resolution::External, + Resolution::External(specifier.to_owned()), "{specifier}" ); } @@ -1448,7 +1465,7 @@ fn a_named_package_in_a_repository_without_workspaces_is_not_linked() { assert_eq!( resolve_in_project(&files, "src/main.ts", "demo"), - Resolution::External + Resolution::External("demo".to_owned()) ); } @@ -1911,7 +1928,7 @@ fn bun_builtins_resolve_as_external_even_with_catch_all_tsconfig_paths() { ("src/db.ts", "bun:test"), ], ); - assert_eq!(resolutions, vec![Resolution::External; 3]); + assert_eq!(resolutions, vec![Resolution::Builtin; 3]); } #[test] diff --git a/wit/language.wit b/wit/language.wit index 0fc146c..2ba8096 100644 --- a/wit/language.wit +++ b/wit/language.wit @@ -1,6 +1,6 @@ /// The Plugin interface of codeint. /// A change that breaks a Plugin built against this version needs a new version. -package codeint:plugin@0.1.0; +package codeint:plugin@0.2.0; /// The interface a Language plugin exports: the file extensions it reads, and the Code model of each such file. interface language { @@ -15,6 +15,10 @@ interface language { decision-points: u32, /// The source lines of the function, not counting lines of nested functions. source-lines: u32, + /// The optional name of the function or method; `none` for anonymous lambdas and closures. + name: option, + /// The nesting-weighted cognitive complexity of the function, not counting nested functions. + cognitive-complexity: u32, } /// What a token is to clone detection, by the rules of the Language plugin. @@ -94,12 +98,34 @@ interface language { variant resolution { /// The import names this file of the repository, relative to the root, with forward slashes. resolved(string), - /// The import names a module outside the repository, such as a package or a built-in module. - external, + /// The import names a third-party package outside the repository; the payload is the canonical package name. + external(string), + /// The import names a standard-library or runtime built-in module. + builtin, /// The import should name a file of the repository, but none matches; the payload says why. unresolved(string), } + /// How a package manifest declares an external dependency. + enum dep-kind { + /// A dependency required at runtime in production. + runtime, + /// A dependency used only during development or testing. + dev, + /// An optional or peer dependency. + optional, + } + + /// One external dependency declared in a package manifest. + record declared-dep { + /// The package root folder relative to the repository root, with forward slashes, or empty for the repository root. + package-root: string, + /// The normalized package name as declared by the manifest. + name: string, + /// Whether the dependency is declared as runtime, dev, or optional. + kind: dep-kind, + } + /// Why a Language plugin cannot lower a file. variant lower-error { /// The file does not parse; the payload is the parser's message. @@ -136,7 +162,7 @@ interface language { /// `text` is the whole file. lower: func(path: string, text: string) -> result; - /// Chooses the files of one repository snapshot that the host reads once and passes to `workspace-packages` and `resolve-imports`, because a Plugin cannot read files. + /// Chooses the files of one repository snapshot that the host reads once and passes to `workspace-packages`, `resolve-imports`, `declared-dependencies`, and `entry-points`, because a Plugin cannot read files. /// `repository-paths` lists every file of the snapshot, relative to the root, with forward slashes. /// The result names only paths from `repository-paths`, such as each `package.json` and `tsconfig.json` file. manifest-paths: func(repository-paths: list) -> list; @@ -152,6 +178,17 @@ interface language { /// `manifests` holds each file that `manifest-paths` chose, with its text. /// The result holds one resolution per request, in request order. resolve-imports: func(repository-paths: list, manifests: list, requests: list) -> list; + + /// Extracts external dependencies declared in the selected manifests. + /// `manifests` holds each file that `manifest-paths` chose, with its text. + declared-dependencies: func(manifests: list) -> list; + + /// Discovers standard entry-point source files from the repository paths and selected manifests. + /// `repository-paths` lists every file of the snapshot, relative to the root, with forward slashes. + /// `manifests` holds each file that `manifest-paths` chose, with its text. + /// Every returned path must come from `repository-paths`. + entry-points: func(repository-paths: list, manifests: list) -> list; + /// The published typical value of one Metric for codebases in the language of the Language plugin. record reference-range { /// The Metric, by its key in the report: `erosion`, `verbosity`, `duplication`, or `import_cycles`. diff --git a/wit/metric.wit b/wit/metric.wit index 371ac14..f000874 100644 --- a/wit/metric.wit +++ b/wit/metric.wit @@ -1,4 +1,4 @@ -package codeint:plugin@0.1.0; +package codeint:plugin@0.2.0; /// The interface a Metric plugin exports: metadata for one Metric and a function that measures a Code model. interface metric { From aa30584109aa8e6056a0284dd1e3f0d849bace65 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 11:33:39 +0800 Subject: [PATCH 2/5] feat: extract manifest entry points across built-in language plugins Implement entry_points(repository_paths, manifests) for the TypeScript/JavaScript, Rust, Python, PHP, and Dart built-in Language plugins to extract standard manifest-declared entry files from package.json, Cargo.toml, pyproject.toml, composer.json, and pubspec.yaml. Return only existing repository-relative paths present in repository_paths, deduplicated and sorted deterministically, returning an empty list cleanly when no standard entry points are declared or when a manifest is malformed. Closes #198 --- plugins/languages/dart/src/entry_points.rs | 110 ++++++++ plugins/languages/dart/src/lib.rs | 5 +- plugins/languages/dart/tests/entry_points.rs | 67 +++++ plugins/languages/php/src/entry_points.rs | 52 ++++ plugins/languages/php/src/lib.rs | 5 +- plugins/languages/php/tests/entry_points.rs | 69 +++++ plugins/languages/python/src/entry_points.rs | 245 ++++++++++++++++++ plugins/languages/python/src/lib.rs | 5 +- .../languages/python/tests/entry_points.rs | 80 ++++++ plugins/languages/rust/src/entry_points.rs | 142 ++++++++++ plugins/languages/rust/src/lib.rs | 9 +- plugins/languages/rust/tests/entry_points.rs | 93 +++++++ plugins/languages/ts/src/entry_points.rs | 238 +++++++++++++++++ plugins/languages/ts/src/lib.rs | 5 +- plugins/languages/ts/tests/entry_points.rs | 125 +++++++++ 15 files changed, 1238 insertions(+), 12 deletions(-) create mode 100644 plugins/languages/dart/src/entry_points.rs create mode 100644 plugins/languages/dart/tests/entry_points.rs create mode 100644 plugins/languages/php/src/entry_points.rs create mode 100644 plugins/languages/php/tests/entry_points.rs create mode 100644 plugins/languages/python/src/entry_points.rs create mode 100644 plugins/languages/python/tests/entry_points.rs create mode 100644 plugins/languages/rust/src/entry_points.rs create mode 100644 plugins/languages/rust/tests/entry_points.rs create mode 100644 plugins/languages/ts/src/entry_points.rs create mode 100644 plugins/languages/ts/tests/entry_points.rs diff --git a/plugins/languages/dart/src/entry_points.rs b/plugins/languages/dart/src/entry_points.rs new file mode 100644 index 0000000..1f65977 --- /dev/null +++ b/plugins/languages/dart/src/entry_points.rs @@ -0,0 +1,110 @@ +use std::collections::{BTreeMap, BTreeSet, HashSet}; + +use codeint_model::language::Manifest; +use codeint_model::scan::normalize_relative_path; +use serde::Deserialize; + +use crate::workspaces::PUBSPEC_MANIFEST; + +#[derive(Deserialize)] +struct PubspecEntryPoints { + name: Option, + executables: Option>>, +} + +pub(crate) fn discover(repository_paths: &[String], manifests: &[Manifest]) -> Vec { + let dart_files: HashSet<&str> = repository_paths + .iter() + .map(String::as_str) + .filter(|path| path.ends_with(".dart")) + .collect(); + let suffix = format!("/{PUBSPEC_MANIFEST}"); + let mut results = BTreeSet::new(); + for manifest in manifests { + let base_dir = if manifest.path == PUBSPEC_MANIFEST { + "" + } else if let Some(dir) = manifest.path.strip_suffix(&suffix) { + dir + } else { + continue; + }; + if let Ok(Some(spec)) = serde_saphyr::from_str::>(&manifest.text) + { + spec.collect_entries(base_dir, repository_paths, &dart_files, &mut results); + } + } + results.into_iter().collect() +} + +impl PubspecEntryPoints { + fn collect_entries( + &self, + base_dir: &str, + repository_paths: &[String], + dart_files: &HashSet<&str>, + out: &mut BTreeSet, + ) { + if let Some(pkg) = self + .name + .as_deref() + .map(str::trim) + .filter(|n| !n.is_empty() && !n.contains('/') && !n.contains('\\') && *n != "..") + && let Some(lib_file) = normalize_relative_path(base_dir, &format!("lib/{pkg}.dart")) + && dart_files.contains(lib_file.as_str()) + { + out.insert(lib_file); + } + if let Some(executables) = self.executables.as_ref() { + collect_declared_executables(base_dir, executables, dart_files, out); + } + collect_bin_directory(base_dir, repository_paths, out); + } +} + +fn collect_declared_executables( + base_dir: &str, + executables: &BTreeMap>, + dart_files: &HashSet<&str>, + out: &mut BTreeSet, +) { + for (command, explicit) in executables { + let target = explicit + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .unwrap_or_else(|| command.trim()); + if target.is_empty() + || target.starts_with('/') + || target.contains('\\') + || target.split('/').any(|segment| segment == "..") + { + continue; + } + let rel = if target.ends_with(".dart") { + format!("bin/{target}") + } else { + format!("bin/{target}.dart") + }; + if let Some(candidate) = normalize_relative_path(base_dir, &rel) + && dart_files.contains(candidate.as_str()) + { + out.insert(candidate); + } + } +} + +fn collect_bin_directory(base_dir: &str, repository_paths: &[String], out: &mut BTreeSet) { + let prefix = if base_dir.is_empty() { + "bin/".to_owned() + } else { + format!("{base_dir}/bin/") + }; + for path in repository_paths { + if let Some(rest) = path.strip_prefix(&prefix) + && !rest.contains('/') + && rest.ends_with(".dart") + { + out.insert(path.clone()); + } + } +} diff --git a/plugins/languages/dart/src/lib.rs b/plugins/languages/dart/src/lib.rs index 9179e00..ee53540 100644 --- a/plugins/languages/dart/src/lib.rs +++ b/plugins/languages/dart/src/lib.rs @@ -1,5 +1,6 @@ #![forbid(unsafe_code)] +mod entry_points; mod functions; mod imports; mod lexer; @@ -95,8 +96,8 @@ impl Guest for Dart { lower_dart(&path, &text) } - fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { - Vec::new() + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + entry_points::discover(&repository_paths, &manifests) } fn extensions() -> Vec { diff --git a/plugins/languages/dart/tests/entry_points.rs b/plugins/languages/dart/tests/entry_points.rs new file mode 100644 index 0000000..91ee40b --- /dev/null +++ b/plugins/languages/dart/tests/entry_points.rs @@ -0,0 +1,67 @@ +use codeint_lang_dart::Dart; +use codeint_model::{LanguagePlugin, Manifest, RepoPath}; + +#[test] +fn extracts_executables_default_lib_and_bin_entries_from_pubspec() { + let mut paths = Vec::new(); + for raw in [ + "pubspec.yaml", + "lib/toolkit.dart", + "lib/src/internal.dart", + "lib/secret.dart", + "bin/run_cli.dart", + "bin/direct.dart", + "bin/extra.dart", + "bin/internal/helper.dart", + "packages/core/pubspec.yaml", + "packages/core/lib/core_lib.dart", + "packages/core/lib/src/impl.dart", + "packages/core/bin/serve.dart", + ] { + paths.push(RepoPath::new(raw).unwrap()); + } + + let root = Manifest { + path: "pubspec.yaml".into(), + text: "name: toolkit\nexecutables:\n cli: run_cli\n direct:\n missing_cmd: absent\n escape: ../lib/secret\n".into(), + }; + let core = Manifest { + path: "packages/core/pubspec.yaml".into(), + text: "name: core_lib\n".into(), + }; + + assert_eq!( + Dart.entry_points(&paths, vec![root, core]), + [ + "bin/direct.dart", + "bin/extra.dart", + "bin/run_cli.dart", + "lib/toolkit.dart", + "packages/core/bin/serve.dart", + "packages/core/lib/core_lib.dart", + ] + ); +} + +#[test] +fn returns_empty_when_pubspec_has_no_matching_entry_points_or_is_invalid() { + let paths = [ + RepoPath::new("pubspec.yaml").unwrap(), + RepoPath::new("lib/helper.dart").unwrap(), + ]; + let no_match = Dart.entry_points( + &paths, + vec![Manifest { + path: "pubspec.yaml".into(), + text: "name: app\n".into(), + }], + ); + let malformed = Dart.entry_points( + &paths, + vec![Manifest { + path: "pubspec.yaml".into(), + text: "executables: [\n".into(), + }], + ); + assert!(no_match.is_empty() && malformed.is_empty()); +} diff --git a/plugins/languages/php/src/entry_points.rs b/plugins/languages/php/src/entry_points.rs new file mode 100644 index 0000000..fee3bf8 --- /dev/null +++ b/plugins/languages/php/src/entry_points.rs @@ -0,0 +1,52 @@ +use std::collections::{BTreeSet, HashSet}; + +use codeint_model::language::Manifest; +use codeint_model::scan::normalize_relative_path; +use serde_json::Value; + +use crate::workspaces::COMPOSER_MANIFEST; + +pub(crate) fn extract(repository_paths: &[String], manifests: &[Manifest]) -> Vec { + let available: HashSet<&str> = repository_paths.iter().map(String::as_str).collect(); + let available_ref = &available; + let nested_suffix = format!("/{COMPOSER_MANIFEST}"); + let collected: BTreeSet = manifests + .iter() + .filter_map(|manifest| { + let dir = if manifest.path == COMPOSER_MANIFEST { + "" + } else { + manifest.path.strip_suffix(&nested_suffix)? + }; + let parsed = serde_json::from_str::(&manifest.text).ok()?; + Some( + bin_strings(parsed.get("bin")?) + .into_iter() + .filter_map(move |raw| resolve_composer_bin(dir, &raw, available_ref)), + ) + }) + .flatten() + .collect(); + collected.into_iter().collect() +} + +fn bin_strings(value: &Value) -> Vec { + match value { + Value::String(single) => vec![single.clone()], + Value::Array(items) => items + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(), + _ => Vec::new(), + } +} + +fn resolve_composer_bin(base_dir: &str, raw: &str, available: &HashSet<&str>) -> Option { + let trimmed = raw.trim(); + if trimmed.is_empty() || trimmed.starts_with('/') || trimmed.contains('\\') { + return None; + } + let normalized = normalize_relative_path(base_dir, trimmed)?; + (!normalized.is_empty() && available.contains(normalized.as_str())).then_some(normalized) +} diff --git a/plugins/languages/php/src/lib.rs b/plugins/languages/php/src/lib.rs index f95671e..a65faa7 100644 --- a/plugins/languages/php/src/lib.rs +++ b/plugins/languages/php/src/lib.rs @@ -1,5 +1,6 @@ #![forbid(unsafe_code)] +mod entry_points; mod functions; mod imports; mod lexer; @@ -102,7 +103,7 @@ impl Guest for Php { Vec::new() } - fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { - Vec::new() + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + entry_points::extract(&repository_paths, &manifests) } } diff --git a/plugins/languages/php/tests/entry_points.rs b/plugins/languages/php/tests/entry_points.rs new file mode 100644 index 0000000..a89af97 --- /dev/null +++ b/plugins/languages/php/tests/entry_points.rs @@ -0,0 +1,69 @@ +use codeint_lang_php::Php; +use codeint_model::{LanguagePlugin, Manifest, RepoPath}; + +#[test] +fn extracts_bin_entry_points_from_composer_manifests() { + let manifest = |path: &str, text: &str| Manifest { + path: path.into(), + text: text.into(), + }; + let repo_paths = [ + "composer.json", + "bin/console", + "bin/worker.php", + "src/Helper.php", + "packages/cli/composer.json", + "packages/cli/scripts/run.php", + "packages/tool/composer.json", + "packages/tool/tool.php", + ] + .map(|path| RepoPath::new(path).unwrap()); + + let manifests = vec![ + manifest( + "composer.json", + r#"{"name": "acme/app", "bin": ["bin/console", "./bin/worker.php", "bin/missing.php", "../outside.php", "/abs.php", "bin/console"]}"#, + ), + manifest( + "packages/cli/composer.json", + r#"{"name": "acme/cli", "bin": ["scripts/run.php"]}"#, + ), + manifest( + "packages/tool/composer.json", + r#"{"name": "acme/tool", "bin": "tool.php"}"#, + ), + ]; + + assert_eq!( + Php.entry_points(&repo_paths, manifests), + [ + "bin/console", + "bin/worker.php", + "packages/cli/scripts/run.php", + "packages/tool/tool.php", + ] + ); +} + +#[test] +fn returns_empty_when_composer_manifest_has_no_bin_or_is_invalid() { + let paths = [ + RepoPath::new("composer.json").unwrap(), + RepoPath::new("src/App.php").unwrap(), + ]; + let psr4_only = r#"{"name": "acme/lib", "autoload": {"psr-4": {"Acme\\": "src/"}}}"#; + let empty_count = [psr4_only, "{invalid"] + .into_iter() + .map(|body| { + Php.entry_points( + &paths, + vec![Manifest { + path: "composer.json".into(), + text: body.into(), + }], + ) + .len() + }) + .sum::(); + assert_eq!(empty_count, 0); +} diff --git a/plugins/languages/python/src/entry_points.rs b/plugins/languages/python/src/entry_points.rs new file mode 100644 index 0000000..9aa1f2f --- /dev/null +++ b/plugins/languages/python/src/entry_points.rs @@ -0,0 +1,245 @@ +use std::collections::{BTreeSet, HashSet}; + +use codeint_model::language::Manifest; +use codeint_model::scan::normalize_relative_path; + +pub(crate) fn discover(repository_paths: &[String], manifests: &[Manifest]) -> Vec { + let py_files: HashSet<&str> = repository_paths + .iter() + .map(String::as_str) + .filter(|path| path.ends_with(".py")) + .collect(); + let mut entries = BTreeSet::new(); + for (base_dir, doc) in parsed_pyprojects(manifests) { + let roots = package_search_roots(base_dir); + collect_script_entries(&doc, &roots, &py_files, &mut entries); + collect_declared_packages(&doc, base_dir, &py_files, &mut entries); + } + entries.into_iter().collect() +} + +fn parsed_pyprojects(manifests: &[Manifest]) -> Vec<(&str, toml::Value)> { + manifests + .iter() + .filter_map(|manifest| { + let dir = if manifest.path == "pyproject.toml" { + "" + } else { + manifest.path.strip_suffix("/pyproject.toml")? + }; + let doc = toml::from_str::(&manifest.text).ok()?; + Some((dir, doc)) + }) + .collect() +} + +fn package_search_roots(base_dir: &str) -> [String; 2] { + let src_root = if base_dir.is_empty() { + "src".to_owned() + } else { + format!("{base_dir}/src") + }; + [base_dir.to_owned(), src_root] +} + +fn collect_script_entries( + doc: &toml::Value, + roots: &[String], + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + if let Some(project) = doc.get("project") { + for section in ["scripts", "gui-scripts"] { + if let Some(table) = project.get(section).and_then(toml::Value::as_table) { + for spec in table.values().filter_map(toml::Value::as_str) { + resolve_module_spec(spec, roots, py_files, found); + } + } + } + if let Some(groups) = project.get("entry-points").and_then(toml::Value::as_table) { + for group in groups.values().filter_map(toml::Value::as_table) { + for spec in group.values().filter_map(toml::Value::as_str) { + resolve_module_spec(spec, roots, py_files, found); + } + } + } + } + collect_poetry_scripts(doc, roots, py_files, found); +} + +fn collect_poetry_scripts( + doc: &toml::Value, + roots: &[String], + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + let Some(scripts) = doc + .get("tool") + .and_then(|v| v.get("poetry")) + .and_then(|v| v.get("scripts")) + .and_then(toml::Value::as_table) + else { + return; + }; + for value in scripts.values() { + let spec = value.as_str().or_else(|| { + value + .get("callable") + .or_else(|| value.get("reference")) + .and_then(toml::Value::as_str) + }); + if let Some(target) = spec { + resolve_module_spec(target, roots, py_files, found); + } + } +} + +fn resolve_module_spec( + spec: &str, + roots: &[String], + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + let Some(rel_path) = module_spec_to_rel_path(spec) else { + return; + }; + for root in roots { + let Some(base) = normalize_relative_path(root, &rel_path) else { + continue; + }; + if base.is_empty() { + continue; + } + for candidate in [ + format!("{base}.py"), + format!("{base}/__init__.py"), + format!("{base}/__main__.py"), + ] { + if py_files.contains(candidate.as_str()) { + found.insert(candidate); + return; + } + } + } +} + +fn module_spec_to_rel_path(spec: &str) -> Option { + let module_part = spec + .trim() + .split(':') + .next()? + .split('[') + .next()? + .split_whitespace() + .next()? + .trim(); + if module_part.is_empty() || module_part.contains('/') || module_part.contains('\\') { + return None; + } + let segments: Vec<&str> = module_part.split('.').collect(); + if segments.iter().any(|seg| seg.is_empty() || *seg == "..") { + return None; + } + Some(segments.join("/")) +} + +fn collect_declared_packages( + doc: &toml::Value, + base_dir: &str, + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + let Some(tool) = doc.get("tool") else { + return; + }; + let setuptools = tool + .get("setuptools") + .and_then(|v| v.get("packages")) + .and_then(toml::Value::as_array); + let hatch = tool + .get("hatch") + .and_then(|v| v.get("build")) + .and_then(|v| v.get("targets")) + .and_then(|v| v.get("wheel")) + .and_then(|v| v.get("packages")) + .and_then(toml::Value::as_array); + for list in [setuptools, hatch].into_iter().flatten() { + for pkg in list.iter().filter_map(toml::Value::as_str) { + resolve_package_dir(base_dir, None, pkg, py_files, found); + } + } + collect_poetry_packages(tool, base_dir, py_files, found); +} + +fn collect_poetry_packages( + tool: &toml::Value, + base_dir: &str, + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + let Some(packages) = tool + .get("poetry") + .and_then(|v| v.get("packages")) + .and_then(toml::Value::as_array) + else { + return; + }; + for entry in packages { + if let Some(pkg) = entry.as_str() { + resolve_package_dir(base_dir, None, pkg, py_files, found); + } else if let Some(include) = entry.get("include").and_then(toml::Value::as_str) { + let from = entry.get("from").and_then(toml::Value::as_str); + resolve_package_dir(base_dir, from, include, py_files, found); + } + } +} + +fn resolve_package_dir( + base_dir: &str, + from: Option<&str>, + pkg: &str, + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + let trimmed = pkg.trim(); + if trimmed.is_empty() || trimmed.starts_with('/') || trimmed.contains('\\') { + return; + } + let rel_pkg = if trimmed.contains('/') { + trimmed.to_owned() + } else { + trimmed.replace('.', "/") + }; + for root in candidate_package_roots(base_dir, from, trimmed.contains('/')) { + if let Some(pkg_dir) = normalize_relative_path(&root, &rel_pkg) + && !pkg_dir.is_empty() + { + record_package_init_files(&pkg_dir, py_files, found); + } + } +} + +fn candidate_package_roots(base_dir: &str, from: Option<&str>, has_slash: bool) -> Vec { + if let Some(from_dir) = from { + return normalize_relative_path(base_dir, from_dir.trim()) + .into_iter() + .collect(); + } + if has_slash { + return vec![base_dir.to_owned()]; + } + package_search_roots(base_dir).into() +} + +fn record_package_init_files( + pkg_dir: &str, + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + for entry_file in ["__init__.py", "__main__.py"] { + let candidate = format!("{pkg_dir}/{entry_file}"); + if py_files.contains(candidate.as_str()) { + found.insert(candidate); + } + } +} diff --git a/plugins/languages/python/src/lib.rs b/plugins/languages/python/src/lib.rs index 5916f89..5ea9a58 100644 --- a/plugins/languages/python/src/lib.rs +++ b/plugins/languages/python/src/lib.rs @@ -1,5 +1,6 @@ #![forbid(unsafe_code)] +mod entry_points; mod functions; mod imports; mod lexer; @@ -56,8 +57,8 @@ impl Guest for Python { Vec::new() } - fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { - Vec::new() + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + entry_points::discover(&repository_paths, &manifests) } fn lower(path: String, text: String) -> Result { diff --git a/plugins/languages/python/tests/entry_points.rs b/plugins/languages/python/tests/entry_points.rs new file mode 100644 index 0000000..28e143a --- /dev/null +++ b/plugins/languages/python/tests/entry_points.rs @@ -0,0 +1,80 @@ +use codeint_lang_python::Python; +use codeint_model::{LanguagePlugin, Manifest, RepoPath}; + +#[test] +fn extracts_project_scripts_gui_scripts_entry_points_and_declared_packages() { + let snapshot: Vec = [ + "pyproject.toml", + "src/demo/cli.py", + "src/demo/pkg/__init__.py", + "demo/gui.py", + "demo/plugin.py", + "helper_pkg/__init__.py", + "packages/worker/pyproject.toml", + "packages/worker/src/worker/__init__.py", + "packages/worker/src/worker/__main__.py", + "packages/worker/src/worker/entry.py", + "packages/worker/src/worker/jobs.py", + "packages/poetry_app/pyproject.toml", + "packages/poetry_app/src/papp/__init__.py", + ] + .iter() + .map(|item| RepoPath::new(*item).unwrap()) + .collect(); + + let manifests = vec![ + Manifest { + path: "pyproject.toml".to_owned(), + text: "[project]\nname = \"demo\"\n[project.scripts]\napp-cli = \"demo.cli:main\"\npkg-cmd = \"demo.pkg:run [extra]\"\nmissing-cmd = \"demo.absent:run\"\n[project.gui-scripts]\napp-gui = \"demo.gui:launch\"\n[project.entry-points.\"demo.plugins\"]\next = \"demo.plugin:Plugin\"\n[tool.setuptools]\npackages = [\"helper_pkg\"]\n".to_owned(), + }, + Manifest { + path: "packages/worker/pyproject.toml".to_owned(), + text: "[project]\nname = \"worker\"\n[tool.poetry.scripts]\nrun-worker = \"worker.entry:start\"\njob-runner = { callable = \"worker.jobs:main\" }\n[tool.hatch.build.targets.wheel]\npackages = [\"src/worker\"]\n".to_owned(), + }, + Manifest { + path: "packages/poetry_app/pyproject.toml".to_owned(), + text: "[tool.poetry]\nname = \"papp\"\npackages = [{ include = \"papp\", from = \"src\" }]\n".to_owned(), + }, + ]; + + assert_eq!( + Python.entry_points(&snapshot, manifests), + [ + "demo/gui.py", + "demo/plugin.py", + "helper_pkg/__init__.py", + "packages/poetry_app/src/papp/__init__.py", + "packages/worker/src/worker/__init__.py", + "packages/worker/src/worker/__main__.py", + "packages/worker/src/worker/entry.py", + "packages/worker/src/worker/jobs.py", + "src/demo/cli.py", + "src/demo/pkg/__init__.py", + ] + ); +} + +#[test] +fn returns_empty_when_pyproject_declares_no_entry_points_or_is_invalid() { + let snapshot = [ + RepoPath::new("pyproject.toml").unwrap(), + RepoPath::new("webapp/__init__.py").unwrap(), + RepoPath::new("webapp/views.py").unwrap(), + ]; + let plain = Manifest { + path: "pyproject.toml".to_owned(), + text: "[project]\nname = \"webapp\"\n".to_owned(), + }; + let broken = Manifest { + path: "pyproject.toml".to_owned(), + text: "[project\nname =".to_owned(), + }; + assert_eq!( + Python.entry_points(&snapshot, vec![plain]), + Vec::::new() + ); + assert_eq!( + Python.entry_points(&snapshot, vec![broken]), + Vec::::new() + ); +} diff --git a/plugins/languages/rust/src/entry_points.rs b/plugins/languages/rust/src/entry_points.rs new file mode 100644 index 0000000..30a29ca --- /dev/null +++ b/plugins/languages/rust/src/entry_points.rs @@ -0,0 +1,142 @@ +use std::collections::{BTreeSet, HashSet}; + +use codeint_model::language::Manifest; +use codeint_model::scan::normalize_relative_path; +use serde::Deserialize; + +use crate::workspaces::CARGO_MANIFEST; + +#[derive(Deserialize)] +struct CargoTargets { + package: Option, + lib: Option, + #[serde(default)] + bin: Vec, +} + +#[derive(Deserialize)] +struct PackageMeta { + name: Option, + autolib: Option, + autobins: Option, +} + +#[derive(Deserialize)] +struct TargetSpec { + name: Option, + path: Option, +} + +pub(crate) fn entry_points(repository_paths: &[String], manifests: &[Manifest]) -> Vec { + let index = CrateTargetIndex { + all_paths: repository_paths, + present: repository_paths.iter().map(String::as_str).collect(), + }; + let mut targets = BTreeSet::new(); + let suffix = format!("/{CARGO_MANIFEST}"); + for manifest in manifests { + let base_dir = match manifest.path.as_str() { + CARGO_MANIFEST => "", + other => match other.strip_suffix(&suffix) { + Some(dir) => dir, + None => continue, + }, + }; + if let Ok(parsed) = toml::from_str::(&manifest.text) { + parsed.collect_into(&index, base_dir, &mut targets); + } + } + targets.into_iter().collect() +} + +struct CrateTargetIndex<'a> { + all_paths: &'a [String], + present: HashSet<&'a str>, +} + +impl CrateTargetIndex<'_> { + fn record(&self, base_dir: &str, rel: &str, out: &mut BTreeSet) -> bool { + let trimmed = rel.trim(); + if trimmed.is_empty() || trimmed.starts_with('/') || trimmed.contains('\\') { + return false; + } + let Some(candidate) = normalize_relative_path(base_dir, trimmed) else { + return false; + }; + if !candidate.is_empty() && self.present.contains(candidate.as_str()) { + out.insert(candidate); + true + } else { + false + } + } + + fn scan_auto_bins(&self, base_dir: &str, out: &mut BTreeSet) { + let prefix = if base_dir.is_empty() { + "src/bin/".to_owned() + } else { + format!("{base_dir}/src/bin/") + }; + for path in self.all_paths { + let Some(rest) = path.strip_prefix(&prefix) else { + continue; + }; + let is_top_level = !rest.contains('/') && rest.ends_with(".rs"); + let is_subdir_main = rest + .strip_suffix("/main.rs") + .is_some_and(|dir| !dir.is_empty() && !dir.contains('/')); + if is_top_level || is_subdir_main { + out.insert(path.clone()); + } + } + } +} + +impl CargoTargets { + fn collect_into( + &self, + index: &CrateTargetIndex<'_>, + base_dir: &str, + out: &mut BTreeSet, + ) { + let Some(package) = self.package.as_ref() else { + return; + }; + if let Some(explicit) = self.lib.as_ref().and_then(|spec| spec.path.as_deref()) { + index.record(base_dir, explicit, out); + } else if package.autolib != Some(false) { + index.record(base_dir, "src/lib.rs", out); + } + for bin in &self.bin { + if let Some(explicit) = bin.path.as_deref() { + index.record(base_dir, explicit, out); + } else if let Some(name) = bin.name.as_deref() { + record_named_bin(index, base_dir, package.name.as_deref(), name, out); + } + } + if package.autobins != Some(false) { + index.record(base_dir, "src/main.rs", out); + index.scan_auto_bins(base_dir, out); + } + } +} + +fn record_named_bin( + index: &CrateTargetIndex<'_>, + base_dir: &str, + package_name: Option<&str>, + bin_name: &str, + out: &mut BTreeSet, +) { + let direct = format!("src/bin/{bin_name}.rs"); + if index.record(base_dir, &direct, out) { + return; + } + let nested = format!("src/bin/{bin_name}/main.rs"); + if index.record(base_dir, &nested, out) { + return; + } + if package_name == Some(bin_name) { + index.record(base_dir, "src/main.rs", out); + } +} diff --git a/plugins/languages/rust/src/lib.rs b/plugins/languages/rust/src/lib.rs index 10f2c5e..390a539 100644 --- a/plugins/languages/rust/src/lib.rs +++ b/plugins/languages/rust/src/lib.rs @@ -1,6 +1,7 @@ #![forbid(unsafe_code)] mod cfg_test; +mod entry_points; mod functions; mod imports; mod resolution; @@ -69,10 +70,6 @@ impl Guest for Rust { Vec::new() } - fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { - Vec::new() - } - fn manifest_paths(repository_paths: Vec) -> Vec { manifest_paths(&repository_paths) } @@ -104,4 +101,8 @@ impl Guest for Rust { ], ) } + + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + entry_points::entry_points(&repository_paths, &manifests) + } } diff --git a/plugins/languages/rust/tests/entry_points.rs b/plugins/languages/rust/tests/entry_points.rs new file mode 100644 index 0000000..01dc717 --- /dev/null +++ b/plugins/languages/rust/tests/entry_points.rs @@ -0,0 +1,93 @@ +use codeint_lang_rust::Rust; +use codeint_model::{LanguagePlugin, Manifest, RepoPath}; + +#[test] +fn extracts_explicit_and_default_lib_and_bin_targets_from_cargo_manifests() { + let files: Vec = [ + "Cargo.toml", + "src/lib.rs", + "crates/core/Cargo.toml", + "crates/core/src/lib.rs", + "crates/core/src/main.rs", + "crates/core/src/helper.rs", + "crates/core/src/bin/tool.rs", + "crates/core/src/bin/worker/main.rs", + "crates/core/src/bin/worker/extra.rs", + "crates/custom/Cargo.toml", + "crates/custom/src/custom_lib.rs", + "crates/custom/src/cli_main.rs", + "crates/custom/src/bin/named.rs", + "crates/disabled/Cargo.toml", + "crates/disabled/src/lib.rs", + "crates/disabled/src/main.rs", + ] + .into_iter() + .map(|raw| RepoPath::new(raw).expect("valid repo path")) + .collect(); + + let manifests = [ + ("Cargo.toml", "[workspace]\nmembers = [\"crates/*\"]\n"), + ("crates/core/Cargo.toml", "[package]\nname = \"core\"\n"), + ( + "crates/custom/Cargo.toml", + "[package]\nname = \"custom\"\nautobins = false\n[lib]\npath = \"src/custom_lib.rs\"\n[[bin]]\nname = \"cli\"\npath = \"src/cli_main.rs\"\n[[bin]]\nname = \"named\"\n[[bin]]\nname = \"missing\"\npath = \"src/missing.rs\"\n", + ), + ( + "crates/disabled/Cargo.toml", + "[package]\nname = \"disabled\"\nautolib = false\nautobins = false\n", + ), + ] + .into_iter() + .map(|(path, text)| Manifest { + path: path.to_owned(), + text: text.to_owned(), + }) + .collect(); + + assert_eq!( + Rust.entry_points(&files, manifests), + [ + "crates/core/src/bin/tool.rs", + "crates/core/src/bin/worker/main.rs", + "crates/core/src/lib.rs", + "crates/core/src/main.rs", + "crates/custom/src/bin/named.rs", + "crates/custom/src/cli_main.rs", + "crates/custom/src/custom_lib.rs", + ] + ); +} + +#[test] +fn handles_root_crate_empty_targets_and_invalid_manifests() { + let root_files = [ + RepoPath::new("Cargo.toml").unwrap(), + RepoPath::new("src/lib.rs").unwrap(), + RepoPath::new("src/main.rs").unwrap(), + RepoPath::new("src/bin/extra.rs").unwrap(), + ]; + let root_manifest = Manifest { + path: "Cargo.toml".into(), + text: "[package]\nname = \"root_app\"\nautobins = false\n[[bin]]\nname = \"root_app\"\n[[bin]]\nname = \"escape\"\npath = \"../outside.rs\"\n[[bin]]\nname = \"abs\"\npath = \"/etc/passwd\"\n".into(), + }; + assert_eq!( + Rust.entry_points(&root_files, vec![root_manifest]), + ["src/lib.rs", "src/main.rs"] + ); + + let no_targets = [ + RepoPath::new("Cargo.toml").unwrap(), + RepoPath::new("src/helper.rs").unwrap(), + ]; + for text in [ + "[workspace]\nmembers = [\"crates/*\"]\n", + "[package]\nname = \"empty\"\n", + "[package\nname =", + ] { + let entry = Manifest { + path: "Cargo.toml".into(), + text: text.into(), + }; + assert!(Rust.entry_points(&no_targets, vec![entry]).is_empty()); + } +} diff --git a/plugins/languages/ts/src/entry_points.rs b/plugins/languages/ts/src/entry_points.rs new file mode 100644 index 0000000..f1b8db0 --- /dev/null +++ b/plugins/languages/ts/src/entry_points.rs @@ -0,0 +1,238 @@ +use std::collections::{BTreeSet, HashSet}; + +use codeint_model::language::Manifest; +use codeint_model::scan::normalize_relative_path; +use serde_json::Value; + +use crate::EXTENSIONS; +use crate::workspaces::PACKAGE_MANIFEST; + +const OUTPUT_TO_SOURCE_ALIASES: [(&str, &[&str]); 4] = [ + (".js", &[".ts", ".tsx"]), + (".jsx", &[".tsx"]), + (".mjs", &[".mts"]), + (".cjs", &[".cts"]), +]; + +pub(crate) fn entry_points(repository_paths: &[String], manifests: &[Manifest]) -> Vec { + let mut finder = TsEntryFinder::new(repository_paths); + for manifest in manifests { + finder.scan_manifest(manifest); + } + finder.entries.into_iter().collect() +} + +struct TsEntryFinder<'a> { + paths: &'a [String], + file_set: HashSet<&'a str>, + entries: BTreeSet, +} + +impl<'a> TsEntryFinder<'a> { + fn new(paths: &'a [String]) -> TsEntryFinder<'a> { + TsEntryFinder { + paths, + file_set: paths.iter().map(String::as_str).collect(), + entries: BTreeSet::new(), + } + } + + fn scan_manifest(&mut self, manifest: &Manifest) { + let base_dir = if manifest.path == PACKAGE_MANIFEST { + "" + } else if let Some(dir) = manifest.path.strip_suffix(&format!("/{PACKAGE_MANIFEST}")) { + dir + } else { + return; + }; + let Ok(doc) = serde_json::from_str::(&manifest.text) else { + return; + }; + for key in ["main", "module"] { + if let Some(target) = doc.get(key).and_then(Value::as_str) { + self.resolve_source_target(base_dir, target); + } + } + if let Some(bin) = doc.get("bin") { + self.collect_bin(base_dir, bin); + } + if let Some(exports) = doc.get("exports") { + self.collect_exports(base_dir, exports); + } + } + + fn collect_bin(&mut self, base_dir: &str, bin: &Value) { + if let Some(target) = bin.as_str() { + self.resolve_bin_target(base_dir, target); + return; + } + if let Some(map) = bin.as_object() { + for target in map.values().filter_map(Value::as_str) { + self.resolve_bin_target(base_dir, target); + } + } + } + + fn collect_exports(&mut self, base_dir: &str, value: &Value) { + match value { + Value::String(target) if target.contains('*') => { + self.resolve_wildcard_export(base_dir, target); + } + Value::String(target) => self.resolve_source_target(base_dir, target), + Value::Array(items) => { + for item in items { + self.collect_exports(base_dir, item); + } + } + Value::Object(map) => { + for item in map.values() { + self.collect_exports(base_dir, item); + } + } + _ => {} + } + } + + fn resolve_bin_target(&mut self, base_dir: &str, raw: &str) { + let Some(candidate) = normalize_entry_path(base_dir, raw) else { + return; + }; + if self.file_set.contains(candidate.as_str()) + && (is_ts_source_file(&candidate) || has_no_extension(&candidate)) + { + self.entries.insert(candidate); + return; + } + self.resolve_source_candidate(&candidate); + } + + fn resolve_source_target(&mut self, base_dir: &str, raw: &str) { + if let Some(candidate) = normalize_entry_path(base_dir, raw) { + self.resolve_source_candidate(&candidate); + } + } + + fn resolve_source_candidate(&mut self, candidate: &str) { + if is_declaration_file(candidate) { + return; + } + if self.file_set.contains(candidate) && is_ts_source_file(candidate) { + self.entries.insert(candidate.to_owned()); + return; + } + if let Some(aliased) = self.resolve_output_alias(candidate) { + self.entries.insert(aliased); + return; + } + if let Some(expanded) = self.resolve_extension_or_index(candidate) { + self.entries.insert(expanded); + } + } + + fn resolve_output_alias(&self, candidate: &str) -> Option { + for (output_ext, source_exts) in OUTPUT_TO_SOURCE_ALIASES { + let Some(stem) = candidate.strip_suffix(output_ext) else { + continue; + }; + for source_ext in source_exts { + let aliased = format!("{stem}{source_ext}"); + if self.file_set.contains(aliased.as_str()) && !is_declaration_file(&aliased) { + return Some(aliased); + } + } + } + None + } + + fn resolve_extension_or_index(&self, candidate: &str) -> Option { + for ext in EXTENSIONS { + let with_ext = format!("{candidate}.{ext}"); + if self.file_set.contains(with_ext.as_str()) && !is_declaration_file(&with_ext) { + return Some(with_ext); + } + } + for ext in EXTENSIONS { + let index_file = format!("{candidate}/index.{ext}"); + if self.file_set.contains(index_file.as_str()) { + return Some(index_file); + } + } + None + } + + fn resolve_wildcard_export(&mut self, base_dir: &str, raw: &str) { + if raw.starts_with('/') || raw.contains('\\') { + return; + } + let Some((prefix_raw, suffix)) = raw.split_once('*') else { + return; + }; + if suffix.contains('*') { + return; + } + let Some(normalized_prefix) = normalize_relative_path(base_dir, prefix_raw) else { + return; + }; + let prefix = if prefix_raw.ends_with('/') && !normalized_prefix.is_empty() { + format!("{normalized_prefix}/") + } else { + normalized_prefix + }; + for path in self.paths { + if let Some(matched_suffix) = wildcard_suffix_match(path, &prefix, suffix) + && path.len() > prefix.len() + matched_suffix.len() + && is_ts_source_file(path) + { + self.entries.insert(path.clone()); + } + } + } +} + +fn wildcard_suffix_match<'a>(path: &str, prefix: &str, suffix: &'a str) -> Option<&'a str> { + if !path.starts_with(prefix) { + return None; + } + if path.ends_with(suffix) { + return Some(suffix); + } + for (output_ext, source_exts) in OUTPUT_TO_SOURCE_ALIASES { + if suffix == output_ext { + for source_ext in source_exts { + if path.ends_with(source_ext) { + return Some(source_ext); + } + } + } + } + None +} + +fn normalize_entry_path(base_dir: &str, raw: &str) -> Option { + let trimmed = raw.trim(); + if trimmed.is_empty() || trimmed.starts_with('/') || trimmed.contains('\\') { + return None; + } + let normalized = normalize_relative_path(base_dir, trimmed)?; + (!normalized.is_empty()).then_some(normalized) +} + +fn is_declaration_file(path: &str) -> bool { + path.ends_with(".d.ts") || path.ends_with(".d.mts") || path.ends_with(".d.cts") +} + +fn is_ts_source_file(path: &str) -> bool { + if is_declaration_file(path) { + return false; + } + let file_name = path.rsplit_once('/').map_or(path, |(_, name)| name); + let Some((_, ext)) = file_name.rsplit_once('.') else { + return false; + }; + EXTENSIONS.contains(&ext) +} + +fn has_no_extension(path: &str) -> bool { + let file_name = path.rsplit_once('/').map_or(path, |(_, name)| name); + !file_name.contains('.') +} diff --git a/plugins/languages/ts/src/lib.rs b/plugins/languages/ts/src/lib.rs index c40cc53..f0505a3 100644 --- a/plugins/languages/ts/src/lib.rs +++ b/plugins/languages/ts/src/lib.rs @@ -1,5 +1,6 @@ #![forbid(unsafe_code)] +mod entry_points; mod functions; mod nesting; mod resolution; @@ -78,8 +79,8 @@ impl Guest for TypeScriptAndJavaScript { Vec::new() } - fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { - Vec::new() + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + entry_points::entry_points(&repository_paths, &manifests) } fn reference_ranges() -> Vec { diff --git a/plugins/languages/ts/tests/entry_points.rs b/plugins/languages/ts/tests/entry_points.rs new file mode 100644 index 0000000..648d5a7 --- /dev/null +++ b/plugins/languages/ts/tests/entry_points.rs @@ -0,0 +1,125 @@ +use codeint_lang_ts::TypeScriptAndJavaScript; +use codeint_model::{LanguagePlugin, Manifest, RepoPath}; + +#[test] +fn extracts_main_module_bin_and_exports_from_package_json() { + let repo: Vec = [ + "package.json", + "tsconfig.json", + "pnpm-workspace.yaml", + "src/index.ts", + "src/esm.mts", + "src/cli.ts", + "src/alt-cli.js", + "src/button.tsx", + "src/fallback.ts", + "src/features/auth.ts", + "src/features/billing.ts", + "src/features/auth.d.ts", + "dist/index.d.ts", + "bin/tool", + "packages/cli/package.json", + "packages/cli/src/entry.ts", + "packages/cli/src/esm.ts", + "packages/cli/src/dir/index.ts", + "packages/cli/bin/run.mjs", + ] + .map(|p| RepoPath::new(p).unwrap()) + .into(); + let root_pkg = r#"{ + "name": "demo", + "main": "./src/index.ts", + "module": "./src/esm.mts", + "bin": { + "demo-cli": "./src/cli.ts", + "alt": "src/alt-cli.js", + "raw": "./bin/tool", + "missing": "./bin/absent.js" + }, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./src/index.ts", + "default": "./dist/missing.js" + }, + "./button": { + "bun": "./src/button.tsx" + }, + "./fallback": ["./dist/nope.js", "./src/fallback.ts"], + "./features/*": "./src/features/*.js", + "./internal/*": null, + "./package.json": "./package.json", + "./escape": "../outside.ts", + "./abs": "/etc/passwd" + } + }"#; + let cli_pkg = r#"{ + "name": "@demo/cli", + "main": "./src/entry.js", + "module": "./src/esm", + "bin": "./bin/run.mjs", + "exports": "./src/dir" + }"#; + let manifests = vec![ + Manifest { + path: "package.json".into(), + text: root_pkg.into(), + }, + Manifest { + path: "tsconfig.json".into(), + text: r#"{"compilerOptions": {}}"#.into(), + }, + Manifest { + path: "pnpm-workspace.yaml".into(), + text: "packages:\n - packages/*\n".into(), + }, + Manifest { + path: "packages/cli/package.json".into(), + text: cli_pkg.into(), + }, + ]; + + let found = TypeScriptAndJavaScript.entry_points(&repo, manifests); + assert_eq!( + found, + [ + "bin/tool", + "packages/cli/bin/run.mjs", + "packages/cli/src/dir/index.ts", + "packages/cli/src/entry.ts", + "packages/cli/src/esm.ts", + "src/alt-cli.js", + "src/button.tsx", + "src/cli.ts", + "src/esm.mts", + "src/fallback.ts", + "src/features/auth.ts", + "src/features/billing.ts", + "src/index.ts", + ] + ); +} + +#[test] +fn returns_empty_when_package_json_declares_no_entry_points_or_is_invalid() { + let repo: Vec = ["package.json", "src/index.ts", "src/helper.ts"] + .map(|p| RepoPath::new(p).unwrap()) + .into(); + for manifests in [ + vec![Manifest { + path: "package.json".into(), + text: r#"{"name": "webapp", "dependencies": {"react": "19.0.0"}}"#.into(), + }], + vec![Manifest { + path: "package.json".into(), + text: "{not valid json".into(), + }], + Vec::new(), + ] { + assert!( + TypeScriptAndJavaScript + .entry_points(&repo, manifests) + .is_empty() + ); + } +} From 359478f26dcd728cb4df75d053e12127332bad36 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 12:41:54 +0800 Subject: [PATCH 3/5] feat(metrics): add orphan-file reachability, entry_points globs, budgets, diff, and MCP Implement language-neutral Production reachability in codeint-metrics starting from the union of manifest-discovered entry points and codeint.json entry_points globs, classifying unreachable Production files as unreferenced or test-only, excluding Generated and Vendored Source sets, traversing cross-package monorepo imports, and staying silently inactive when zero entry points exist. Integrate orphan_files independently across TOON, JSON, SARIF, Markdown, per-Source-set Budgets, stable FindingId Regression gating in codeint diff, and codeint mcp, and update schema/codeint.schema.json and docs/reference.md. Closes #199 --- crates/cli/src/check.rs | 219 +++++++++---- crates/cli/src/commit_measurement.rs | 38 ++- crates/cli/src/mcp.rs | 2 +- crates/cli/tests/check.rs | 4 +- crates/cli/tests/orphan_files.rs | 364 +++++++++++++++++++++ crates/config/src/codeint_json.rs | 58 +++- crates/config/src/codeint_json/starter.rs | 1 + crates/config/src/lib.rs | 2 +- crates/config/src/regression_limits.rs | 5 +- crates/config/tests/entry_points.rs | 109 +++++++ crates/metrics/src/lib.rs | 2 + crates/metrics/src/orphan_files.rs | 381 ++++++++++++++++++++++ crates/metrics/src/orphan_files/tests.rs | 264 +++++++++++++++ crates/report/src/diff.rs | 34 +- crates/report/src/diff/markdown.rs | 22 +- crates/report/src/lib.rs | 139 +++++++- crates/report/src/markdown.rs | 54 ++- crates/report/src/measurement.rs | 50 ++- crates/report/src/sarif.rs | 54 ++- crates/report/src/sarif/tests.rs | 1 + docs/reference.md | 44 ++- schema/codeint.schema.json | 22 ++ 22 files changed, 1765 insertions(+), 104 deletions(-) create mode 100644 crates/cli/tests/orphan_files.rs create mode 100644 crates/config/tests/entry_points.rs create mode 100644 crates/metrics/src/orphan_files.rs create mode 100644 crates/metrics/src/orphan_files/tests.rs diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index 050322a..92fbbac 100644 --- a/crates/cli/src/check.rs +++ b/crates/cli/src/check.rs @@ -1,10 +1,10 @@ -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; use std::string::FromUtf8Error; use codeint_config::{ - Configuration, ConfigurationFileError, FindingsShown, LanguageCoverage, PluginHostConfig, - SourceSetOverrides, read_configuration, + Configuration, ConfigurationFileError, EntryPoints, FindingsShown, LanguageCoverage, + PluginHostConfig, SourceSetOverrides, read_configuration, }; use codeint_git::{GitError, Repository, Snapshot}; use codeint_lang_dart::Dart; @@ -12,6 +12,7 @@ use codeint_lang_php::Php; use codeint_lang_python::Python; use codeint_lang_rust::Rust; use codeint_lang_ts::{TypeScriptAndJavaScript, vue_reference_ranges}; +use codeint_metrics::OrphanFiles; use codeint_model::{ CodeModel, InvalidReferenceRange, LanguagePlugin, LowerError, Manifest, MetricPlugin, MetricPluginError, Package, ReferenceRanges, RepoPath, ResolveError, SkippedFile, SourceFile, @@ -21,7 +22,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::{MeasuredLanguage, Report, ReportOptions}; use rayon::prelude::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator}; #[cfg(test)] @@ -337,6 +338,34 @@ fn check_with( check_loaded(&repository, &configuration, plugins, &[], findings, None) } +pub(crate) struct MeasuredSnapshot { + pub(crate) languages: Vec, + pub(crate) entry_points_by_language: BTreeMap>, +} + +pub(crate) fn compute_orphan_files( + snapshot: &MeasuredSnapshot, + selected: Option<&SelectedPackage>, +) -> (Option, BTreeMap) { + let mut by_language = BTreeMap::new(); + for language in &snapshot.languages { + let entry_points = snapshot + .entry_points_by_language + .get(&language.plugin) + .map(Vec::as_slice) + .unwrap_or(&[]); + if let Some(measured) = + OrphanFiles::measure_filtered(&language.model, entry_points, |path| { + selected.is_none_or(|pkg| pkg.matches(language.model.workspace.package_of(path))) + }) + { + by_language.insert(language.plugin.clone(), measured); + } + } + let total = OrphanFiles::merge(by_language.values().cloned()); + (total, by_language) +} + fn check_loaded( repository: &Repository, configuration: &Configuration, @@ -346,19 +375,29 @@ fn check_loaded( package: Option<&str>, ) -> Result { let tree = repository.working_tree()?; - let mut languages = measure_with(&tree, plugins, configuration)?; - if let Some(requested) = package { - let workspace = workspace_of_languages(&languages); - let selected = select_workspace_package(&workspace, requested)?; - filter_languages_to_package(&mut languages, &selected); + let mut snapshot = measure_snapshot(&tree, plugins, configuration)?; + let selected = if let Some(requested) = package { + let workspace = workspace_of_languages(&snapshot.languages); + Some(select_workspace_package(&workspace, requested)?) + } else { + None + }; + let (orphan_files, orphan_files_by_language) = + compute_orphan_files(&snapshot, selected.as_ref()); + if let Some(selected) = &selected { + filter_languages_to_package(&mut snapshot.languages, selected); } - Ok(Report::summarize_with_metrics_and_boundaries( - languages, + Ok(Report::summarize_with_options( + snapshot.languages, tree.submodules().to_vec(), findings, &configuration.budgets, - metric_plugins, - configuration.boundaries.as_ref(), + ReportOptions { + metric_plugins, + boundaries: configuration.boundaries.as_ref(), + orphan_files: orphan_files.as_ref(), + orphan_files_by_language: Some(&orphan_files_by_language), + }, )?) } @@ -367,6 +406,14 @@ pub(crate) fn measure_with( plugins: &[NamedLanguagePlugin<'_>], configuration: &Configuration, ) -> Result, CheckError> { + Ok(measure_snapshot(tree, plugins, configuration)?.languages) +} + +pub(crate) fn measure_snapshot( + tree: &Snapshot, + plugins: &[NamedLanguagePlugin<'_>], + configuration: &Configuration, +) -> Result { let names: Vec<&str> = plugins.iter().map(|plugin| plugin.name).collect(); let coverage = configuration.languages.coverage_of(&names)?; measure( @@ -374,6 +421,7 @@ pub(crate) fn measure_with( plugins, &coverage, &configuration.source_set_overrides, + &configuration.entry_points, ) } @@ -382,19 +430,30 @@ fn measure( plugins: &[NamedLanguagePlugin<'_>], coverage: &[LanguageCoverage<'_>], overrides: &SourceSetOverrides, -) -> Result, CheckError> { + configured_entry_points: &EntryPoints, +) -> Result { let covered_files = assign_files_to_plugins(tree, plugins, coverage)?; let manifests_by_plugin = read_manifests(tree, plugins)?; let workspace = find_workspace(plugins, &manifests_by_plugin)?; - let mut models: Vec = plugins - .iter() - .map(|_| CodeModel { - workspace: workspace.clone(), - ..CodeModel::default() - }) - .collect(); - let outcomes = if let Some(reader) = tree.working_tree_reader() { - covered_files + let outcomes = lower_covered_files(tree, plugins, &covered_files, overrides)?; + let models = collect_plugin_models(plugins.len(), workspace, outcomes); + resolve_measured_snapshot( + tree, + plugins, + models, + manifests_by_plugin, + configured_entry_points, + ) +} + +fn lower_covered_files( + tree: &Snapshot, + plugins: &[NamedLanguagePlugin<'_>], + covered_files: &[(&RepoPath, usize)], + overrides: &SourceSetOverrides, +) -> Result, CheckError> { + if let Some(reader) = tree.working_tree_reader() { + return covered_files .par_iter() .map(|&(path, index)| { let bytes = reader.read(path)?; @@ -403,22 +462,34 @@ fn measure( lower_bytes(bytes, path, plugins[index].plugin, overrides), )) }) - .collect::, CheckError>>()? - } else { - let loaded = covered_files - .iter() - .map(|&(path, index)| Ok((path, index, tree.read(path)?))) - .collect::, CheckError>>()?; - loaded - .into_par_iter() - .map(|(path, index, bytes)| { - ( - index, - lower_bytes(bytes, path, plugins[index].plugin, overrides), - ) - }) - .collect() - }; + .collect(); + } + let loaded = covered_files + .iter() + .map(|&(path, index)| Ok((path, index, tree.read(path)?))) + .collect::, CheckError>>()?; + Ok(loaded + .into_par_iter() + .map(|(path, index, bytes)| { + ( + index, + lower_bytes(bytes, path, plugins[index].plugin, overrides), + ) + }) + .collect()) +} + +fn collect_plugin_models( + plugin_count: usize, + workspace: Workspace, + outcomes: Vec<(usize, LoweredFile)>, +) -> Vec { + let mut models: Vec = (0..plugin_count) + .map(|_| CodeModel { + workspace: workspace.clone(), + ..CodeModel::default() + }) + .collect(); for (index, outcome) in outcomes { let model = &mut models[index]; match outcome { @@ -427,23 +498,59 @@ fn measure( LoweredFile::Skipped(skipped) => model.skipped.push(skipped), } } - plugins - .iter() - .zip(models) - .zip(manifests_by_plugin) - .map(|((named, mut model), manifests)| { - let importers: Vec<&SourceFile> = model.files.iter().collect(); - let reference_ranges = select_reference_ranges(named, &model, &manifests)?; - model.runtime_imports = - resolve_runtime_imports(named.plugin, tree.files(), manifests, &importers) - .map_err(CheckError::Resolve)?; - Ok(MeasuredLanguage { - plugin: named.name.to_owned(), - model, - reference_ranges, - }) - }) - .collect() + models +} + +fn resolve_measured_snapshot( + tree: &Snapshot, + plugins: &[NamedLanguagePlugin<'_>], + models: Vec, + manifests_by_plugin: Vec>, + configured_entry_points: &EntryPoints, +) -> Result { + let mut languages = Vec::with_capacity(plugins.len()); + let mut entry_points_by_language = BTreeMap::new(); + for ((named, mut model), manifests) in plugins.iter().zip(models).zip(manifests_by_plugin) { + let importers: Vec<&SourceFile> = model.files.iter().collect(); + let reference_ranges = select_reference_ranges(named, &model, &manifests)?; + let manifest_entries = named.plugin.entry_points(tree.files(), manifests.clone()); + let combined_entries = + combine_entry_points(manifest_entries, &model.files, configured_entry_points); + model.runtime_imports = + resolve_runtime_imports(named.plugin, tree.files(), manifests, &importers) + .map_err(CheckError::Resolve)?; + entry_points_by_language.insert(named.name.to_owned(), combined_entries); + languages.push(MeasuredLanguage { + plugin: named.name.to_owned(), + model, + reference_ranges, + }); + } + Ok(MeasuredSnapshot { + languages, + entry_points_by_language, + }) +} + +fn combine_entry_points( + manifest_entries: Vec, + files: &[SourceFile], + configured: &EntryPoints, +) -> Vec { + let mut entries = BTreeSet::new(); + for raw in manifest_entries { + if let Ok(path) = RepoPath::new(raw) { + entries.insert(path); + } + } + if !configured.is_empty() { + for file in files { + if configured.matches(&file.path) { + entries.insert(file.path.clone()); + } + } + } + entries.into_iter().collect() } fn select_reference_ranges( diff --git a/crates/cli/src/commit_measurement.rs b/crates/cli/src/commit_measurement.rs index 9ce0a76..5820447 100644 --- a/crates/cli/src/commit_measurement.rs +++ b/crates/cli/src/commit_measurement.rs @@ -5,8 +5,8 @@ use codeint_report::CommitMeasurement; use serde::Serialize; use crate::check::{ - BUILT_IN_LANGUAGE_PLUGINS, CheckError, LoadedPlugins, SelectedPackage, filter_model_to_package, - measure_with, select_workspace_package, + BUILT_IN_LANGUAGE_PLUGINS, CheckError, LoadedPlugins, SelectedPackage, compute_orphan_files, + filter_model_to_package, measure_snapshot, select_workspace_package, workspace_of_languages, }; use crate::describe; @@ -128,19 +128,28 @@ pub(crate) fn measure_all_languages_for_package( ) -> Result<(Option, CommitMeasurement), CheckError> { let named = plugins.as_named(); let metric_plugins = plugins.metric_plugins(); - let languages = measure_with(tree, &named, configuration)?; - let mut model = CodeModel::merge(languages.into_iter().map(|language| language.model)); + let snapshot = measure_snapshot(tree, &named, configuration)?; let selected = if let Some(requested) = package { - let selected = select_workspace_package(&model.workspace, requested)?; - filter_model_to_package(&mut model, &selected); - Some(selected) + let workspace = workspace_of_languages(&snapshot.languages); + Some(select_workspace_package(&workspace, requested)?) } else { None }; - let measurement = CommitMeasurement::of_with_metrics_and_boundaries( + let (orphan_files, _) = compute_orphan_files(&snapshot, selected.as_ref()); + let mut model = CodeModel::merge( + snapshot + .languages + .into_iter() + .map(|language| language.model), + ); + if let Some(selected) = &selected { + filter_model_to_package(&mut model, selected); + } + let measurement = CommitMeasurement::of_with_options( model, &metric_plugins, configuration.boundaries.as_ref(), + orphan_files.as_ref(), )?; Ok((selected, measurement)) } @@ -153,14 +162,21 @@ fn measure_all_languages_selected( ) -> Result { let named = plugins.as_named(); let metric_plugins = plugins.metric_plugins(); - let languages = measure_with(tree, &named, configuration)?; - let mut model = CodeModel::merge(languages.into_iter().map(|language| language.model)); + let snapshot = measure_snapshot(tree, &named, configuration)?; + let (orphan_files, _) = compute_orphan_files(&snapshot, selected); + let mut model = CodeModel::merge( + snapshot + .languages + .into_iter() + .map(|language| language.model), + ); if let Some(selected) = selected { filter_model_to_package(&mut model, selected); } - Ok(CommitMeasurement::of_with_metrics_and_boundaries( + Ok(CommitMeasurement::of_with_options( model, &metric_plugins, configuration.boundaries.as_ref(), + orphan_files.as_ref(), )?) } diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 6778d01..9342098 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -128,7 +128,7 @@ fn handle_tools_list() -> Value { "tools": [ { "name": "check", - "description": "Measure Software entropy of a Git repository working tree (Erosion, Duplication, Verbosity, Import cycles) and report any Budget failures.", + "description": "Measure Software entropy of a Git repository working tree (Erosion, Duplication, Verbosity, Import cycles, Boundaries, Orphan files) and report any Budget failures.", "inputSchema": { "type": "object", "properties": { diff --git a/crates/cli/tests/check.rs b/crates/cli/tests/check.rs index 56d57b0..6e1cd4b 100644 --- a/crates/cli/tests/check.rs +++ b/crates/cli/tests/check.rs @@ -2719,7 +2719,7 @@ fn an_unknown_key_in_codeint_json_is_named_with_the_allowed_keys_and_exits_2() { fn an_unknown_top_level_key_in_codeint_json_is_named_and_exits_2() { assert_codeint_json_is_rejected( r#"{ "budget": {} }"#, - "codeint.json has an unknown key budget; the keys allowed there are $schema, source_sets, budgets, regression_limits, languages, plugins, plugin_limits, boundaries", + "codeint.json has an unknown key budget; the keys allowed there are $schema, source_sets, budgets, regression_limits, languages, plugins, plugin_limits, boundaries, entry_points", UNKNOWN_KEY_REMEDY, ); } @@ -3937,7 +3937,7 @@ fn a_budget_for_an_unknown_metric_names_the_metrics_and_exits_2() { assert_codeint_json_is_rejected( r#"{ "budgets": { "production": { "complexity": 0.1 } } }"#, "codeint.json has an unknown key budgets.production.complexity; \ - the keys allowed there are erosion, duplication, verbosity, import_cycles, boundaries", + the keys allowed there are erosion, duplication, verbosity, import_cycles, boundaries, orphan_files", UNKNOWN_KEY_REMEDY, ); } diff --git a/crates/cli/tests/orphan_files.rs b/crates/cli/tests/orphan_files.rs new file mode 100644 index 0000000..e6b30ed --- /dev/null +++ b/crates/cli/tests/orphan_files.rs @@ -0,0 +1,364 @@ +mod common; + +use std::path::Path; +use std::process::Command; + +use common::{init_git_repo, mcp_payload, mcp_tool_call, send_mcp_requests}; +use serde_json::{Value, json}; +use tempfile::TempDir; + +fn run_codeint(dir: &Path, cache_dir: Option<&Path>, args: &[&str], expected_code: i32) -> String { + let mut command = Command::new(env!("CARGO_BIN_EXE_codeint")); + command.args(args).current_dir(dir); + if let Some(cache) = cache_dir { + command.env("CODEINT_CACHE_DIR", cache); + } + let output = command.output().expect("run codeint"); + assert_eq!( + output.status.code(), + Some(expected_code), + "codeint {args:?} exited {:?}; stderr: {}", + output.status.code(), + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).expect("stdout utf8") +} + +fn run_json(dir: &Path, cache_dir: Option<&Path>, args: &[&str], expected_code: i32) -> Value { + let stdout = run_codeint(dir, cache_dir, args, expected_code); + serde_json::from_str(&stdout).expect("valid JSON output") +} + +fn write_file(dir: &Path, rel: &str, body: &str) { + let path = dir.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent dirs"); + } + std::fs::write(path, body).expect("write fixture file"); +} + +fn orphan_finding_paths(section: &Value) -> Vec<&str> { + section["findings"] + .as_array() + .expect("orphan findings array") + .iter() + .map(|entry| entry["path"].as_str().expect("finding path")) + .collect() +} + +fn check_json(dir: &Path, expected_code: i32) -> Value { + run_json(dir, None, &["check", "--format", "json"], expected_code) +} + +fn production_orphans(report: &Value) -> &Value { + &report["source_sets"]["production"]["orphan_files"] +} + +fn diff_main_json(dir: &Path, cache: &Path, expected_code: i32) -> Value { + run_json( + dir, + Some(cache), + &["diff", "main", "--format", "json"], + expected_code, + ) +} + +#[test] +fn ts_check_reports_orphan_files_across_toon_json_sarif_and_markdown_excluding_generated_and_vendored() + { + let repo = init_git_repo(&[ + ( + "package.json", + r#"{"name": "demo", "main": "./src/index.ts"}"#, + ), + ( + "src/index.ts", + "import { live } from './live';\nexport const run = () => live();\n", + ), + ("src/live.ts", "export const live = () => 1;\n"), + ("src/dead.ts", "export const dead = () => 2;\n"), + ("src/helper.ts", "export const helper = () => 3;\n"), + ( + "src/helper.test.ts", + "import { helper } from './helper';\nexport const check = () => helper();\n", + ), + ( + "src/gen.ts", + "// @generated\nexport const generated = () => 4;\n", + ), + ("vendor/third.ts", "export const vendored = () => 5;\n"), + ]); + + let report = run_json(repo.path(), None, &["check", "--format", "json"], 0); + assert!(report.get("score").is_none()); + let prod = &report["source_sets"]["production"]; + let orphan = &prod["orphan_files"]; + assert_eq!(orphan["orphan_files"], 2); + assert_eq!(orphan["evaluated_files"], 4); + assert_eq!(orphan["entry_points"], 1); + assert_eq!(orphan["unreferenced"], 1); + assert_eq!(orphan["test_only"], 1); + assert_eq!(orphan["ratio"], 0.5); + + let findings = orphan["findings"].as_array().expect("orphan findings"); + assert_eq!(findings.len(), 2); + assert_eq!(findings[0]["path"], "src/dead.ts"); + assert_eq!(findings[0]["kind"], "unreferenced"); + assert!(findings[0].get("test_importers").is_none()); + assert_eq!(findings[1]["path"], "src/helper.ts"); + assert_eq!(findings[1]["kind"], "test-only"); + assert_eq!(findings[1]["test_importers"], json!(["src/helper.test.ts"])); + assert!( + findings[1]["message"] + .as_str() + .unwrap() + .contains("only imported by tests") + ); + + assert!(report["source_sets"]["test"].get("orphan_files").is_none()); + assert!( + report["source_sets"]["generated"] + .get("orphan_files") + .is_none() + ); + assert!( + report["source_sets"]["vendored"] + .get("orphan_files") + .is_none() + ); + + let toon = run_codeint(repo.path(), None, &["check"], 0); + assert!(toon.contains("orphan_files:")); + assert!(toon.contains("src/dead.ts")); + assert!(toon.contains("src/helper.ts")); + assert!(toon.contains("test-only")); + assert!(toon.contains("unreferenced")); + + let sarif = run_json(repo.path(), None, &["check", "--format", "sarif"], 0); + let results: Vec<&Value> = sarif["runs"][0]["results"] + .as_array() + .expect("sarif results") + .iter() + .filter(|item| item["ruleId"] == "orphan_files") + .collect(); + assert_eq!(results.len(), 2); + assert_eq!( + results[1]["relatedLocations"][0]["physicalLocation"]["artifactLocation"]["uri"], + "src/helper.test.ts" + ); + assert_eq!( + results[0]["partialFingerprints"]["codeintFindingId"], + findings[0]["id"] + ); + + let markdown = run_codeint(repo.path(), None, &["check", "--format", "markdown"], 0); + assert!(markdown.contains("| Production | Orphan files | 0.5 |")); + assert!(markdown.contains("### Orphan files")); + assert!(markdown.contains("`src/dead.ts`")); + assert!(markdown.contains("`src/helper.ts`")); + assert!(markdown.contains("test-only")); +} + +#[test] +fn silent_no_op_when_no_entry_points_and_activates_via_config_entry_points_globs() { + let repo = init_git_repo(&[ + ( + "src/routes/home.ts", + "import { shared } from '../shared';\nexport const home = () => shared();\n", + ), + ("src/shared.ts", "export const shared = () => 1;\n"), + ("src/abandoned.ts", "export const abandoned = () => 2;\n"), + ]); + + let silent = run_json(repo.path(), None, &["check", "--format", "json"], 0); + assert!( + silent["source_sets"]["production"] + .get("orphan_files") + .is_none() + ); + + write_file( + repo.path(), + "codeint.json", + r#"{"entry_points": ["src/routes/**/*.ts"]}"#, + ); + + let active = run_json(repo.path(), None, &["check", "--format", "json"], 0); + let orphan = &active["source_sets"]["production"]["orphan_files"]; + assert_eq!(orphan["evaluated_files"], 3); + assert_eq!(orphan["entry_points"], 1); + assert_eq!(orphan["orphan_files"], 1); + assert_eq!(orphan["findings"][0]["path"], "src/abandoned.ts"); + assert_eq!(orphan["findings"][0]["kind"], "unreferenced"); +} + +#[test] +fn monorepo_cross_package_reachability_and_isolated_package_safety() { + let repo = init_git_repo(&[ + ( + "package.json", + r#"{"name": "mono", "private": true, "workspaces": ["packages/*"]}"#, + ), + ( + "packages/app/package.json", + r#"{"name": "@mono/app", "main": "./src/index.ts"}"#, + ), + ( + "packages/app/src/index.ts", + "import { used } from '@mono/lib';\nexport const start = () => used();\n", + ), + ( + "packages/lib/package.json", + r#"{"name": "@mono/lib", "exports": {".": "./src/used.ts"}}"#, + ), + ("packages/lib/src/used.ts", "export const used = () => 1;\n"), + ( + "packages/lib/src/unused.ts", + "export const unused = () => 2;\n", + ), + ("packages/docs/package.json", r#"{"name": "@mono/docs"}"#), + ( + "packages/docs/src/page.ts", + "export const page = () => 3;\n", + ), + ]); + + let report = check_json(repo.path(), 0); + let orphan = production_orphans(&report); + assert_eq!(orphan["evaluated_files"], 3); + assert_eq!(orphan["orphan_files"], 1); + assert_eq!( + orphan_finding_paths(orphan), + vec!["packages/lib/src/unused.ts"] + ); +} + +#[test] +fn budget_and_diff_regression_gating_with_stable_finding_ids() { + let cache = TempDir::new().expect("cache dir"); + let repo = init_git_repo(&[ + ( + "package.json", + r#"{"name": "gate", "main": "./src/index.ts"}"#, + ), + ("src/index.ts", "export const main = () => 1;\n"), + ("src/legacy_dead.ts", "export const legacy = () => 2;\n"), + ]); + + write_file( + repo.path(), + "codeint.json", + r#"{"budgets": {"production": {"orphan_files": 0}}}"#, + ); + let over_budget = run_json(repo.path(), None, &["check", "--format", "json"], 1); + assert_eq!(over_budget["over_budget"][0]["metric"], "orphan_files"); + + write_file(repo.path(), "codeint.json", "{}"); + let unchanged_diff = diff_main_json(repo.path(), cache.path(), 0); + let diff_orphans = &unchanged_diff["source_sets"]["production"]["orphan_files"]; + assert_eq!(diff_orphans["new"].as_array().unwrap().len(), 0); + assert_eq!(diff_orphans["resolved"].as_array().unwrap().len(), 0); + assert_eq!(diff_orphans["unchanged"], 1); + + write_file( + repo.path(), + "src/new_dead.ts", + "export const added = () => 3;\n", + ); + let regressed_diff = diff_main_json(repo.path(), cache.path(), 1); + let regressed_orphans = ®ressed_diff["source_sets"]["production"]["orphan_files"]; + assert_eq!(regressed_orphans["new"].as_array().unwrap().len(), 1); + assert_eq!(regressed_orphans["new"][0]["path"], "src/new_dead.ts"); + assert_eq!(regressed_orphans["unchanged"], 1); + assert_eq!(regressed_diff["regressions"][0]["metric"], "orphan_files"); + + std::fs::remove_file(repo.path().join("src/new_dead.ts")).expect("remove new_dead.ts"); + write_file( + repo.path(), + "src/index.ts", + "import { legacy } from './legacy_dead';\nexport const main = () => legacy();\n", + ); + let resolved_diff = diff_main_json(repo.path(), cache.path(), 0); + let resolved_orphans = &resolved_diff["source_sets"]["production"]["orphan_files"]; + assert_eq!(resolved_orphans["new"].as_array().unwrap().len(), 0); + assert_eq!(resolved_orphans["resolved"].as_array().unwrap().len(), 1); + assert_eq!( + resolved_orphans["resolved"][0]["path"], + "src/legacy_dead.ts" + ); + assert_eq!(resolved_orphans["unchanged"], 0); +} + +#[test] +fn multi_language_rust_and_python_check_and_mcp_expose_orphan_files() { + let repo = init_git_repo(&[ + ( + "Cargo.toml", + "[package]\nname = \"svc\"\nversion = \"0.1.0\"\n", + ), + ( + "src/lib.rs", + "mod live;\nuse crate::live::value;\npub fn entry() -> i32 { value() }\n", + ), + ("src/live.rs", "pub fn value() -> i32 { 1 }\n"), + ("src/dead.rs", "pub fn unused() -> i32 { 2 }\n"), + ( + "pyproject.toml", + "[project]\nname = \"pyapp\"\nversion = \"0.1.0\"\n[project.scripts]\npyapp = \"app.cli:main\"\n", + ), + ("app/__init__.py", ""), + ( + "app/cli.py", + "from app.used import run\ndef main():\n return run()\n", + ), + ("app/used.py", "def run():\n return 1\n"), + ("app/unused.py", "def stale():\n return 2\n"), + ("app/helper_for_tests.py", "def helper():\n return 3\n"), + ( + "tests/test_helper.py", + "from app.helper_for_tests import helper\ndef test_it():\n assert helper() == 3\n", + ), + ]); + + let report = check_json(repo.path(), 0); + let total_orphans = production_orphans(&report); + let paths = orphan_finding_paths(total_orphans); + assert!(paths.contains(&"src/dead.rs"), "got {paths:?}"); + assert!(paths.contains(&"app/unused.py"), "got {paths:?}"); + assert!(paths.contains(&"app/helper_for_tests.py"), "got {paths:?}"); + assert!(!paths.contains(&"src/live.rs"), "got {paths:?}"); + assert!(!paths.contains(&"app/used.py"), "got {paths:?}"); + + let test_only_finding = total_orphans["findings"] + .as_array() + .unwrap() + .iter() + .find(|f| f["path"] == "app/helper_for_tests.py") + .expect("python test-only finding"); + assert_eq!(test_only_finding["kind"], "test-only"); + + let rust_orphans = &report["languages"]["rust"]["source_sets"]["production"]["orphan_files"]; + assert!(orphan_finding_paths(rust_orphans).contains(&"src/dead.rs")); + let py_orphans = &report["languages"]["python"]["source_sets"]["production"]["orphan_files"]; + assert!(orphan_finding_paths(py_orphans).contains(&"app/unused.py")); + + write_file( + repo.path(), + "app/extra_orphan.py", + "def extra():\n return 4\n", + ); + let mcp_calls = [ + mcp_tool_call(1, "check", json!({})), + mcp_tool_call(2, "diff", json!({"base_ref": "main"})), + ]; + let responses = send_mcp_requests(repo.path(), &mcp_calls); + let check_payload = mcp_payload(&responses[0]); + let mcp_orphans = &check_payload["report"]["source_sets"]["production"]["orphan_files"]; + assert!(orphan_finding_paths(mcp_orphans).contains(&"app/extra_orphan.py")); + let diff_payload = mcp_payload(&responses[1]); + assert_eq!(diff_payload["passed"], false); + assert_eq!( + diff_payload["report"]["source_sets"]["production"]["orphan_files"]["new"][0]["path"], + "app/extra_orphan.py" + ); +} diff --git a/crates/config/src/codeint_json.rs b/crates/config/src/codeint_json.rs index 98d2f2d..471a940 100644 --- a/crates/config/src/codeint_json.rs +++ b/crates/config/src/codeint_json.rs @@ -55,9 +55,27 @@ pub struct Configuration { pub plugins: Vec, pub plugin_limits: PluginLimits, pub boundaries: Option, + pub entry_points: EntryPoints, effective: ConfigurationFile, } +#[derive(Debug, Default)] +pub struct EntryPoints { + globs: Option, +} + +impl EntryPoints { + pub fn is_empty(&self) -> bool { + self.globs.is_none() + } + + pub fn matches(&self, path: &RepoPath) -> bool { + self.globs + .as_ref() + .is_some_and(|globs| globs.is_match(path.as_str())) + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct Sha256Digest([u8; 32]); @@ -131,7 +149,7 @@ impl Configuration { let allowed_metrics = || -> Vec { Metric::BUILT_IN_KEYS .iter() - .chain(["boundaries"].iter()) + .chain(["boundaries", "orphan_files"].iter()) .chain(external_metric_keys.iter()) .map(|key| (*key).to_owned()) .collect() @@ -139,6 +157,7 @@ impl Configuration { let is_known = |key: &str| { Metric::BUILT_IN_KEYS.contains(&key) || key == "boundaries" + || key == "orphan_files" || external_metric_keys.contains(&key) }; for (source_set, metric_key, _) in &self.budgets.set { @@ -355,6 +374,11 @@ struct ConfigurationFile { description = "Architectural import boundaries defining named zones, optional public_files entry points, directional allow or deny rules, and optional strict_zones mode." )] boundaries: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[schemars( + description = "Globs of repository-relative paths treated as additional Production entry points for Orphan files detection, combined with manifest-discovered entry points." + )] + entry_points: Vec, } #[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)] @@ -425,6 +449,9 @@ struct RegressionLimitsFile { #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] #[schemars(description = "The Regression limit of Boundaries in every Source set.")] boundaries: RegressionLimitSetting, + #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] + #[schemars(description = "The Regression limit of Orphan files in every Source set.")] + orphan_files: RegressionLimitSetting, #[serde(default, skip_serializing_if = "MetricRegressionLimits::is_unset")] #[schemars(description = "The Regression limits of the Production Source set.")] production: MetricRegressionLimits, @@ -458,6 +485,9 @@ struct MetricRegressionLimits { #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] #[schemars(description = "The Regression limit of Boundaries in this Source set.")] boundaries: RegressionLimitSetting, + #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] + #[schemars(description = "The Regression limit of Orphan files in this Source set.")] + orphan_files: RegressionLimitSetting, #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")] external: BTreeMap, } @@ -470,6 +500,7 @@ impl MetricRegressionLimits { &self.verbosity, &self.import_cycles, &self.boundaries, + &self.orphan_files, ] .into_iter() .chain(self.external.values()) @@ -483,6 +514,7 @@ impl MetricRegressionLimits { verbosity, import_cycles, boundaries, + orphan_files, external, } = self; [ @@ -491,6 +523,7 @@ impl MetricRegressionLimits { (Metric::Verbosity.key().to_owned(), verbosity), (Metric::ImportCycles.key().to_owned(), import_cycles), ("boundaries".to_owned(), boundaries), + ("orphan_files".to_owned(), orphan_files), ] .into_iter() .chain(external) @@ -552,6 +585,13 @@ struct MetricBudgets { description = "The highest Boundaries ratio, from 0 to 1." )] boundaries: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars( + with = "f64", + range(min = 0, max = 1), + description = "The highest Orphan files ratio, from 0 to 1." + )] + orphan_files: Option, #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")] external: BTreeMap, } @@ -611,6 +651,7 @@ fn parse(text: &str) -> Result { serde_json::from_value(value).map_err(ConfigurationFileError::NotJson)?; let effective = file.without_schema_address(); let parsed_boundaries = file.boundaries.map(Boundaries::from_file).transpose()?; + let parsed_entry_points = entry_points(&file.entry_points)?; Ok(Configuration { effective, source_set_overrides: source_set_overrides(file.source_sets)?, @@ -620,6 +661,17 @@ fn parse(text: &str) -> Result { plugins: plugins(file.plugins)?, plugin_limits: plugin_limits(file.plugin_limits), boundaries: parsed_boundaries, + entry_points: parsed_entry_points, + }) +} + +fn entry_points(globs: &[String]) -> Result { + if globs.is_empty() { + return Ok(EntryPoints::default()); + } + let key = KeyPath::default().child(KeySegment::Key("entry_points".to_owned())); + Ok(EntryPoints { + globs: Some(glob_set(&key, globs)?), }) } @@ -713,6 +765,7 @@ fn regression_limits(file: RegressionLimitsFile) -> RegressionLimits { verbosity, import_cycles, boundaries, + orphan_files, production, test, generated, @@ -725,6 +778,7 @@ fn regression_limits(file: RegressionLimitsFile) -> RegressionLimits { verbosity, import_cycles, boundaries, + orphan_files, external, } .by_metric() @@ -775,6 +829,7 @@ fn budgets(file: SourceSetBudgets) -> Budgets { verbosity, import_cycles, boundaries, + orphan_files, external, } = metric_budgets; [ @@ -783,6 +838,7 @@ fn budgets(file: SourceSetBudgets) -> Budgets { (Metric::Verbosity.key().to_owned(), verbosity), (Metric::ImportCycles.key().to_owned(), import_cycles), ("boundaries".to_owned(), boundaries), + ("orphan_files".to_owned(), orphan_files), ] .into_iter() .filter_map(move |(metric, ratio)| Some((source_set, metric, ratio?))) diff --git a/crates/config/src/codeint_json/starter.rs b/crates/config/src/codeint_json/starter.rs index c991ddc..d473fde 100644 --- a/crates/config/src/codeint_json/starter.rs +++ b/crates/config/src/codeint_json/starter.rs @@ -69,6 +69,7 @@ fn starter_configuration_text(languages: &[DetectedLanguage]) -> String { plugins: Vec::new(), plugin_limits: Default::default(), boundaries: None, + entry_points: Vec::new(), languages: (!languages.is_empty()).then(|| { languages .iter() diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 7dddfa0..56bc6ae 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -16,7 +16,7 @@ pub use boundaries::{ }; pub use calendar_day::{CalendarDay, CalendarDayError}; pub use codeint_json::{ - Budget, Budgets, Configuration, DetectedLanguage, LanguageCoverage, Languages, + Budget, Budgets, Configuration, DetectedLanguage, EntryPoints, LanguageCoverage, Languages, PluginDeclaration, PluginKind, PluginLimits, PluginSource, Sha256Digest, SourceSetOverrides, StarterConfigurationError, configuration_schema, published_schema_address, read_configuration, write_starter_configuration, diff --git a/crates/config/src/regression_limits.rs b/crates/config/src/regression_limits.rs index 5d9cbdf..223817c 100644 --- a/crates/config/src/regression_limits.rs +++ b/crates/config/src/regression_limits.rs @@ -68,7 +68,10 @@ impl RegressionLimit { }; fn default_for_key(metric_key: &str) -> RegressionLimit { - if metric_key == Metric::ImportCycles.key() || metric_key == "boundaries" { + if metric_key == Metric::ImportCycles.key() + || metric_key == "boundaries" + || metric_key == "orphan_files" + { RegressionLimit::DEFAULT_FOR_IMPORT_CYCLES } else { RegressionLimit::DEFAULT diff --git a/crates/config/tests/entry_points.rs b/crates/config/tests/entry_points.rs new file mode 100644 index 0000000..cbacf1b --- /dev/null +++ b/crates/config/tests/entry_points.rs @@ -0,0 +1,109 @@ +use std::path::{Path, PathBuf}; + +use codeint_config::{Configuration, NewFindingsRule, read_configuration}; +use codeint_model::{RepoPath, SourceSet}; + +struct TempFolder(PathBuf); + +impl TempFolder { + fn new(name: &str) -> TempFolder { + let path = + std::env::temp_dir().join(format!("codeint-config-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("create temp dir"); + TempFolder(path) + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[test] +fn parses_entry_points_orphan_files_budget_and_regression_limits() { + let dir = TempFolder::new("entry-points-valid"); + std::fs::write( + dir.path().join("codeint.json"), + r#"{ + "entry_points": ["src/pages/**/*.tsx", "scripts/cli.ts"], + "budgets": { + "production": { + "orphan_files": 0.0 + } + }, + "regression_limits": { + "orphan_files": { + "ratio_rise": 0.02 + }, + "production": { + "orphan_files": { + "new_findings": "any_new_finding" + } + } + } +}"#, + ) + .expect("write codeint.json"); + + let config = read_configuration(dir.path()).expect("valid configuration"); + config + .validate_metrics(&[]) + .expect("orphan_files is a known built-in metric"); + + let budget = config + .budgets + .budget_for_key(SourceSet::Production, "orphan_files") + .expect("production orphan_files budget"); + assert_eq!(budget.ratio(), 0.0); + + let prod_limit = config + .regression_limits + .limit_for_key(SourceSet::Production, "orphan_files"); + assert_eq!(prod_limit.ratio_rise.ratio(), 0.02); + assert_eq!(prod_limit.new_findings, NewFindingsRule::AnyNewFinding); + + let default_config = Configuration::default(); + let default_limit = default_config + .regression_limits + .limit_for_key(SourceSet::Production, "orphan_files"); + assert_eq!(default_limit.new_findings, NewFindingsRule::AnyNewFinding); + + assert!(!config.entry_points.is_empty()); + assert!( + config + .entry_points + .matches(&RepoPath::new("src/pages/blog/post.tsx").expect("path")) + ); + assert!( + config + .entry_points + .matches(&RepoPath::new("scripts/cli.ts").expect("path")) + ); + assert!( + !config + .entry_points + .matches(&RepoPath::new("src/lib/unused.ts").expect("path")) + ); +} + +#[test] +fn rejects_invalid_entry_points_glob() { + let dir = TempFolder::new("entry-points-invalid"); + std::fs::write( + dir.path().join("codeint.json"), + r#"{ "entry_points": ["src/[unclosed"] }"#, + ) + .expect("write codeint.json"); + + let error = read_configuration(dir.path()).expect_err("invalid glob must fail"); + assert!( + error.to_string().contains("entry_points[0]"), + "unexpected error: {error}" + ); +} diff --git a/crates/metrics/src/lib.rs b/crates/metrics/src/lib.rs index d39d411..df3b88d 100644 --- a/crates/metrics/src/lib.rs +++ b/crates/metrics/src/lib.rs @@ -7,9 +7,11 @@ mod finding_id; mod impact; mod import_cycles; mod line_share; +mod orphan_files; mod trace; mod verbosity; +pub use crate::orphan_files::{OrphanFileFinding, OrphanFileKind, OrphanFiles}; pub use boundaries::{ Boundaries, BoundaryEdgeCheck, BoundaryFinding, BoundaryFindingKind, BoundaryPolicy, }; diff --git a/crates/metrics/src/orphan_files.rs b/crates/metrics/src/orphan_files.rs new file mode 100644 index 0000000..1ba820a --- /dev/null +++ b/crates/metrics/src/orphan_files.rs @@ -0,0 +1,381 @@ +use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; + +use codeint_model::{CodeModel, ImportResolution, Package, RepoPath, SourceSet}; + +use crate::finding_id::{FindingId, FindingIds}; + +#[cfg(test)] +mod tests; + +const ORPHAN_FILES_METRIC_KEY: &str = "orphan_files"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum OrphanFileKind { + Unreferenced, + TestOnly, +} + +impl OrphanFileKind { + pub fn key(self) -> &'static str { + match self { + OrphanFileKind::Unreferenced => "unreferenced", + OrphanFileKind::TestOnly => "test-only", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OrphanFileFinding { + pub id: FindingId, + pub path: RepoPath, + pub kind: OrphanFileKind, + pub test_importers: Vec, + pub message: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OrphanFiles { + entry_points: Vec, + evaluated_files: usize, + findings: Vec, +} + +struct ImportGraphs { + forward: Vec>, + reverse_non_test: Vec>, + direct_test_importers: Vec>, +} + +struct PendingOrphan { + path: RepoPath, + kind: OrphanFileKind, + test_importers: Vec, + message: String, +} + +impl OrphanFiles { + pub fn measure(model: &CodeModel, entry_points: &[RepoPath]) -> Option { + OrphanFiles::measure_filtered(model, entry_points, |_| true) + } + + pub fn measure_filtered( + model: &CodeModel, + entry_points: &[RepoPath], + include_in_report: impl Fn(&RepoPath) -> bool, + ) -> Option { + let index_of: HashMap<&RepoPath, usize> = model + .files + .iter() + .enumerate() + .map(|(index, file)| (&file.path, index)) + .collect(); + let source_sets: Vec = model + .files + .iter() + .map(|file| file.model.source_set) + .collect(); + let roots = collect_roots(&index_of, &source_sets, entry_points); + if roots.is_empty() { + return None; + } + let graphs = build_import_graphs(model, &index_of, &source_sets); + let live = traverse_live(&roots, &graphs.forward, &source_sets); + let active_packages = active_packages_of(model, &live); + let reached_by_test = traverse_test_reachable( + &graphs.direct_test_importers, + &graphs.forward, + &live, + &source_sets, + ); + + let mut evaluated_files = 0usize; + let mut pending = Vec::new(); + for (index, file) in model.files.iter().enumerate() { + if file.model.source_set != SourceSet::Production { + continue; + } + if let Some(active) = &active_packages + && !active.contains(&model.workspace.package_of(&file.path)) + { + continue; + } + if !include_in_report(&file.path) { + continue; + } + evaluated_files += 1; + if live[index] { + continue; + } + let (kind, test_importers, message) = if reached_by_test[index] { + let importers = collect_reaching_test_importers( + index, + &graphs.direct_test_importers, + &graphs.reverse_non_test, + &live, + model, + ); + let message = format!( + "Production file {} is unreachable from Production entry points (only imported by tests)", + file.path + ); + (OrphanFileKind::TestOnly, importers, message) + } else { + let message = format!( + "Production file {} is unreachable from any entry point", + file.path + ); + (OrphanFileKind::Unreferenced, Vec::new(), message) + }; + pending.push(PendingOrphan { + path: file.path.clone(), + kind, + test_importers, + message, + }); + } + + if evaluated_files == 0 { + return None; + } + + let mut reported_roots: Vec = roots + .iter() + .map(|&index| model.files[index].path.clone()) + .filter(&include_in_report) + .collect(); + reported_roots.sort(); + reported_roots.dedup(); + + Some(OrphanFiles { + entry_points: reported_roots, + evaluated_files, + findings: assign_finding_ids(pending), + }) + } + + pub fn merge(measurements: impl IntoIterator) -> Option { + let mut iter = measurements.into_iter().peekable(); + iter.peek()?; + let mut entry_points = BTreeSet::new(); + let mut evaluated_files = 0usize; + let mut findings = Vec::new(); + for measurement in iter { + evaluated_files += measurement.evaluated_files; + entry_points.extend(measurement.entry_points); + findings.extend(measurement.findings); + } + if evaluated_files == 0 { + return None; + } + findings.sort_by(|left, right| left.path.cmp(&right.path)); + findings.dedup_by(|left, right| left.path == right.path); + Some(OrphanFiles { + entry_points: entry_points.into_iter().collect(), + evaluated_files, + findings, + }) + } + + pub fn ratio(&self) -> f64 { + if self.evaluated_files > 0 { + self.findings.len() as f64 / self.evaluated_files as f64 + } else { + 0.0 + } + } + + pub fn entry_points(&self) -> &[RepoPath] { + &self.entry_points + } + + pub fn evaluated_files(&self) -> usize { + self.evaluated_files + } + + pub fn findings(&self) -> &[OrphanFileFinding] { + &self.findings + } + + pub fn unreferenced_count(&self) -> usize { + self.findings + .iter() + .filter(|finding| finding.kind == OrphanFileKind::Unreferenced) + .count() + } + + pub fn test_only_count(&self) -> usize { + self.findings + .iter() + .filter(|finding| finding.kind == OrphanFileKind::TestOnly) + .count() + } +} + +fn collect_roots( + index_of: &HashMap<&RepoPath, usize>, + source_sets: &[SourceSet], + entry_points: &[RepoPath], +) -> BTreeSet { + let mut roots = BTreeSet::new(); + for entry in entry_points { + if let Some(&index) = index_of.get(entry) + && source_sets[index] != SourceSet::Test + { + roots.insert(index); + } + } + roots +} + +fn build_import_graphs( + model: &CodeModel, + index_of: &HashMap<&RepoPath, usize>, + source_sets: &[SourceSet], +) -> ImportGraphs { + let count = model.files.len(); + let mut forward = vec![Vec::new(); count]; + let mut reverse_non_test = vec![Vec::new(); count]; + let mut direct_test_importers = vec![BTreeSet::new(); count]; + for runtime_import in &model.runtime_imports { + let ImportResolution::Resolved(target) = &runtime_import.resolution else { + continue; + }; + let (Some(&from), Some(&to)) = + (index_of.get(&runtime_import.importer), index_of.get(target)) + else { + continue; + }; + if source_sets[from] == SourceSet::Test { + if source_sets[to] != SourceSet::Test { + direct_test_importers[to].insert(from); + } + } else { + forward[from].push(to); + if source_sets[to] != SourceSet::Test { + reverse_non_test[to].push(from); + } + } + } + ImportGraphs { + forward, + reverse_non_test, + direct_test_importers, + } +} + +fn traverse_live( + roots: &BTreeSet, + forward: &[Vec], + source_sets: &[SourceSet], +) -> Vec { + let mut visited = vec![false; forward.len()]; + let mut queue = VecDeque::new(); + for &root in roots { + visited[root] = true; + queue.push_back(root); + } + while let Some(node) = queue.pop_front() { + for &target in &forward[node] { + if !visited[target] && source_sets[target] != SourceSet::Test { + visited[target] = true; + queue.push_back(target); + } + } + } + visited +} + +fn active_packages_of<'model>( + model: &'model CodeModel, + live: &[bool], +) -> Option>> { + if !model.workspace.has_members() { + return None; + } + let active = live + .iter() + .enumerate() + .filter(|&(_, &is_live)| is_live) + .map(|(index, _)| model.workspace.package_of(&model.files[index].path)) + .collect(); + Some(active) +} + +fn traverse_test_reachable( + direct_test_importers: &[BTreeSet], + forward: &[Vec], + live: &[bool], + source_sets: &[SourceSet], +) -> Vec { + let mut reached = vec![false; forward.len()]; + let mut queue = VecDeque::new(); + for (node, importers) in direct_test_importers.iter().enumerate() { + if !importers.is_empty() && !live[node] && source_sets[node] != SourceSet::Test { + reached[node] = true; + queue.push_back(node); + } + } + while let Some(node) = queue.pop_front() { + for &target in &forward[node] { + if !reached[target] && !live[target] && source_sets[target] != SourceSet::Test { + reached[target] = true; + queue.push_back(target); + } + } + } + reached +} + +fn collect_reaching_test_importers( + start: usize, + direct_test_importers: &[BTreeSet], + reverse_non_test: &[Vec], + live: &[bool], + model: &CodeModel, +) -> Vec { + if !direct_test_importers[start].is_empty() { + let mut paths: Vec = direct_test_importers[start] + .iter() + .map(|&index| model.files[index].path.clone()) + .collect(); + paths.sort(); + return paths; + } + let mut visited = HashSet::new(); + let mut queue = VecDeque::new(); + let mut test_indices = BTreeSet::new(); + visited.insert(start); + queue.push_back(start); + while let Some(node) = queue.pop_front() { + test_indices.extend(direct_test_importers[node].iter().copied()); + for &importer in &reverse_non_test[node] { + if !live[importer] && visited.insert(importer) { + queue.push_back(importer); + } + } + } + let mut paths: Vec = test_indices + .into_iter() + .map(|index| model.files[index].path.clone()) + .collect(); + paths.sort(); + paths +} + +fn assign_finding_ids(mut pending: Vec) -> Vec { + pending.sort_by(|left, right| left.path.cmp(&right.path)); + let mut ids = FindingIds::for_key(ORPHAN_FILES_METRIC_KEY); + pending + .into_iter() + .map(|item| { + let id = ids.next_in_source_order([&item.path], []); + OrphanFileFinding { + id, + path: item.path, + kind: item.kind, + test_importers: item.test_importers, + message: item.message, + } + }) + .collect() +} diff --git a/crates/metrics/src/orphan_files/tests.rs b/crates/metrics/src/orphan_files/tests.rs new file mode 100644 index 0000000..955a27a --- /dev/null +++ b/crates/metrics/src/orphan_files/tests.rs @@ -0,0 +1,264 @@ +use codeint_model::{ + CodeModel, FileModel, ImportResolution, RepoPath, RuntimeImport, SourceFile, SourceSet, + Workspace, +}; + +use super::{OrphanFileKind, OrphanFiles}; + +fn repo_path(text: &str) -> RepoPath { + RepoPath::new(text).expect("valid repo path") +} + +fn source_file(name: &str, source_set: SourceSet) -> SourceFile { + SourceFile { + path: repo_path(name), + model: FileModel { + source_set, + source_lines: 5, + functions: Vec::new(), + tokens: Vec::new(), + flagged_lines: Vec::new(), + runtime_imports: Vec::new(), + }, + } +} + +fn build_model( + files: &[(&str, SourceSet)], + edges: &[(&str, &str)], + workspace_members: &[&str], +) -> CodeModel { + CodeModel { + files: files + .iter() + .map(|(name, set)| source_file(name, *set)) + .collect(), + runtime_imports: edges + .iter() + .map(|(from, to)| RuntimeImport { + importer: repo_path(from), + specifier: format!("./{to}"), + resolution: ImportResolution::Resolved(repo_path(to)), + }) + .collect(), + workspace: Workspace::new(workspace_members.iter().copied().map(repo_path)), + ..CodeModel::default() + } +} + +fn production_model(files: &[&str], edges: &[(&str, &str)]) -> CodeModel { + let entries: Vec<(&str, SourceSet)> = files + .iter() + .map(|name| (*name, SourceSet::Production)) + .collect(); + build_model(&entries, edges, &[]) +} + +fn orphan_paths(measured: &OrphanFiles) -> Vec<&str> { + measured + .findings() + .iter() + .map(|finding| finding.path.as_str()) + .collect() +} + +#[test] +fn detects_live_unreferenced_and_test_only_production_files() { + let model = build_model( + &[ + ("src/index.ts", SourceSet::Production), + ("src/live.ts", SourceSet::Production), + ("src/deep.ts", SourceSet::Production), + ("src/dead.ts", SourceSet::Production), + ("src/test_only.ts", SourceSet::Production), + ("src/test_only_dep.ts", SourceSet::Production), + ("src/test_only.test.ts", SourceSet::Test), + ("src/live.test.ts", SourceSet::Test), + ], + &[ + ("src/index.ts", "src/live.ts"), + ("src/live.ts", "src/deep.ts"), + ("src/test_only.test.ts", "src/test_only.ts"), + ("src/test_only.ts", "src/test_only_dep.ts"), + ("src/live.test.ts", "src/live.ts"), + ], + &[], + ); + + let measured = OrphanFiles::measure(&model, &[repo_path("src/index.ts")]) + .expect("entry point activates orphan-file detection"); + + assert_eq!(measured.evaluated_files(), 6); + assert_eq!(measured.entry_points(), &[repo_path("src/index.ts")]); + assert_eq!(measured.unreferenced_count(), 1); + assert_eq!(measured.test_only_count(), 2); + assert_eq!(measured.findings().len(), 3); + assert!((measured.ratio() - 0.5).abs() < 1e-9); + + let summary: Vec<(&str, OrphanFileKind, Vec<&str>)> = measured + .findings() + .iter() + .map(|f| { + ( + f.path.as_str(), + f.kind, + f.test_importers.iter().map(RepoPath::as_str).collect(), + ) + }) + .collect(); + assert_eq!( + summary, + vec![ + ("src/dead.ts", OrphanFileKind::Unreferenced, vec![]), + ( + "src/test_only.ts", + OrphanFileKind::TestOnly, + vec!["src/test_only.test.ts"], + ), + ( + "src/test_only_dep.ts", + OrphanFileKind::TestOnly, + vec!["src/test_only.test.ts"], + ), + ] + ); + assert!( + measured.findings()[1] + .message + .contains("only imported by tests") + ); +} + +#[test] +fn reachable_import_cycle_is_live_while_unreachable_import_cycle_is_orphan() { + let model = production_model( + &[ + "src/main.ts", + "src/live_a.ts", + "src/live_b.ts", + "src/dead_a.ts", + "src/dead_b.ts", + ], + &[ + ("src/main.ts", "src/live_a.ts"), + ("src/live_a.ts", "src/live_b.ts"), + ("src/live_b.ts", "src/live_a.ts"), + ("src/dead_a.ts", "src/dead_b.ts"), + ("src/dead_b.ts", "src/dead_a.ts"), + ], + ); + + let measured = OrphanFiles::measure(&model, &[repo_path("src/main.ts")]) + .expect("entry point activates detection"); + + assert_eq!( + orphan_paths(&measured), + vec!["src/dead_a.ts", "src/dead_b.ts"] + ); + assert_eq!(measured.unreferenced_count(), 2); + assert_eq!(measured.test_only_count(), 0); +} + +#[test] +fn stays_silently_inactive_when_zero_entry_points_exist() { + let model = build_model( + &[ + ("src/a.ts", SourceSet::Production), + ("src/b.ts", SourceSet::Production), + ("src/a.test.ts", SourceSet::Test), + ], + &[("src/a.test.ts", "src/a.ts")], + &[], + ); + + assert!(OrphanFiles::measure(&model, &[]).is_none()); + assert!(OrphanFiles::measure(&model, &[repo_path("src/missing.ts")]).is_none()); + assert!(OrphanFiles::measure(&model, &[repo_path("src/a.test.ts")]).is_none()); +} + +#[test] +fn excludes_generated_and_vendored_source_sets() { + let model = build_model( + &[ + ("src/index.ts", SourceSet::Production), + ("src/orphan.ts", SourceSet::Production), + ("src/schema.g.ts", SourceSet::Generated), + ("vendor/lib.ts", SourceSet::Vendored), + ], + &[], + &[], + ); + + let measured = OrphanFiles::measure(&model, &[repo_path("src/index.ts")]) + .expect("entry point activates detection"); + + assert_eq!(measured.evaluated_files(), 2); + assert_eq!(orphan_paths(&measured), vec!["src/orphan.ts"]); +} + +#[test] +fn traverses_cross_package_imports_and_skips_unrooted_isolated_packages() { + let model = build_model( + &[ + ("packages/app/src/index.ts", SourceSet::Production), + ("packages/lib/src/used.ts", SourceSet::Production), + ("packages/lib/src/unused.ts", SourceSet::Production), + ("packages/site/pages/home.ts", SourceSet::Production), + ("packages/site/pages/about.ts", SourceSet::Production), + ], + &[("packages/app/src/index.ts", "packages/lib/src/used.ts")], + &["packages/app", "packages/lib", "packages/site"], + ); + + let measured = OrphanFiles::measure(&model, &[repo_path("packages/app/src/index.ts")]) + .expect("entry point in app activates detection"); + + assert_eq!(measured.evaluated_files(), 3); + assert_eq!(orphan_paths(&measured), vec!["packages/lib/src/unused.ts"]); + + let lib_only = + OrphanFiles::measure_filtered(&model, &[repo_path("packages/app/src/index.ts")], |path| { + path.as_str().starts_with("packages/lib/") + }) + .expect("lib package stays active via cross-package import"); + assert_eq!(lib_only.evaluated_files(), 2); + assert_eq!(lib_only.findings().len(), 1); + assert_eq!( + lib_only.findings()[0].path.as_str(), + "packages/lib/src/unused.ts" + ); +} + +#[test] +fn assigns_stable_finding_ids_and_merges_across_languages() { + let ts_model = build_model( + &[ + ("web/index.ts", SourceSet::Production), + ("web/dead.ts", SourceSet::Production), + ], + &[], + &[], + ); + let py_model = build_model( + &[ + ("api/main.py", SourceSet::Production), + ("api/dead.py", SourceSet::Production), + ], + &[], + &[], + ); + + let first_ts = OrphanFiles::measure(&ts_model, &[repo_path("web/index.ts")]).expect("ts"); + let second_ts = OrphanFiles::measure(&ts_model, &[repo_path("web/index.ts")]).expect("ts"); + assert_eq!(first_ts.findings()[0].id, second_ts.findings()[0].id); + + let py = OrphanFiles::measure(&py_model, &[repo_path("api/main.py")]).expect("py"); + assert_ne!(first_ts.findings()[0].id, py.findings()[0].id); + + let merged = OrphanFiles::merge([first_ts, py]).expect("merged"); + assert_eq!(merged.evaluated_files(), 4); + assert_eq!(merged.findings().len(), 2); + assert_eq!(merged.findings()[0].path.as_str(), "api/dead.py"); + assert_eq!(merged.findings()[1].path.as_str(), "web/dead.ts"); + assert!((merged.ratio() - 0.5).abs() < 1e-9); +} diff --git a/crates/report/src/diff.rs b/crates/report/src/diff.rs index 0260e8a..0916434 100644 --- a/crates/report/src/diff.rs +++ b/crates/report/src/diff.rs @@ -12,7 +12,8 @@ use crate::measurement::{CommitMeasurement, MetricMeasurement, SourceSetMeasurem use crate::sarif::{ListedExternalMetric, ListedFindings, SarifLog}; use crate::{ BoundaryFindingRow, BudgetFailure, CloneGroupFinding, Decimal, ErodedFunctionFinding, - ExternalMetricFinding, Findings, FlaggedLineRow, ImportCycleFinding, ReportError, + ExternalMetricFinding, Findings, FlaggedLineRow, ImportCycleFinding, OrphanFileRow, + ReportError, }; mod markdown; @@ -106,6 +107,8 @@ struct SourceSetChanges { import_cycles: MetricChanges, #[serde(skip_serializing_if = "Option::is_none")] boundaries: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + orphan_files: Option>, #[serde(flatten)] external_metrics: BTreeMap, } @@ -205,6 +208,10 @@ impl DiffReport { .boundaries .as_ref() .map_or(&[], |boundaries| boundaries.new.listed.as_slice()), + orphan_files: changes + .orphan_files + .as_ref() + .map_or(&[], |orphans| orphans.new.listed.as_slice()), external_metrics: changes .external_metrics .iter() @@ -296,6 +303,12 @@ fn over_budget(source_sets: &SourceSetChangesSections, budgets: &Budgets) -> Vec .iter() .map(move |boundaries| (source_set, "boundaries", boundaries.head_ratio.0)), ) + .chain( + changes + .orphan_files + .iter() + .map(move |orphans| (source_set, "orphan_files", orphans.head_ratio.0)), + ) .chain( changes.external_metrics.iter().map(move |(key, metric)| { (source_set, key.as_str(), metric.changes.head_ratio.0) @@ -333,6 +346,9 @@ impl SourceSetChanges { if let Some(boundaries) = &self.boundaries { found.extend(boundaries.regressions(source_set, "boundaries", limits)); } + if let Some(orphan_files) = &self.orphan_files { + found.extend(orphan_files.regressions(source_set, "orphan_files", limits)); + } for (key, external) in &self.external_metrics { found.extend(external.changes.regressions(source_set, key, limits)); } @@ -459,6 +475,7 @@ fn numerator_key(metric_key: &str) -> &'static str { "verbosity" => "verbose_lines", "import_cycles" => "modules_in_import_cycles", "boundaries" => "boundary_findings", + "orphan_files" => "orphan_files", _ => "numerator", } } @@ -532,12 +549,21 @@ fn source_set_changes( shown, )), }; + let orphan_files = match (base.orphan_files, head.orphan_files) { + (None, None) => None, + (base_orphans, head_orphans) => Some(classify( + base_orphans.unwrap_or_default(), + head_orphans.unwrap_or_default(), + shown, + )), + }; SourceSetChanges { erosion: classify(base.erosion, head.erosion, shown), duplication: classify(base.duplication, head.duplication, shown), verbosity: classify(base.verbosity, head.verbosity, shown), import_cycles: classify(base.import_cycles, head.import_cycles, shown), boundaries, + orphan_files, external_metrics, } } @@ -606,6 +632,12 @@ impl Identified for BoundaryFindingRow { } } +impl Identified for OrphanFileRow { + fn id(&self) -> &str { + &self.id + } +} + fn source_set_name(source_set: SourceSet) -> &'static str { match source_set { SourceSet::Production => "Production", diff --git a/crates/report/src/diff/markdown.rs b/crates/report/src/diff/markdown.rs index 4d75479..d53c67b 100644 --- a/crates/report/src/diff/markdown.rs +++ b/crates/report/src/diff/markdown.rs @@ -3,8 +3,9 @@ use crate::Findings; use crate::markdown::{ BOUNDARY_FINDING_COLUMNS, CLONE_GROUP, ERODED_FUNCTION, ERODED_FUNCTION_COLUMNS, EXTERNAL_FINDING_COLUMNS, FINDING, FLAGGED_LINE, FLAGGED_LINE_COLUMNS, IMPORT_CYCLE, Noun, - boundary_finding_row, clone_group_item, code, eroded_function_row, external_finding_row, - flagged_line_row, import_cycle_item, list, push_findings, sentence_item, table, + ORPHAN_FILE, ORPHAN_FILE_COLUMNS, boundary_finding_row, clone_group_item, code, + eroded_function_row, external_finding_row, flagged_line_row, import_cycle_item, list, + orphan_file_row, push_findings, sentence_item, table, }; const TITLE: &str = "# codeint diff"; @@ -75,6 +76,9 @@ fn metric_rows(source_set: &str, changes: &SourceSetChanges) -> Vec> if let Some(boundaries) = &changes.boundaries { rows.push(metric_row(source_set, "Boundaries", boundaries)); } + if let Some(orphan_files) = &changes.orphan_files { + rows.push(metric_row(source_set, "Orphan files", orphan_files)); + } for external in changes.external_metrics.values() { rows.push(metric_row(source_set, &external.name, &external.changes)); } @@ -145,6 +149,20 @@ fn findings_blocks(changes: &SourceSetChanges) -> Vec { ) }); } + if let Some(orphan_files) = &changes.orphan_files { + push_changes( + &mut blocks, + "Orphan files", + orphan_files, + &ORPHAN_FILE, + |listed| { + table( + &ORPHAN_FILE_COLUMNS, + listed.iter().map(orphan_file_row).collect(), + ) + }, + ); + } for external in changes.external_metrics.values() { push_changes( &mut blocks, diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index d10085e..27f0f54 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -9,7 +9,8 @@ use codeint_config::{ use codeint_metrics::{ Boundaries, BoundaryEdgeCheck, BoundaryFinding, BoundaryPolicy, CloneGroup, Duplication, ErodedFunction, Erosion, FlaggedLineFinding, Fragment, ImportCycle, ImportCycles, - MinimumCloneTokens, MinimumDistinctTokens, UnresolvedImport, Verbosity, + MinimumCloneTokens, MinimumDistinctTokens, OrphanFileFinding, OrphanFiles, UnresolvedImport, + Verbosity, }; use codeint_model::{ CodeModel, ExternalFinding, Metric, MetricPlugin, MetricPluginError, Package, ReferenceRange, @@ -82,6 +83,14 @@ pub struct MeasuredLanguage { pub reference_ranges: ReferenceRanges, } +#[derive(Default)] +pub struct ReportOptions<'a> { + pub metric_plugins: &'a [&'a dyn MetricPlugin], + pub boundaries: Option<&'a BoundariesConfig>, + pub orphan_files: Option<&'a OrphanFiles>, + pub orphan_files_by_language: Option<&'a BTreeMap>, +} + #[derive(Debug, Serialize)] struct MeasuredSection { files: usize, @@ -127,12 +136,36 @@ struct SourceSetSection { import_cycles: ImportCyclesSection, #[serde(skip_serializing_if = "Option::is_none")] boundaries: Option, + #[serde(skip_serializing_if = "Option::is_none")] + orphan_files: Option, #[serde(flatten)] external_metrics: BTreeMap, #[serde(skip_serializing_if = "Vec::is_empty")] packages: Vec, } +#[derive(Debug, Serialize)] +struct OrphanFilesSection { + ratio: Decimal, + orphan_files: usize, + evaluated_files: usize, + entry_points: usize, + unreferenced: usize, + test_only: usize, + #[serde(flatten)] + findings: Findings, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct OrphanFileRow { + id: String, + path: String, + kind: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + test_importers: Vec, + message: String, +} + #[derive(Debug, Serialize)] struct BoundariesSection { ratio: Decimal, @@ -449,6 +482,10 @@ impl FindingKind for BoundaryFindingRow { const LIST_KEY: &'static str = "findings"; } +impl FindingKind for OrphanFileRow { + const LIST_KEY: &'static str = "findings"; +} + struct ConfigBoundaryPolicy<'config>(&'config BoundariesConfig); impl BoundaryPolicy for ConfigBoundaryPolicy<'_> { @@ -525,6 +562,46 @@ impl ExternalMetricFinding { } } +pub(crate) fn evaluate_boundaries( + model: &CodeModel, + config: Option<&BoundariesConfig>, +) -> Option { + config.map(|policy| Boundaries::measure(model, &ConfigBoundaryPolicy(policy))) +} + +impl OrphanFilesSection { + fn new(orphan_files: &OrphanFiles, shown: FindingsShown) -> OrphanFilesSection { + let all_findings = orphan_files.findings(); + let findings = mapped_findings(all_findings, shown); + OrphanFilesSection { + ratio: Decimal::rounded(orphan_files.ratio()), + orphan_files: all_findings.len(), + evaluated_files: orphan_files.evaluated_files(), + entry_points: orphan_files.entry_points().len(), + unreferenced: orphan_files.unreferenced_count(), + test_only: orphan_files.test_only_count(), + findings, + } + } +} + +impl From<&OrphanFileFinding> for OrphanFileRow { + fn from(finding: &OrphanFileFinding) -> OrphanFileRow { + let test_importers = finding + .test_importers + .iter() + .map(RepoPath::to_string) + .collect(); + OrphanFileRow { + id: finding.id.to_string(), + path: finding.path.to_string(), + kind: finding.kind.key().to_owned(), + test_importers, + message: finding.message.clone(), + } + } +} + impl SourceSetSections { fn new( source_sets: &SourceSets, @@ -532,18 +609,22 @@ impl SourceSetSections { findings: FindingsShown, metric_plugins: &[&dyn MetricPlugin], boundaries: Option<&BoundariesConfig>, + orphan_files: Option<&OrphanFiles>, ) -> Result { let mut sections = SourceSetSections::default(); for (source_set, model) in source_sets.iter() { if !model.files.is_empty() { let source_set_boundaries = boundaries.filter(|config| config.applies_to_source_set(source_set)); + let source_set_orphans = + orphan_files.filter(|_| source_set == SourceSet::Production); *sections.slot(source_set) = Some(SourceSetSection::new( model, ranges, findings, metric_plugins, source_set_boundaries, + source_set_orphans, )?); } } @@ -590,6 +671,12 @@ impl SourceSetSections { .iter() .map(move |boundaries| (source_set, "boundaries", boundaries.ratio.0)), ) + .chain( + section + .orphan_files + .iter() + .map(move |orphans| (source_set, "orphan_files", orphans.ratio.0)), + ) .chain( section .external_metrics @@ -617,12 +704,12 @@ impl SourceSetSection { findings: FindingsShown, metric_plugins: &[&dyn MetricPlugin], boundaries: Option<&BoundariesConfig>, + orphan_files: Option<&OrphanFiles>, ) -> Result { let measured = Measured::new(model); - let boundaries = boundaries.map(|config| { - let evaluated = Boundaries::measure(model, &ConfigBoundaryPolicy(config)); - BoundariesSection::new(&evaluated, findings) - }); + let boundaries = evaluate_boundaries(model, boundaries) + .map(|evaluated| BoundariesSection::new(&evaluated, findings)); + let orphan_files = orphan_files.map(|measured| OrphanFilesSection::new(measured, findings)); let mut external_metrics = BTreeMap::new(); for plugin in metric_plugins { let result = plugin.measure(model)?; @@ -653,6 +740,7 @@ impl SourceSetSection { verbosity: VerbositySection::new(&measured.verbosity, ranges, findings), import_cycles: ImportCyclesSection::new(&measured.import_cycles, ranges, findings), boundaries, + orphan_files, external_metrics, packages: package_sections(model, &measured), }) @@ -903,6 +991,7 @@ impl MeasuredSection { findings: FindingsShown, metric_plugins: &[&dyn MetricPlugin], boundaries: Option<&BoundariesConfig>, + orphan_files: Option<&OrphanFiles>, ) -> Result { let files = model.files.len(); let lines = source_lines(&model); @@ -912,6 +1001,7 @@ impl MeasuredSection { findings, metric_plugins, boundaries, + orphan_files, )?; Ok(MeasuredSection { files, @@ -956,6 +1046,27 @@ impl Report { budgets: &Budgets, metric_plugins: &[&dyn MetricPlugin], boundaries: Option<&BoundariesConfig>, + ) -> Result { + Report::summarize_with_options( + languages, + submodules, + findings, + budgets, + ReportOptions { + metric_plugins, + boundaries, + orphan_files: None, + orphan_files_by_language: None, + }, + ) + } + + pub fn summarize_with_options( + languages: Vec, + submodules: Vec, + findings: FindingsShown, + budgets: &Budgets, + options: ReportOptions<'_>, ) -> Result { let (measured, unmeasured): (Vec, Vec) = languages .into_iter() @@ -972,14 +1083,18 @@ impl Report { _ => { let mut per_language = BTreeMap::new(); for language in &measured { + let language_orphans = options + .orphan_files_by_language + .and_then(|map| map.get(&language.plugin)); per_language.insert( language.plugin.clone(), MeasuredSection::new( language.model.clone(), &ReferenceRangeScope::OneLanguage(language.reference_ranges.clone()), findings, - metric_plugins, - boundaries, + options.metric_plugins, + options.boundaries, + language_orphans, )?, ); } @@ -998,8 +1113,14 @@ impl Report { .iter() .map(RepoPath::to_string) .collect(); - let measured = - MeasuredSection::new(model, &total_ranges, findings, metric_plugins, boundaries)?; + let measured = MeasuredSection::new( + model, + &total_ranges, + findings, + options.metric_plugins, + options.boundaries, + options.orphan_files, + )?; Ok(Report { over_budget: measured.source_sets.over_budget(budgets), skipped, diff --git a/crates/report/src/markdown.rs b/crates/report/src/markdown.rs index 5b45835..5db65db 100644 --- a/crates/report/src/markdown.rs +++ b/crates/report/src/markdown.rs @@ -1,8 +1,9 @@ use crate::{ BoundaryFindingRow, CloneGroupFinding, CloneLocation, DuplicationSection, ErodedFunctionFinding, ErosionSection, ExternalMetricFinding, Findings, FlaggedLineRow, - ImportCycleFinding, ImportCyclesSection, MeasuredSection, PackageSection, ReferenceRangeEntry, - Report, SourceSetSection, SourceSetSections, UnresolvedImportRow, VerbositySection, + ImportCycleFinding, ImportCyclesSection, MeasuredSection, OrphanFileRow, PackageSection, + ReferenceRangeEntry, Report, SourceSetSection, SourceSetSections, UnresolvedImportRow, + VerbositySection, }; #[cfg(test)] @@ -42,6 +43,7 @@ pub(crate) const BOUNDARY_FINDING_COLUMNS: [&str; 6] = [ "Rule", "Reason", ]; +pub(crate) const ORPHAN_FILE_COLUMNS: [&str; 3] = ["File", "Kind", "Details"]; const UNRESOLVED_IMPORT_COLUMNS: [&str; 3] = ["Importer", "Specifier", "Reason"]; pub(crate) struct Noun { @@ -89,6 +91,10 @@ pub(crate) const FINDING: Noun = Noun { one: "Finding", many: "Findings", }; +pub(crate) const ORPHAN_FILE: Noun = Noun { + one: "orphan file", + many: "orphan files", +}; const UNRESOLVED_IMPORT: Noun = Noun { one: "unresolved import", many: "unresolved imports", @@ -316,6 +322,21 @@ fn metric_rows(source_set: &str, section: &SourceSetSection) -> Vec> "not applicable".to_string(), ]); } + if let Some(orphan_files) = §ion.orphan_files { + rows.push(vec![ + source_set.to_string(), + "Orphan files".to_string(), + orphan_files.ratio.0.to_string(), + format!( + "{} of {} evaluated files unreachable ({} unreferenced, {} test-only)", + orphan_files.orphan_files, + orphan_files.evaluated_files, + orphan_files.unreferenced, + orphan_files.test_only + ), + "not applicable".to_string(), + ]); + } for external in section.external_metrics.values() { rows.push(row( &external.name, @@ -418,6 +439,20 @@ fn findings_blocks(section: &SourceSetSection) -> Vec { }, ); } + if let Some(orphan_files) = §ion.orphan_files { + push_findings( + &mut blocks, + "Orphan files", + &orphan_files.findings, + &ORPHAN_FILE, + |listed| { + table( + &ORPHAN_FILE_COLUMNS, + listed.iter().map(orphan_file_row).collect(), + ) + }, + ); + } for external in section.external_metrics.values() { push_findings( &mut blocks, @@ -528,6 +563,21 @@ pub(crate) fn boundary_finding_row(row: &BoundaryFindingRow) -> Vec { ] } +pub(crate) fn orphan_file_row(row: &OrphanFileRow) -> Vec { + let details = if row.test_importers.is_empty() { + prose(&row.message) + } else { + let importers: Vec = row + .test_importers + .iter() + .map(String::as_str) + .map(code) + .collect(); + format!("only imported by tests: {}", importers.join(", ")) + }; + vec![code(&row.path), prose(&row.kind), details] +} + fn files_not_measured(report: &Report) -> Vec { let skipped = report .skipped diff --git a/crates/report/src/measurement.rs b/crates/report/src/measurement.rs index d5db469..83643c5 100644 --- a/crates/report/src/measurement.rs +++ b/crates/report/src/measurement.rs @@ -1,13 +1,13 @@ use std::collections::BTreeMap; use codeint_config::Boundaries as BoundariesConfig; -use codeint_metrics::Boundaries; +use codeint_metrics::OrphanFiles; use codeint_model::{CodeModel, MetricPlugin, MetricPluginError, SourceSet}; use serde::{Deserialize, Serialize}; use crate::{ - BoundaryFindingRow, CloneGroupFinding, ConfigBoundaryPolicy, ErodedFunctionFinding, - ExternalMetricFinding, FlaggedLineRow, ImportCycleFinding, Measured, + BoundaryFindingRow, CloneGroupFinding, ErodedFunctionFinding, ExternalMetricFinding, + FlaggedLineRow, ImportCycleFinding, Measured, OrphanFileRow, evaluate_boundaries, }; #[derive(Debug, Serialize, Deserialize)] @@ -27,6 +27,8 @@ pub(crate) struct SourceSetMeasurement { pub(crate) import_cycles: MetricMeasurement, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) boundaries: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) orphan_files: Option>, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub(crate) external_metrics: BTreeMap, } @@ -71,6 +73,15 @@ impl CommitMeasurement { model: CodeModel, metric_plugins: &[&dyn MetricPlugin], boundaries: Option<&BoundariesConfig>, + ) -> Result { + CommitMeasurement::of_with_options(model, metric_plugins, boundaries, None) + } + + pub fn of_with_options( + model: CodeModel, + metric_plugins: &[&dyn MetricPlugin], + boundaries: Option<&BoundariesConfig>, + orphan_files: Option<&OrphanFiles>, ) -> Result { let source_sets = model.into_source_sets(); Ok(CommitMeasurement { @@ -78,21 +89,25 @@ impl CommitMeasurement { source_sets.get(SourceSet::Production), metric_plugins, boundaries.filter(|config| config.applies_to_source_set(SourceSet::Production)), + orphan_files, )?, test: SourceSetMeasurement::of( source_sets.get(SourceSet::Test), metric_plugins, boundaries.filter(|config| config.applies_to_source_set(SourceSet::Test)), + None, )?, generated: SourceSetMeasurement::of( source_sets.get(SourceSet::Generated), metric_plugins, boundaries.filter(|config| config.applies_to_source_set(SourceSet::Generated)), + None, )?, vendored: SourceSetMeasurement::of( source_sets.get(SourceSet::Vendored), metric_plugins, boundaries.filter(|config| config.applies_to_source_set(SourceSet::Vendored)), + None, )?, }) } @@ -112,20 +127,13 @@ impl SourceSetMeasurement { model: &CodeModel, metric_plugins: &[&dyn MetricPlugin], boundaries: Option<&BoundariesConfig>, + orphan_files: Option<&OrphanFiles>, ) -> Result { let measured = Measured::new(model); - let boundaries = boundaries.map(|config| { - let evaluated = Boundaries::measure(model, &ConfigBoundaryPolicy(config)); - MetricMeasurement { - ratio: evaluated.ratio(), - numerator: evaluated.findings().len() as f64, - findings_worst_first: evaluated - .findings() - .iter() - .map(BoundaryFindingRow::from) - .collect(), - } - }); + let boundaries = evaluate_boundaries(model, boundaries) + .map(|evaluated| finding_measurement(evaluated.ratio(), evaluated.findings())); + let orphan_files = orphan_files + .map(|evaluated| finding_measurement(evaluated.ratio(), evaluated.findings())); let mut external_metrics = BTreeMap::new(); for plugin in metric_plugins { let result = plugin.measure(model)?; @@ -153,11 +161,23 @@ impl SourceSetMeasurement { verbosity: verbosity(&measured), import_cycles: import_cycles(&measured), boundaries, + orphan_files, external_metrics, }) } } +fn finding_measurement<'a, T: 'a, R: From<&'a T>>( + ratio: f64, + findings: &'a [T], +) -> MetricMeasurement { + MetricMeasurement { + ratio, + numerator: findings.len() as f64, + findings_worst_first: findings.iter().map(R::from).collect(), + } +} + fn erosion(measured: &Measured) -> MetricMeasurement { MetricMeasurement { ratio: measured.erosion.ratio(), diff --git a/crates/report/src/sarif.rs b/crates/report/src/sarif.rs index a28ca62..8aee0db 100644 --- a/crates/report/src/sarif.rs +++ b/crates/report/src/sarif.rs @@ -6,7 +6,8 @@ use codeint_model::{Metric, SourceSet}; use crate::{ BoundaryFindingRow, CloneGroupFinding, CloneLocation, ErodedFunctionFinding, - ExternalMetricFinding, FlaggedLineRow, ImportCycleFinding, Report, SourceSetSection, + ExternalMetricFinding, FlaggedLineRow, ImportCycleFinding, OrphanFileRow, Report, + SourceSetSection, }; #[cfg(test)] @@ -142,6 +143,7 @@ pub(crate) struct ListedFindings<'findings> { pub(crate) flagged_lines: &'findings [FlaggedLineRow], pub(crate) import_cycles: &'findings [ImportCycleFinding], pub(crate) boundaries: &'findings [BoundaryFindingRow], + pub(crate) orphan_files: &'findings [OrphanFileRow], pub(crate) external_metrics: Vec>, } @@ -163,6 +165,9 @@ impl SarifLog { let has_boundaries = collected .iter() .any(|(_, listed)| !listed.boundaries.is_empty()); + let has_orphan_files = collected + .iter() + .any(|(_, listed)| !listed.orphan_files.is_empty()); let mut external_rules: BTreeMap = BTreeMap::new(); for (_, listed) in &collected { for external in &listed.external_metrics { @@ -177,6 +182,11 @@ impl SarifLog { rules.push(boundaries_descriptor()); index }); + let orphan_files_rule_index = has_orphan_files.then(|| { + let index = rules.len(); + rules.push(orphan_files_descriptor()); + index + }); let mut external_rule_indices: BTreeMap = BTreeMap::new(); for (key, (name, description)) in external_rules { let index = rules.len(); @@ -215,6 +225,7 @@ impl SarifLog { *source_set, listed, boundaries_rule_index, + orphan_files_rule_index, &external_rule_indices, ) }) @@ -343,6 +354,20 @@ fn boundaries_descriptor() -> Rule { } } +fn orphan_files_descriptor() -> Rule { + Rule { + id: "orphan_files".to_owned(), + name: "Orphan files".to_owned(), + short_description: Text::from("A Production file unreachable from any entry point"), + full_description: Text::from( + "Orphan files measures the share of Production files that cannot be reached through resolved runtime imports from any manifest-declared or configured entry point, annotating files imported only by tests as test-only.", + ), + help: Text::from( + "Delete the unused Production file (and any stale tests that only import it), wire it into an entry point, or add its path glob to entry_points in codeint.json.", + ), + } +} + impl<'findings> ListedFindings<'findings> { fn of_section(section: &'findings SourceSetSection) -> ListedFindings<'findings> { ListedFindings { @@ -354,6 +379,10 @@ impl<'findings> ListedFindings<'findings> { .boundaries .as_ref() .map_or(&[], |boundaries| boundaries.findings.listed.as_slice()), + orphan_files: section + .orphan_files + .as_ref() + .map_or(&[], |orphans| orphans.findings.listed.as_slice()), external_metrics: section .external_metrics .iter() @@ -372,6 +401,7 @@ fn results( source_set: SourceSet, listed: &ListedFindings<'_>, boundaries_rule_index: Option, + orphan_files_rule_index: Option, external_rule_indices: &BTreeMap, ) -> Vec { let eroded_functions = listed.eroded_functions.iter().map(|function| { @@ -428,6 +458,27 @@ fn results( }, } }); + let orphan_files = listed.orphan_files.iter().map(|finding| SarifResult { + rule_id: "orphan_files".to_owned(), + rule_index: orphan_files_rule_index.unwrap_or_default(), + level: "note", + message: Text { + text: finding.message.clone(), + }, + locations: [Location::in_repository(&finding.path, 1, None)], + related_locations: related( + finding + .test_importers + .iter() + .map(|importer| Location::in_repository(importer, 1, None)), + ), + partial_fingerprints: PartialFingerprints { + codeint_finding_id: finding.id.clone(), + }, + properties: ResultProperties { + source_set: source_set.key(), + }, + }); let external_findings = listed.external_metrics.iter().flat_map(|external| { let rule_index = external_rule_indices .get(external.key) @@ -459,6 +510,7 @@ fn results( .chain(flagged_lines) .chain(import_cycles) .chain(boundaries) + .chain(orphan_files) .chain(external_findings) .collect() } diff --git a/crates/report/src/sarif/tests.rs b/crates/report/src/sarif/tests.rs index 78d134d..b9f1b7a 100644 --- a/crates/report/src/sarif/tests.rs +++ b/crates/report/src/sarif/tests.rs @@ -71,6 +71,7 @@ fn every_sarif_result_carries_its_finding_id_in_partial_fingerprints() { flagged_lines: &flagged, import_cycles: &cycles, boundaries: &[], + orphan_files: &[], external_metrics: Vec::new(), }; diff --git a/docs/reference.md b/docs/reference.md index 61d9650..53f5145 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -637,6 +637,7 @@ In the key paths below, `[]` stands for each item of a list, and a name in brace | `budgets.{source_set}` | object | The Budgets of this Source set; empty by default | | `budgets.{source_set}.{metric}` | number from 0 to 1 | The highest ratio of this Metric in this Source set | | `budgets.{source_set}.boundaries` | number from 0 to 1 | The highest Boundaries ratio in this Source set | +| `budgets.{source_set}.orphan_files` | number from 0 to 1 | The highest Orphan files ratio in this Source set | | `regression_limits` | object | How much each Metric may get worse in `codeint diff`; see [Regression limits](#regression-limits) | | `regression_limits.{metric}` | object | The Regression limit of this Metric in every Source set | | `regression_limits.{metric}.ratio_rise` | number from 0 to 1 | The highest ratio rise that passes | @@ -644,6 +645,9 @@ In the key paths below, `[]` stands for each item of a list, and a name in brace | `regression_limits.boundaries` | object | The Regression limit of Boundaries in every Source set | | `regression_limits.boundaries.ratio_rise` | number from 0 to 1 | The highest Boundaries ratio rise that passes | | `regression_limits.boundaries.new_findings` | string | When new Boundaries Findings are a Regression: `any_new_finding` (default), `numerator_rise_with_new_findings`, or `never` | +| `regression_limits.orphan_files` | object | The Regression limit of Orphan files in every Source set | +| `regression_limits.orphan_files.ratio_rise` | number from 0 to 1 | The highest Orphan files ratio rise that passes | +| `regression_limits.orphan_files.new_findings` | string | When new Orphan files Findings are a Regression: `any_new_finding` (default), `numerator_rise_with_new_findings`, or `never` | | `regression_limits.{source_set}` | object | The Regression limits of this Source set only | | `regression_limits.{source_set}.{metric}` | object | The Regression limit of this Metric in this Source set | | `regression_limits.{source_set}.{metric}.ratio_rise` | number from 0 to 1 | The highest ratio rise that passes | @@ -651,6 +655,9 @@ In the key paths below, `[]` stands for each item of a list, and a name in brace | `regression_limits.{source_set}.boundaries` | object | The Regression limit of Boundaries in this Source set | | `regression_limits.{source_set}.boundaries.ratio_rise` | number from 0 to 1 | The highest Boundaries ratio rise that passes | | `regression_limits.{source_set}.boundaries.new_findings` | string | When new Boundaries Findings are a Regression: `any_new_finding` (default), `numerator_rise_with_new_findings`, or `never` | +| `regression_limits.{source_set}.orphan_files` | object | The Regression limit of Orphan files in this Source set | +| `regression_limits.{source_set}.orphan_files.ratio_rise` | number from 0 to 1 | The highest Orphan files ratio rise that passes | +| `regression_limits.{source_set}.orphan_files.new_findings` | string | When new Orphan files Findings are a Regression: `any_new_finding` (default), `numerator_rise_with_new_findings`, or `never` | | `languages` | list of objects | Which Language plugin measures which folders; see [Languages](#languages) | | `languages[].plugin` | string | The name of the Language plugin, such as `typescript-javascript` | | `languages[].include` | list of strings | Globs of repository-relative folders or files that the Language plugin measures; a folder covers every file below it | @@ -674,6 +681,7 @@ In the key paths below, `[]` stands for each item of a list, and a name in brace | `boundaries.rules[].reason` | string | Optional human-readable explanation shown in boundary Findings | | `boundaries.strict_zones` | boolean | When `true`, report files in evaluated Source sets that do not match any configured zone; `false` by default | | `boundaries.source_sets` | list of strings | Source sets evaluated by boundary rules; defaults to `["production"]` when omitted or empty | +| `entry_points` | list of strings | Globs of repository-relative paths treated as additional Production entry points for Orphan files detection; empty by default | A key that the schema does not have, or a value of the wrong type, stops the run with exit code 2 and names the key. With this `codeint.json`: @@ -689,7 +697,7 @@ codeint check ``` ```text stderr -codeint: codeint.json has an unknown key budget; the keys allowed there are $schema, source_sets, budgets, regression_limits, languages, plugins, plugin_limits, boundaries +codeint: codeint.json has an unknown key budget; the keys allowed there are $schema, source_sets, budgets, regression_limits, languages, plugins, plugin_limits, boundaries, entry_points Remove the key, or correct its spelling to one of the allowed keys. ``` @@ -955,6 +963,40 @@ In `codeint diff`, each boundary Finding carries a stable content-based identifi codeint check ``` +### Orphan files + +Orphan files detection traverses resolved runtime imports from the union of manifest-declared entry points (such as `package.json`, `Cargo.toml`, `pyproject.toml`, `composer.json`, and `pubspec.yaml`) and configured `entry_points` globs in `codeint.json`. +Production files unreachable from any Production entry point are reported as `unreferenced`, or as `test-only` when still imported by Test files. +Generated and Vendored Source sets are excluded, and when no entry points exist for a language or isolated Workspace package, Orphan files reporting stays silently inactive. +In `codeint diff`, each Orphan files Finding carries a stable `id` so pre-existing orphans remain unchanged while newly introduced orphans fail by default (`new_findings: "any_new_finding"`). + +```json codeint.json +{ + "entry_points": ["src/*.ts"], + "budgets": { + "production": { + "orphan_files": 0 + } + }, + "regression_limits": { + "orphan_files": { + "ratio_rise": 0.01, + "new_findings": "any_new_finding" + }, + "production": { + "orphan_files": { + "ratio_rise": 0, + "new_findings": "any_new_finding" + } + } + } +} +``` + +```sh exit=0 +codeint check +``` + ## Result cache codeint caches the measurement of each commit it reads from Git objects, so a second `codeint diff` against the same base reads it back instead of measuring the commit again. diff --git a/schema/codeint.schema.json b/schema/codeint.schema.json index 1e269a7..fc724f3 100644 --- a/schema/codeint.schema.json +++ b/schema/codeint.schema.json @@ -59,6 +59,13 @@ "boundaries": { "$ref": "#/$defs/BoundariesFile", "description": "Architectural import boundaries defining named zones, optional public_files entry points, directional allow or deny rules, and optional strict_zones mode." + }, + "entry_points": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Globs of repository-relative paths treated as additional Production entry points for Orphan files detection, combined with manifest-discovered entry points." } }, "title": "codeint.json", @@ -166,6 +173,13 @@ "description": "The highest Boundaries ratio, from 0 to 1.", "minimum": 0, "maximum": 1 + }, + "orphan_files": { + "type": "number", + "format": "double", + "description": "The highest Orphan files ratio, from 0 to 1.", + "minimum": 0, + "maximum": 1 } }, "additionalProperties": { @@ -201,6 +215,10 @@ "$ref": "#/$defs/RegressionLimitSetting", "description": "The Regression limit of Boundaries in every Source set." }, + "orphan_files": { + "$ref": "#/$defs/RegressionLimitSetting", + "description": "The Regression limit of Orphan files in every Source set." + }, "production": { "$ref": "#/$defs/MetricRegressionLimits", "description": "The Regression limits of the Production Source set." @@ -269,6 +287,10 @@ "boundaries": { "$ref": "#/$defs/RegressionLimitSetting", "description": "The Regression limit of Boundaries in this Source set." + }, + "orphan_files": { + "$ref": "#/$defs/RegressionLimitSetting", + "description": "The Regression limit of Orphan files in this Source set." } }, "additionalProperties": { From dd9286f40d8462a9c264c462dc08006c62d93141 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 15:33:19 +0800 Subject: [PATCH 4/5] fix: harden entry point discovery and require production orphan roots - Require SourceSet::Production in orphan_files::collect_roots so generated and vendored files do not activate orphan detection. - Reject parent-traversal segments in TS, Rust, PHP, and Python manifest entry points, and reject path separators or parent segments in Rust bin names. - Include src/lib.rs in Rust when autolib = false and an explicit [lib] table omits path. - Subtract null-excluded subpaths from wildcard package.json exports matches in TS. --- crates/metrics/src/orphan_files.rs | 2 +- crates/metrics/src/orphan_files/tests.rs | 55 ++++++++ plugins/languages/php/src/entry_points.rs | 6 +- plugins/languages/php/tests/entry_points.rs | 22 +++ plugins/languages/python/src/entry_points.rs | 15 +- .../languages/python/tests/entry_points.rs | 19 +++ plugins/languages/rust/src/entry_points.rs | 17 ++- plugins/languages/rust/tests/entry_points.rs | 49 +++++++ plugins/languages/ts/src/entry_points.rs | 132 +++++++++++++++--- plugins/languages/ts/tests/entry_points.rs | 89 ++++++++++++ 10 files changed, 380 insertions(+), 26 deletions(-) diff --git a/crates/metrics/src/orphan_files.rs b/crates/metrics/src/orphan_files.rs index 1ba820a..70580c6 100644 --- a/crates/metrics/src/orphan_files.rs +++ b/crates/metrics/src/orphan_files.rs @@ -219,7 +219,7 @@ fn collect_roots( let mut roots = BTreeSet::new(); for entry in entry_points { if let Some(&index) = index_of.get(entry) - && source_sets[index] != SourceSet::Test + && source_sets[index] == SourceSet::Production { roots.insert(index); } diff --git a/crates/metrics/src/orphan_files/tests.rs b/crates/metrics/src/orphan_files/tests.rs index 955a27a..dc9ed1a 100644 --- a/crates/metrics/src/orphan_files/tests.rs +++ b/crates/metrics/src/orphan_files/tests.rs @@ -196,6 +196,61 @@ fn excludes_generated_and_vendored_source_sets() { assert_eq!(orphan_paths(&measured), vec!["src/orphan.ts"]); } +#[test] +fn generated_and_vendored_entry_points_do_not_activate_orphan_detection() { + let single = build_model( + &[ + ("app/main.ts", SourceSet::Production), + ("app/util.ts", SourceSet::Production), + ("app/types.g.ts", SourceSet::Generated), + ("vendor/pkg.ts", SourceSet::Vendored), + ], + &[], + &[], + ); + for candidates in [ + vec![repo_path("app/types.g.ts")], + vec![repo_path("vendor/pkg.ts")], + vec![repo_path("app/types.g.ts"), repo_path("vendor/pkg.ts")], + ] { + assert!(OrphanFiles::measure(&single, &candidates).is_none()); + } + + let workspace = build_model( + &[ + ("mods/web/main.ts", SourceSet::Production), + ("mods/web/unused.ts", SourceSet::Production), + ("mods/gen/service.ts", SourceSet::Production), + ("mods/gen/router.g.ts", SourceSet::Generated), + ("mods/gen/vendor/entry.ts", SourceSet::Vendored), + ], + &[], + &["mods/web", "mods/gen"], + ); + let measured = OrphanFiles::measure( + &workspace, + &[ + repo_path("mods/web/main.ts"), + repo_path("mods/gen/router.g.ts"), + repo_path("mods/gen/vendor/entry.ts"), + ], + ) + .expect("production root activates detection"); + + assert_eq!( + ( + measured.entry_points(), + measured.evaluated_files(), + orphan_paths(&measured), + ), + ( + &[repo_path("mods/web/main.ts")][..], + 2, + vec!["mods/web/unused.ts"], + ) + ); +} + #[test] fn traverses_cross_package_imports_and_skips_unrooted_isolated_packages() { let model = build_model( diff --git a/plugins/languages/php/src/entry_points.rs b/plugins/languages/php/src/entry_points.rs index fee3bf8..c294f42 100644 --- a/plugins/languages/php/src/entry_points.rs +++ b/plugins/languages/php/src/entry_points.rs @@ -44,7 +44,11 @@ fn bin_strings(value: &Value) -> Vec { fn resolve_composer_bin(base_dir: &str, raw: &str, available: &HashSet<&str>) -> Option { let trimmed = raw.trim(); - if trimmed.is_empty() || trimmed.starts_with('/') || trimmed.contains('\\') { + if trimmed.is_empty() + || trimmed.starts_with('/') + || trimmed.contains('\\') + || trimmed.split('/').any(|segment| segment == "..") + { return None; } let normalized = normalize_relative_path(base_dir, trimmed)?; diff --git a/plugins/languages/php/tests/entry_points.rs b/plugins/languages/php/tests/entry_points.rs index 24741c7..41b5e2b 100644 --- a/plugins/languages/php/tests/entry_points.rs +++ b/plugins/languages/php/tests/entry_points.rs @@ -74,3 +74,25 @@ fn returns_empty_when_composer_manifest_has_no_bin_or_is_invalid() { .sum::(); assert_eq!(empty_count, 0); } + +#[test] +fn rejects_parent_traversal_in_nested_composer_bin() { + let files = [ + RepoPath::new("packages/cli/composer.json").unwrap(), + RepoPath::new("packages/cli/bin/run.php").unwrap(), + RepoPath::new("packages/other/secret.php").unwrap(), + ]; + let entries = Php + .entry_points( + &files, + vec![Manifest { + path: "packages/cli/composer.json".into(), + text: r#"{"name": "acme/cli", "bin": ["../other/secret.php", "./../other/secret.php", "bin/../../other/secret.php", "bin/run.php"]}"#.into(), + }], + ) + .expect("entry points"); + assert_eq!( + entries, + [RepoPath::new("packages/cli/bin/run.php").unwrap()] + ); +} diff --git a/plugins/languages/python/src/entry_points.rs b/plugins/languages/python/src/entry_points.rs index 9aa1f2f..889be03 100644 --- a/plugins/languages/python/src/entry_points.rs +++ b/plugins/languages/python/src/entry_points.rs @@ -202,7 +202,11 @@ fn resolve_package_dir( found: &mut BTreeSet, ) { let trimmed = pkg.trim(); - if trimmed.is_empty() || trimmed.starts_with('/') || trimmed.contains('\\') { + if trimmed.is_empty() + || trimmed.starts_with('/') + || trimmed.contains('\\') + || trimmed.split('/').any(|segment| segment == "..") + { return; } let rel_pkg = if trimmed.contains('/') { @@ -221,7 +225,14 @@ fn resolve_package_dir( fn candidate_package_roots(base_dir: &str, from: Option<&str>, has_slash: bool) -> Vec { if let Some(from_dir) = from { - return normalize_relative_path(base_dir, from_dir.trim()) + let trimmed = from_dir.trim(); + if trimmed.starts_with('/') + || trimmed.contains('\\') + || trimmed.split('/').any(|segment| segment == "..") + { + return Vec::new(); + } + return normalize_relative_path(base_dir, trimmed) .into_iter() .collect(); } diff --git a/plugins/languages/python/tests/entry_points.rs b/plugins/languages/python/tests/entry_points.rs index f6ddcd0..8f688ef 100644 --- a/plugins/languages/python/tests/entry_points.rs +++ b/plugins/languages/python/tests/entry_points.rs @@ -88,3 +88,22 @@ fn returns_empty_when_pyproject_declares_no_entry_points_or_is_invalid() { Vec::::new() ); } + +#[test] +fn rejects_parent_traversal_in_nested_pyproject_entries() { + let repo = [ + "packages/app/pyproject.toml", + "packages/app/src/app/__init__.py", + "packages/other/secret/__init__.py", + "packages/other/secret.py", + ] + .map(|item| RepoPath::new(item).unwrap()); + let pyproject = Manifest { + path: "packages/app/pyproject.toml".to_owned(), + text: "[project]\nname = \"app\"\n[project.scripts]\nescape = \"../other.secret:main\"\ndotted = \"..other.secret:main\"\n[tool.setuptools]\npackages = [\"../other/secret\"]\n[tool.hatch.build.targets.wheel]\npackages = [\"src/../../other/secret\"]\n[tool.poetry]\npackages = [{ include = \"../other/secret\" }, { include = \"secret\", from = \"../other\" }, { include = \"app\", from = \"src\" }]\n".to_owned(), + }; + assert_eq!( + Python.entry_points(&repo, vec![pyproject]).unwrap(), + [RepoPath::new("packages/app/src/app/__init__.py").unwrap()] + ); +} diff --git a/plugins/languages/rust/src/entry_points.rs b/plugins/languages/rust/src/entry_points.rs index 30a29ca..159291f 100644 --- a/plugins/languages/rust/src/entry_points.rs +++ b/plugins/languages/rust/src/entry_points.rs @@ -57,7 +57,11 @@ struct CrateTargetIndex<'a> { impl CrateTargetIndex<'_> { fn record(&self, base_dir: &str, rel: &str, out: &mut BTreeSet) -> bool { let trimmed = rel.trim(); - if trimmed.is_empty() || trimmed.starts_with('/') || trimmed.contains('\\') { + if trimmed.is_empty() + || trimmed.starts_with('/') + || trimmed.contains('\\') + || trimmed.split('/').any(|segment| segment == "..") + { return false; } let Some(candidate) = normalize_relative_path(base_dir, trimmed) else { @@ -104,7 +108,7 @@ impl CargoTargets { }; if let Some(explicit) = self.lib.as_ref().and_then(|spec| spec.path.as_deref()) { index.record(base_dir, explicit, out); - } else if package.autolib != Some(false) { + } else if self.lib.is_some() || package.autolib != Some(false) { index.record(base_dir, "src/lib.rs", out); } for bin in &self.bin { @@ -128,6 +132,15 @@ fn record_named_bin( bin_name: &str, out: &mut BTreeSet, ) { + let bin_name = bin_name.trim(); + if bin_name.is_empty() + || bin_name.contains('/') + || bin_name.contains('\\') + || bin_name == "." + || bin_name == ".." + { + return; + } let direct = format!("src/bin/{bin_name}.rs"); if index.record(base_dir, &direct, out) { return; diff --git a/plugins/languages/rust/tests/entry_points.rs b/plugins/languages/rust/tests/entry_points.rs index 451f96e..137b8b8 100644 --- a/plugins/languages/rust/tests/entry_points.rs +++ b/plugins/languages/rust/tests/entry_points.rs @@ -104,3 +104,52 @@ fn handles_root_crate_empty_targets_and_invalid_manifests() { ); } } + +fn cargo_entries(paths: &[&str], manifest_path: &str, text: &str) -> Vec { + let repo: Vec = paths + .iter() + .map(|raw| RepoPath::new(*raw).unwrap()) + .collect(); + Rust.entry_points( + &repo, + vec![Manifest { + path: manifest_path.into(), + text: text.into(), + }], + ) + .unwrap() + .into_iter() + .map(|entry| entry.as_str().to_owned()) + .collect() +} + +#[test] +fn rejects_parent_traversal_in_nested_cargo_paths_and_bin_names() { + let entries = cargo_entries( + &[ + "crates/app/Cargo.toml", + "crates/app/src/main.rs", + "crates/app/src/secret.rs", + "crates/app/src/bin/sub/tool.rs", + "crates/other/src/lib.rs", + "crates/other/src/main.rs", + ], + "crates/app/Cargo.toml", + "[package]\nname = \"app\"\nautolib = false\nautobins = false\n[lib]\npath = \"../other/src/lib.rs\"\n[[bin]]\nname = \"escape_path\"\npath = \"../other/src/main.rs\"\n[[bin]]\nname = \"../secret\"\n[[bin]]\nname = \"../../other/src/main\"\n[[bin]]\nname = \"sub/tool\"\n[[bin]]\nname = \"..\"\n", + ); + assert!(entries.is_empty()); +} + +#[test] +fn includes_default_lib_when_autolib_is_false_and_lib_table_has_no_path() { + let entries = cargo_entries( + &[ + "crates/explicit_lib/Cargo.toml", + "crates/explicit_lib/src/lib.rs", + "crates/explicit_lib/src/main.rs", + ], + "crates/explicit_lib/Cargo.toml", + "[package]\nname = \"explicit_lib\"\nautolib = false\nautobins = false\n[lib]\ncrate-type = [\"cdylib\"]\n", + ); + assert_eq!(entries, ["crates/explicit_lib/src/lib.rs"]); +} diff --git a/plugins/languages/ts/src/entry_points.rs b/plugins/languages/ts/src/entry_points.rs index 95c0ef1..077acf4 100644 --- a/plugins/languages/ts/src/entry_points.rs +++ b/plugins/languages/ts/src/entry_points.rs @@ -79,19 +79,49 @@ impl<'a> TsEntryFinder<'a> { } fn collect_exports(&mut self, base_dir: &str, value: &Value) { + if let Value::Object(map) = value { + let exclusions: Vec<&str> = map + .iter() + .filter(|(key, item)| key.starts_with('.') && item.is_null()) + .map(|(key, _)| key.as_str()) + .collect(); + for (key, item) in map { + if item.is_null() { + continue; + } + let export_key = key.starts_with('.').then_some(key.as_str()); + let active_exclusions = if export_key.is_some() { + exclusions.as_slice() + } else { + &[] + }; + self.collect_export_target(base_dir, export_key, active_exclusions, item); + } + return; + } + self.collect_export_target(base_dir, None, &[], value); + } + + fn collect_export_target( + &mut self, + base_dir: &str, + export_key: Option<&str>, + exclusions: &[&str], + value: &Value, + ) { match value { Value::String(target) if target.contains('*') => { - self.resolve_wildcard_export(base_dir, target); + self.resolve_wildcard_export(base_dir, target, export_key, exclusions); } Value::String(target) => self.resolve_source_target(base_dir, target), Value::Array(items) => { for item in items { - self.collect_exports(base_dir, item); + self.collect_export_target(base_dir, export_key, exclusions, item); } } Value::Object(map) => { for item in map.values() { - self.collect_exports(base_dir, item); + self.collect_export_target(base_dir, export_key, exclusions, item); } } _ => {} @@ -165,28 +195,22 @@ impl<'a> TsEntryFinder<'a> { None } - fn resolve_wildcard_export(&mut self, base_dir: &str, raw: &str) { - if raw.starts_with('/') || raw.contains('\\') { - return; - } - let Some((prefix_raw, suffix)) = raw.split_once('*') else { - return; - }; - if suffix.contains('*') { - return; - } - let Some(normalized_prefix) = normalize_relative_path(base_dir, prefix_raw) else { + fn resolve_wildcard_export( + &mut self, + base_dir: &str, + raw: &str, + export_key: Option<&str>, + exclusions: &[&str], + ) { + let Some((prefix, suffix)) = wildcard_prefix(base_dir, raw) else { return; }; - let prefix = if prefix_raw.ends_with('/') && !normalized_prefix.is_empty() { - format!("{normalized_prefix}/") - } else { - normalized_prefix - }; + let key_parts = export_key.and_then(split_single_wildcard); for path in self.paths { if let Some(matched_suffix) = wildcard_suffix_match(path, &prefix, suffix) && path.len() > prefix.len() + matched_suffix.len() && is_ts_source_file(path, self.extensions) + && !is_excluded_export(path, &prefix, matched_suffix, key_parts, exclusions) { self.entries.insert(path.clone()); } @@ -194,6 +218,70 @@ impl<'a> TsEntryFinder<'a> { } } +fn split_single_wildcard(pattern: &str) -> Option<(&str, &str)> { + let (prefix, suffix) = pattern.split_once('*')?; + (!suffix.contains('*')).then_some((prefix, suffix)) +} + +fn has_parent_segment(path: &str) -> bool { + path.split('/').any(|segment| segment == "..") +} + +fn wildcard_prefix<'a>(base_dir: &str, raw: &'a str) -> Option<(String, &'a str)> { + let trimmed = raw.trim(); + if trimmed.starts_with('/') || trimmed.contains('\\') { + return None; + } + let (prefix_raw, suffix) = split_single_wildcard(trimmed)?; + if has_parent_segment(prefix_raw) || has_parent_segment(suffix) { + return None; + } + let normalized_prefix = normalize_relative_path(base_dir, prefix_raw)?; + let prefix = if prefix_raw.ends_with('/') && !normalized_prefix.is_empty() { + format!("{normalized_prefix}/") + } else { + normalized_prefix + }; + Some((prefix, suffix)) +} + +fn is_excluded_export( + path: &str, + prefix: &str, + matched_suffix: &str, + key_parts: Option<(&str, &str)>, + exclusions: &[&str], +) -> bool { + let Some((key_prefix, key_suffix)) = key_parts else { + return false; + }; + if exclusions.is_empty() { + return false; + } + let captured = &path[prefix.len()..path.len() - matched_suffix.len()]; + let subpath = format!("{key_prefix}{captured}{key_suffix}"); + exclusions.iter().any(|&exclusion| { + matches_exclusion(&subpath, exclusion, key_prefix.len(), key_suffix.len()) + }) +} + +fn matches_exclusion( + subpath: &str, + exclusion: &str, + key_prefix_len: usize, + key_suffix_len: usize, +) -> bool { + let Some((excl_prefix, excl_suffix)) = split_single_wildcard(exclusion) else { + return subpath == exclusion; + }; + let more_specific = excl_prefix.len() > key_prefix_len + || (excl_prefix.len() == key_prefix_len && excl_suffix.len() >= key_suffix_len); + more_specific + && subpath.starts_with(excl_prefix) + && subpath.ends_with(excl_suffix) + && subpath.len() >= excl_prefix.len() + excl_suffix.len() +} + fn wildcard_suffix_match<'a>(path: &str, prefix: &str, suffix: &'a str) -> Option<&'a str> { if !path.starts_with(prefix) { return None; @@ -215,7 +303,11 @@ fn wildcard_suffix_match<'a>(path: &str, prefix: &str, suffix: &'a str) -> Optio fn normalize_entry_path(base_dir: &str, raw: &str) -> Option { let trimmed = raw.trim(); - if trimmed.is_empty() || trimmed.starts_with('/') || trimmed.contains('\\') { + if trimmed.is_empty() + || trimmed.starts_with('/') + || trimmed.contains('\\') + || has_parent_segment(trimmed) + { return None; } let normalized = normalize_relative_path(base_dir, trimmed)?; diff --git a/plugins/languages/ts/tests/entry_points.rs b/plugins/languages/ts/tests/entry_points.rs index 09a1264..25904df 100644 --- a/plugins/languages/ts/tests/entry_points.rs +++ b/plugins/languages/ts/tests/entry_points.rs @@ -129,3 +129,92 @@ fn returns_empty_when_package_json_declares_no_entry_points_or_is_invalid() { ); } } + +fn discover_ts(paths: &[&str], manifests: &[(&str, &str)]) -> Vec { + let repo: Vec = paths.iter().map(|p| RepoPath::new(*p).unwrap()).collect(); + let specs = manifests + .iter() + .map(|(path, text)| Manifest { + path: (*path).into(), + text: (*text).into(), + }) + .collect(); + TypeScriptAndJavaScript + .entry_points(&repo, specs) + .unwrap() + .into_iter() + .map(|entry| entry.as_str().to_owned()) + .collect() +} + +#[test] +fn rejects_parent_traversal_in_nested_package_json_entries() { + let app_pkg = r#"{ + "name": "@demo/app", + "main": "../other/secret.ts", + "module": "./../other/secret.ts", + "bin": { "bad": "../other/bin.js" }, + "exports": { + ".": "./src/index.ts", + "./escape": "../other/secret.ts", + "./wild/*": "../other/wild/*.ts", + "./dotdot/*": "./../*.ts" + } + }"#; + let found = discover_ts( + &[ + "packages/app/package.json", + "packages/app/src/index.ts", + "packages/other/secret.ts", + "packages/other/bin.js", + "packages/other/wild/a.ts", + ], + &[("packages/app/package.json", app_pkg)], + ); + assert_eq!(found, ["packages/app/src/index.ts"]); +} + +#[test] +fn subtracts_null_excluded_subpaths_from_wildcard_exports() { + let root_pkg = r#"{ + "name": "demo", + "exports": { + "./*": { "import": "./src/*.js" }, + "./secret": null, + "./internal/*": null, + "./internal/public/*": "./src/internal/public/*.ts" + } + }"#; + let lib_pkg = r#"{ + "name": "@demo/lib", + "exports": { + "./*.js": "./src/*.ts", + "./private/*.js": null + } + }"#; + let found = discover_ts( + &[ + "package.json", + "src/public.ts", + "src/secret.ts", + "src/internal/helper.ts", + "src/internal/deep/util.ts", + "src/internal/public/api.ts", + "packages/lib/package.json", + "packages/lib/src/open.ts", + "packages/lib/src/private/hidden.ts", + ], + &[ + ("package.json", root_pkg), + ("packages/lib/package.json", lib_pkg), + ], + ); + assert_eq!( + found, + [ + "packages/lib/src/open.ts", + "src/internal/public/api.ts", + "src/public.ts", + ] + ); +} From ddddcd3e95f67887437d082f5102d0b425d729f6 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 15:56:03 +0800 Subject: [PATCH 5/5] fix(lang-ts): contain nested package entry points and handle nested null exports --- plugins/languages/ts/src/entry_points.rs | 73 ++++++++++++++------ plugins/languages/ts/tests/entry_points.rs | 79 ++++++++++++++++++++++ 2 files changed, 132 insertions(+), 20 deletions(-) diff --git a/plugins/languages/ts/src/entry_points.rs b/plugins/languages/ts/src/entry_points.rs index 077acf4..f309d29 100644 --- a/plugins/languages/ts/src/entry_points.rs +++ b/plugins/languages/ts/src/entry_points.rs @@ -82,11 +82,11 @@ impl<'a> TsEntryFinder<'a> { if let Value::Object(map) = value { let exclusions: Vec<&str> = map .iter() - .filter(|(key, item)| key.starts_with('.') && item.is_null()) + .filter(|(key, item)| key.starts_with('.') && is_null_exclusion(item)) .map(|(key, _)| key.as_str()) .collect(); for (key, item) in map { - if item.is_null() { + if is_null_exclusion(item) { continue; } let export_key = key.starts_with('.').then_some(key.as_str()); @@ -132,34 +132,39 @@ impl<'a> TsEntryFinder<'a> { let Some(candidate) = normalize_entry_path(base_dir, raw) else { return; }; - if self.file_set.contains(candidate.as_str()) + if is_nested_candidate(base_dir, &candidate) + && self.file_set.contains(candidate.as_str()) && (is_ts_source_file(&candidate, self.extensions) || has_no_extension(&candidate)) { self.entries.insert(candidate); return; } - self.resolve_source_candidate(&candidate); + self.resolve_source_candidate(base_dir, &candidate); } fn resolve_source_target(&mut self, base_dir: &str, raw: &str) { if let Some(candidate) = normalize_entry_path(base_dir, raw) { - self.resolve_source_candidate(&candidate); + self.resolve_source_candidate(base_dir, &candidate); } } - fn resolve_source_candidate(&mut self, candidate: &str) { + fn resolve_source_candidate(&mut self, base_dir: &str, candidate: &str) { if is_declaration_file(candidate) { return; } - if self.file_set.contains(candidate) && is_ts_source_file(candidate, self.extensions) { + let allow_file = is_nested_candidate(base_dir, candidate); + if allow_file + && self.file_set.contains(candidate) + && is_ts_source_file(candidate, self.extensions) + { self.entries.insert(candidate.to_owned()); return; } - if let Some(aliased) = self.resolve_output_alias(candidate) { + if allow_file && let Some(aliased) = self.resolve_output_alias(candidate) { self.entries.insert(aliased); return; } - if let Some(expanded) = self.resolve_extension_or_index(candidate) { + if let Some(expanded) = self.resolve_extension_or_index(candidate, allow_file) { self.entries.insert(expanded); } } @@ -179,11 +184,13 @@ impl<'a> TsEntryFinder<'a> { None } - fn resolve_extension_or_index(&self, candidate: &str) -> Option { - for ext in self.extensions { - let with_ext = format!("{candidate}.{ext}"); - if self.file_set.contains(with_ext.as_str()) && !is_declaration_file(&with_ext) { - return Some(with_ext); + fn resolve_extension_or_index(&self, candidate: &str, allow_extension: bool) -> Option { + if allow_extension { + for ext in self.extensions { + let with_ext = format!("{candidate}.{ext}"); + if self.file_set.contains(with_ext.as_str()) && !is_declaration_file(&with_ext) { + return Some(with_ext); + } } } for ext in self.extensions { @@ -207,7 +214,8 @@ impl<'a> TsEntryFinder<'a> { }; let key_parts = export_key.and_then(split_single_wildcard); for path in self.paths { - if let Some(matched_suffix) = wildcard_suffix_match(path, &prefix, suffix) + if is_within_base_dir(base_dir, path) + && let Some(matched_suffix) = wildcard_suffix_match(path, &prefix, suffix) && path.len() > prefix.len() + matched_suffix.len() && is_ts_source_file(path, self.extensions) && !is_excluded_export(path, &prefix, matched_suffix, key_parts, exclusions) @@ -218,6 +226,26 @@ impl<'a> TsEntryFinder<'a> { } } +fn is_null_exclusion(value: &Value) -> bool { + match value { + Value::Null => true, + Value::Array(items) => !items.is_empty() && items.iter().all(is_null_exclusion), + Value::Object(map) => !map.is_empty() && map.values().all(is_null_exclusion), + _ => false, + } +} + +fn is_nested_candidate(base_dir: &str, candidate: &str) -> bool { + base_dir.is_empty() || candidate != base_dir +} + +fn is_within_base_dir(base_dir: &str, path: &str) -> bool { + base_dir.is_empty() + || path + .strip_prefix(base_dir) + .is_some_and(|rest| rest.starts_with('/')) +} + fn split_single_wildcard(pattern: &str) -> Option<(&str, &str)> { let (prefix, suffix) = pattern.split_once('*')?; (!suffix.contains('*')).then_some((prefix, suffix)) @@ -227,6 +255,15 @@ fn has_parent_segment(path: &str) -> bool { path.split('/').any(|segment| segment == "..") } +fn ensure_wildcard_slash(base_dir: &str, prefix_raw: &str, normalized_prefix: String) -> String { + if !normalized_prefix.is_empty() && (prefix_raw.ends_with('/') || normalized_prefix == base_dir) + { + format!("{normalized_prefix}/") + } else { + normalized_prefix + } +} + fn wildcard_prefix<'a>(base_dir: &str, raw: &'a str) -> Option<(String, &'a str)> { let trimmed = raw.trim(); if trimmed.starts_with('/') || trimmed.contains('\\') { @@ -237,11 +274,7 @@ fn wildcard_prefix<'a>(base_dir: &str, raw: &'a str) -> Option<(String, &'a str) return None; } let normalized_prefix = normalize_relative_path(base_dir, prefix_raw)?; - let prefix = if prefix_raw.ends_with('/') && !normalized_prefix.is_empty() { - format!("{normalized_prefix}/") - } else { - normalized_prefix - }; + let prefix = ensure_wildcard_slash(base_dir, prefix_raw, normalized_prefix); Some((prefix, suffix)) } diff --git a/plugins/languages/ts/tests/entry_points.rs b/plugins/languages/ts/tests/entry_points.rs index 25904df..cacc1a6 100644 --- a/plugins/languages/ts/tests/entry_points.rs +++ b/plugins/languages/ts/tests/entry_points.rs @@ -218,3 +218,82 @@ fn subtracts_null_excluded_subpaths_from_wildcard_exports() { ] ); } + +fn assert_discovered(paths: &[&str], manifests: &[(&str, &str)], expected: &[&str]) { + assert_eq!(discover_ts(paths, manifests), expected); +} + +#[test] +fn wildcard_exports_in_nested_package_do_not_escape_to_sibling_directories() { + assert_discovered( + &[ + "packages/app/package.json", + "packages/app/index.ts", + "packages/app-other/secret.ts", + "packages/dot/package.json", + "packages/dot/local.ts", + "packages/dot-other/secret.ts", + ], + &[ + ( + "packages/app/package.json", + r#"{"name":"@demo/app","exports":{"./*":"*.ts"}}"#, + ), + ( + "packages/dot/package.json", + r#"{"name":"@demo/dot","exports":{"./*":"./.*.ts"}}"#, + ), + ], + &["packages/app/index.ts", "packages/dot/local.ts"], + ); +} + +#[test] +fn subtracts_nested_conditional_and_array_null_exclusions_from_wildcard_exports() { + let pkg = r#"{ + "name": "demo", + "exports": { + "./*": "./src/*.ts", + "./internal/*": { "default": null }, + "./dual/*": { "import": null, "require": null }, + "./blocked/*": [null], + "./mixed/*": { "import": null, "default": "./src/mixed/*.ts" } + } + }"#; + assert_discovered( + &[ + "package.json", + "src/public.ts", + "src/internal/secret.ts", + "src/dual/hidden.ts", + "src/blocked/nope.ts", + "src/mixed/ok.ts", + ], + &[("package.json", pkg)], + &["src/mixed/ok.ts", "src/public.ts"], + ); +} + +#[test] +fn nested_package_dot_main_resolves_package_index_instead_of_sibling_file() { + for (manifest, pkg_path, sibling, index) in [ + ( + r#"{"name":"@demo/app","main":"./"}"#, + "packages/app/package.json", + "packages/app.ts", + "packages/app/index.ts", + ), + ( + r#"{"name":"@demo/lib","main":".","bin":"./"}"#, + "packages/lib/package.json", + "packages/lib.ts", + "packages/lib/index.ts", + ), + ] { + assert_discovered( + &[pkg_path, sibling, index], + &[(pkg_path, manifest)], + &[index], + ); + } +}