diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a3e226a1..6bcbe6e6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -47,7 +47,7 @@ People and coding agents follow the same rules in this repository: read [.rules] ## Adding a Language or Metric plugin -Read [docs/plugins.md](./docs/plugins.md) to build an external WebAssembly Plugin against `codeint:plugin@0.2.0`, or inspect `plugins/languages/` to see how built-in Language plugins implement the Code model contract. +Read [docs/plugins.md](./docs/plugins.md) to build an external WebAssembly Plugin against `codeint:plugin@0.3.0`, or inspect `plugins/languages/` to see how built-in Language plugins implement the Code model contract. ## Code of Conduct diff --git a/GLOSSARY.md b/GLOSSARY.md index 1e833933..5b7ec03b 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -76,7 +76,7 @@ A directional rule or public-file constraint governing which architectural zones _Avoid_: layer rule, module fence **Orphan file**: -A Production source file unreachable through runtime imports from any manifest-declared or configured entry point, classified as unreferenced or test-only. +A Production source file unreachable through runtime imports from any manifest-declared, program-start, or configured entry point, classified as unreferenced or test-only. _Avoid_: dead file, unused file **Dependency hygiene**: diff --git a/README.md b/README.md index c3248583..74bdaae0 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ Four core Metrics are calibrated against pre-2023 human-written repositories: Additional independent Metrics and structural checks run in the same pass: - **Cognitive complexity**: share of total nesting-weighted cognitive complexity held by functions scoring over 15. -- **Orphan files**: Production files unreachable from manifest-declared and configured `entry_points`, classified as `unreferenced` or `test-only`. +- **Orphan files**: Production files unreachable from manifest-declared, program-start, and configured `entry_points`, classified as `unreferenced` or `test-only`. - **Dependency hygiene**: three independent Metrics (`unused_dependencies`, `unlisted_dependencies`, and `dev_in_production_dependencies`) comparing `package.json`, `Cargo.toml`, `pyproject.toml`, `composer.json`, and `pubspec.yaml` against imported external packages while excluding standard-library built-ins. - **Architectural import boundaries**: named zones, built-in `layered` and `hexagonal` presets, `public_files` encapsulation, directional `allow`/`deny` rules, and pre-edit `codeint guard ` checks before a file even exists on disk. @@ -79,7 +79,7 @@ Beyond static snapshots, codeint helps humans and coding agents understand how f codeint is written in safe Rust (`#![forbid(unsafe_code)]`, [ADR 0004](./docs/adr/0004-forbid-unsafe-code.md)) around two clean seams: Language plugins lower source files into a language-neutral Code model, and Metric plugins compute Metrics and Findings over that model. It reads tracked files and commit history directly from Git objects without modifying your working tree, scanning `laravel/framework` (132k Production lines) in `0.47s` and `flutter/packages` (434k Production lines) in `3.68s` on Apple Silicon. -External WebAssembly Plugins implement the versioned `codeint:plugin@0.2.0` WIT contract with mandatory SHA-256 verification, zero host capabilities, and configurable memory and time caps. +External WebAssembly Plugins implement the versioned `codeint:plugin@0.3.0` WIT contract with mandatory SHA-256 verification, zero host capabilities, and configurable memory and time caps. Read [docs/guide/philosophy-and-architecture.md](./docs/guide/philosophy-and-architecture.md) for the full architecture diagram and design rationale. diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index d904337a..fd7e7758 100644 --- a/crates/cli/src/check.rs +++ b/crates/cli/src/check.rs @@ -16,10 +16,10 @@ use codeint_lang_rust::Rust; use codeint_lang_ts::{TypeScriptAndJavaScript, react_reference_ranges, vue_reference_ranges}; use codeint_metrics::{DependencyHygiene, OrphanFiles}; use codeint_model::{ - CodeModel, DeclaredDep, DependencyManifest, InvalidReferenceRange, LanguagePlugin, - LanguagePluginError, LowerError, Manifest, MetricPlugin, MetricPluginError, Package, - ReferenceRanges, RepoPath, ResolveError, SkippedFile, SourceFile, Workspace, WorkspaceError, - choose_manifests, resolve_runtime_imports, settle_source_set, + CodeModel, DeclaredDep, DependencyManifest, HazardLine, InvalidReferenceRange, LanguageFacts, + LanguagePlugin, LanguagePluginError, LowerError, Manifest, MetricPlugin, MetricPluginError, + Package, ReferenceRanges, RepoPath, ResolveError, SkippedFile, SourceFile, SourceSet, + Workspace, WorkspaceError, choose_manifests, resolve_runtime_imports, settle_source_set, }; use codeint_plugin_host::{ PluginHostError, WasmLanguagePlugin, WasmMetricPlugin, load_language_plugins_with_limits, @@ -57,8 +57,12 @@ pub(crate) enum CheckError { Configuration(#[from] ConfigurationFileError), #[error(transparent)] Codeowners(#[from] CodeownersError), - #[error("cannot resolve runtime imports")] - Resolve(#[source] ResolveError), + #[error("Language plugin {plugin:?} cannot resolve runtime imports")] + Resolve { + plugin: String, + #[source] + source: ResolveError, + }, #[error("a Language plugin supplies an invalid Reference range")] ReferenceRange(#[source] InvalidReferenceRange), #[error(transparent)] @@ -195,6 +199,9 @@ pub(crate) fn filter_model_to_package(model: &mut CodeModel, selected: &Selected model .files .retain(|file| selected.matches(workspace.package_of(&file.path))); + if model.files.is_empty() { + model.languages.clear(); + } model .skipped .retain(|file| selected.matches(workspace.package_of(&file.path))); @@ -399,12 +406,29 @@ impl WorkspaceContext { } pub(crate) fn measure_working_tree_model(&self) -> Result { + self.measure_working_tree_model_for_package(None) + } + + pub(crate) fn measure_working_tree_model_for_package( + &self, + package: Option<&str>, + ) -> Result { let plugins = self.plugins.as_named(); let tree = self.repository.working_tree()?; - let languages = measure_with(&tree, &plugins, &self.configuration)?; - Ok(CodeModel::merge( - languages.into_iter().map(|language| language.model), - )) + let mut languages = measure_with(&tree, &plugins, &self.configuration)?; + let workspace = 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); + Some(workspace) + } else { + None + }; + let mut model = CodeModel::merge(languages.into_iter().map(|language| language.model)); + if let Some(workspace) = workspace { + model.workspace = workspace; + } + Ok(model) } } @@ -491,6 +515,9 @@ pub(crate) fn compute_orphan_files( ) -> (Option, BTreeMap) { let mut by_language = BTreeMap::new(); for language in &snapshot.languages { + if !language.has_imports { + continue; + } let entry_points = snapshot .entry_points_by_language .get(&language.plugin) @@ -516,6 +543,9 @@ pub(crate) fn compute_dependency_hygiene( let ignored = dependencies.ignored(); let mut by_language = BTreeMap::new(); for language in &snapshot.languages { + if !language.has_imports { + continue; + } let measured = DependencyHygiene::measure_filtered(&language.model, ignored, |root| { selected.is_none_or(|pkg| { package_root_matches_selected(&language.model.workspace, pkg, root) @@ -615,7 +645,7 @@ fn measure( let manifests_by_plugin = read_manifests(tree, plugins)?; let plugin_members = find_plugin_workspaces(plugins, &manifests_by_plugin)?; let workspace = Workspace::new(plugin_members.iter().flatten().cloned()); - let outcomes = lower_covered_files(tree, plugins, &covered_files, overrides)?; + let outcomes = lower_covered_files(tree, plugins, &covered_files, overrides, config_file)?; let models = collect_plugin_models(plugins.len(), workspace, outcomes); resolve_measured_snapshot( tree, @@ -628,37 +658,52 @@ fn measure( ) } +fn listed_hazard_rules_by_plugin(plugins: &[NamedLanguagePlugin<'_>]) -> Vec> { + plugins + .iter() + .map(|named| { + if named.plugin.has_hazard_rules() { + named.plugin.hazard_rules().into_iter().collect() + } else { + HashSet::new() + } + }) + .collect() +} + fn lower_covered_files( tree: &Snapshot, plugins: &[NamedLanguagePlugin<'_>], covered_files: &[(&RepoPath, usize)], overrides: &SourceSetOverrides, + config_file: ConfigFileKind, ) -> Result, CheckError> { + let listed_hazard_rules = listed_hazard_rules_by_plugin(plugins); + let lower_file = |bytes: Vec, path: &RepoPath, index: usize| { + let lowered = lower_bytes( + bytes, + path, + &plugins[index], + &listed_hazard_rules[index], + overrides, + config_file, + )?; + Ok((index, lowered)) + }; if let Some(reader) = tree.working_tree_reader() { return covered_files .par_iter() - .map(|&(path, index)| { - let bytes = reader.read(path)?; - Ok(( - index, - lower_bytes(bytes, path, plugins[index].plugin, overrides), - )) - }) + .map(|&(path, index)| lower_file(reader.read(path)?, path, index)) .collect(); } let loaded = covered_files .iter() .map(|&(path, index)| Ok((path, index, tree.read(path)?))) .collect::, CheckError>>()?; - Ok(loaded + loaded .into_par_iter() - .map(|(path, index, bytes)| { - ( - index, - lower_bytes(bytes, path, plugins[index].plugin, overrides), - ) - }) - .collect()) + .map(|(path, index, bytes)| lower_file(bytes, path, index)) + .collect() } fn collect_plugin_models( @@ -701,12 +746,19 @@ fn resolve_measured_snapshot( .zip(manifests_by_plugin) .zip(plugin_members) { - let manifest_entries = named - .plugin - .entry_points(tree.files(), manifests.clone()) - .map_err(|error| CheckError::language_plugin(config_file, error))?; - let combined_entries = - combine_entry_points(manifest_entries, &model.files, configured_entry_points); + let manifest_entries = if named.plugin.has_imports() { + named + .plugin + .entry_points(tree.files(), manifests.clone()) + .map_err(|error| CheckError::language_plugin(config_file, error))? + } else { + Vec::new() + }; + let combined_entries = if named.plugin.has_imports() { + combine_entry_points(manifest_entries, &model.files, configured_entry_points) + } else { + Vec::new() + }; let retained_manifests = if named.name == "typescript-javascript" { manifests.clone() } else { @@ -731,11 +783,12 @@ fn combine_entry_points( configured: &EntryPoints, ) -> Vec { let mut entries: BTreeSet = manifest_entries.into_iter().collect(); - if !configured.is_empty() { - for file in files { - if configured.matches(&file.path) { - entries.insert(file.path.clone()); - } + for file in files { + let marked_production = + file.model.program_start && file.model.source_set == SourceSet::Production; + let configured_match = !configured.is_empty() && configured.matches(&file.path); + if marked_production || configured_match { + entries.insert(file.path.clone()); } } entries.into_iter().collect() @@ -749,31 +802,50 @@ fn finalize_language_model( repository_paths: &[RepoPath], config_file: ConfigFileKind, ) -> Result { - let importers: Vec<&SourceFile> = model.files.iter().collect(); let reference_ranges = select_reference_ranges(named, &model, &manifests)?; - let declared_dependencies = named - .plugin - .declared_dependencies(manifests.clone()) - .map_err(|error| CheckError::language_plugin(config_file, error))?; - model.dependency_manifests = collect_dependency_manifests( - &manifests, - plugin_members, - &declared_dependencies, - &model.files, - ); - model.manifest_used_dependencies = crate::package_scripts::extract_manifest_used_dependencies( - &manifests, - plugin_members, - &declared_dependencies, - ); - model.declared_dependencies = declared_dependencies; - model.runtime_imports = - resolve_runtime_imports(named.plugin, repository_paths, manifests, &importers) - .map_err(CheckError::Resolve)?; + let has_imports = named.plugin.has_imports(); + if has_imports { + let importers: Vec<&SourceFile> = model.files.iter().collect(); + let declared_dependencies = named + .plugin + .declared_dependencies(manifests.clone()) + .map_err(|error| CheckError::language_plugin(config_file, error))?; + model.dependency_manifests = collect_dependency_manifests( + &manifests, + plugin_members, + &declared_dependencies, + &model.files, + ); + model.manifest_used_dependencies = + crate::package_scripts::extract_manifest_used_dependencies( + &manifests, + plugin_members, + &declared_dependencies, + ); + model.declared_dependencies = declared_dependencies; + model.runtime_imports = + resolve_runtime_imports(named.plugin, repository_paths, manifests, &importers) + .map_err(|source| match source { + ResolveError::Plugin(error) => CheckError::language_plugin(config_file, error), + other => CheckError::Resolve { + plugin: named.name.to_owned(), + source: other, + }, + })?; + } + if !model.files.is_empty() { + model.languages = vec![LanguageFacts { + language: named.name.to_owned(), + has_coverage: false, + has_hazard_rules: named.plugin.has_hazard_rules(), + has_imports, + }]; + } Ok(MeasuredLanguage { plugin: named.name.to_owned(), model, reference_ranges, + has_imports, }) } @@ -1022,8 +1094,14 @@ pub(crate) fn read_manifests( plugins .iter() .map(|named| { + if !named.plugin.has_imports() { + return Ok(Vec::new()); + } choose_manifests(named.plugin, tree.files()) - .map_err(CheckError::Resolve)? + .map_err(|source| CheckError::Resolve { + plugin: named.name.to_owned(), + source, + })? .into_iter() .map(|path| { Ok(Manifest { @@ -1053,7 +1131,12 @@ fn find_plugin_workspaces( plugins .iter() .zip(manifests_by_plugin) - .map(|(named, manifests)| Ok(named.plugin.workspace_packages(manifests.clone())?)) + .map(|(named, manifests)| { + if !named.plugin.has_imports() { + return Ok(Vec::new()); + } + Ok(named.plugin.workspace_packages(manifests.clone())?) + }) .collect() } @@ -1063,33 +1146,84 @@ enum LoweredFile { Skipped(SkippedFile), } +fn validate_hazard_rule_names( + plugin_name: &str, + path: &RepoPath, + hazard_lines: &[HazardLine], + listed_rules: &HashSet, +) -> Result<(), LanguagePluginError> { + for hazard in hazard_lines { + if !listed_rules.contains(&hazard.rule) { + return Err(LanguagePluginError::UnlistedHazardRule { + plugin: plugin_name.to_owned(), + path: path.clone(), + rule: hazard.rule.clone(), + }); + } + } + Ok(()) +} + fn lower_bytes( bytes: Vec, path: &RepoPath, - plugin: &dyn LanguagePlugin, + named: &NamedLanguagePlugin<'_>, + listed_hazard_rules: &HashSet, overrides: &SourceSetOverrides, -) -> LoweredFile { + config_file: ConfigFileKind, +) -> Result { let text = match String::from_utf8(bytes) { Ok(text) => text, - Err(error) => return LoweredFile::Skipped(not_utf8(path.clone(), &error)), + Err(error) => return Ok(LoweredFile::Skipped(not_utf8(path.clone(), &error))), }; - match plugin.lower(path, &text) { + match named.plugin.lower(path, &text) { Ok(mut file) => { + validate_hazard_line_bounds(named.name, path, &text, &file.hazard_lines) + .map_err(|error| CheckError::language_plugin(config_file, error))?; + validate_hazard_rule_names(named.name, path, &file.hazard_lines, listed_hazard_rules) + .map_err(|error| CheckError::language_plugin(config_file, error))?; + for function in &mut file.functions { + function.coverage = None; + } + if !named.plugin.has_imports() { + file.program_start = false; + } file.source_set = overrides.source_set(path, settle_source_set(path, &text, file.source_set)); - LoweredFile::Measured(SourceFile { + Ok(LoweredFile::Measured(SourceFile { path: path.clone(), model: file, - }) + })) } - Err(LowerError::DeclarationOnly) => LoweredFile::DeclarationOnly(path.clone()), - Err(reason) => LoweredFile::Skipped(SkippedFile { + Err(LowerError::DeclarationOnly) => Ok(LoweredFile::DeclarationOnly(path.clone())), + Err(reason) => Ok(LoweredFile::Skipped(SkippedFile { path: path.clone(), reason: reason.to_string(), - }), + })), } } +fn validate_hazard_line_bounds( + plugin_name: &str, + path: &RepoPath, + text: &str, + hazard_lines: &[HazardLine], +) -> Result<(), LanguagePluginError> { + let line_count = text.lines().count(); + for hazard in hazard_lines { + let line_number = usize::try_from(hazard.line).unwrap_or(usize::MAX); + if line_number < 1 || line_number > line_count { + return Err(LanguagePluginError::HazardLineOutOfRange { + plugin: plugin_name.to_owned(), + path: path.clone(), + line: hazard.line, + line_count, + }); + } + } + Ok(()) +} + fn not_utf8(path: RepoPath, error: &FromUtf8Error) -> SkippedFile { SkippedFile { path, diff --git a/crates/cli/src/check/tests.rs b/crates/cli/src/check/tests.rs index 7f63b9ec..98672272 100644 --- a/crates/cli/src/check/tests.rs +++ b/crates/cli/src/check/tests.rs @@ -3,16 +3,19 @@ use std::process::Command; use std::sync::Barrier; use std::sync::atomic::{AtomicUsize, Ordering}; -use codeint_config::{FindingsShown, ReportFormat}; +use codeint_config::{Configuration, FindingsShown, ReportFormat}; +use codeint_git::Repository; use codeint_model::language::{ DeclaredDep, FileModel, FlaggedLine, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, WorkspaceError, }; -use codeint_model::{InvalidReferenceRange, LanguagePlugin, ReferenceRanges, RepoPath}; +use codeint_model::{ + InvalidReferenceRange, LanguageFacts, LanguagePlugin, ReferenceRanges, RepoPath, +}; use serde_json::Value; use tempfile::TempDir; -use super::{CheckError, NamedLanguagePlugin, check_with}; +use super::{CheckError, NamedLanguagePlugin, check_with, measure_snapshot}; struct Alpha; @@ -74,12 +77,29 @@ fn lines_in(source_set: SourceSet, text: &str) -> Result functions: Vec::new(), tokens: Vec::new(), flagged_lines: Vec::new(), + hazard_lines: Vec::new(), runtime_imports: Vec::new(), + program_start: false, }) } macro_rules! every_import_is_external { () => { + every_import_is_external!(imports_only); + + fn has_hazard_rules() -> bool { + false + } + + fn hazard_rules() -> Vec { + Vec::new() + } + + fn has_imports() -> bool { + true + } + }; + (imports_only) => { fn manifest_paths(_repository_paths: Vec) -> Vec { Vec::new() } @@ -122,95 +142,79 @@ macro_rules! without_workspaces { }; } -impl Guest for Alpha { - fn extensions() -> Vec { - vec!["alpha".to_owned()] - } - - fn lower(_path: String, text: String) -> Result { - lines_of(&text) - } - - without_workspaces!(); - - fn reference_ranges() -> Vec { - erosion_range(0.12, 0.56, "Alpha panel of 40 repositories, Table 3") - } - - every_import_is_external!(); -} - -impl Guest for AlphaTwo { - fn extensions() -> Vec { - vec!["alpha".to_owned()] - } +macro_rules! panic_on_import_calls { + () => { + fn manifest_paths(_repository_paths: Vec) -> Vec { + panic!("manifest_paths must not be called when has_imports is false"); + } - fn lower(_path: String, text: String) -> Result { - lines_of(&text) - } + fn workspace_packages(_manifests: Vec) -> Result, WorkspaceError> { + panic!("workspace_packages must not be called when has_imports is false"); + } - without_workspaces!(); + fn resolve_imports( + _repository_paths: Vec, + _manifests: Vec, + _requests: Vec, + ) -> Vec { + panic!("resolve_imports must not be called when has_imports is false"); + } - fn reference_ranges() -> Vec { - Vec::new() - } + fn declared_dependencies(_manifests: Vec) -> Vec { + panic!("declared_dependencies must not be called when has_imports is false"); + } - every_import_is_external!(); + fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { + panic!("entry_points must not be called when has_imports is false"); + } + }; } -impl Guest for DuplicateExtension { - fn extensions() -> Vec { - vec!["dup".to_owned(), "dup".to_owned()] - } - - fn lower(_path: String, text: String) -> Result { - lines_of(&text) - } - - without_workspaces!(); - - fn reference_ranges() -> Vec { - Vec::new() - } - - every_import_is_external!(); +fn measure_test_snapshot( + files: &[(&str, &str)], + plugins: &[NamedLanguagePlugin<'_>], +) -> Result { + let folder = repository(files); + let repo = Repository::discover(folder.path()).expect("open repository"); + let tree = repo.working_tree().expect("read working tree"); + measure_snapshot(&tree, plugins, &Configuration::default()) } -impl Guest for Beta { - fn extensions() -> Vec { - vec!["beta".to_owned()] - } +macro_rules! stub_language_plugin { + ($name:ident, [$($ext:expr),+ $(,)?], $ranges:expr) => { + impl Guest for $name { + fn extensions() -> Vec { + vec![$($ext.to_owned()),+] + } - fn lower(_path: String, text: String) -> Result { - lines_of(&text) - } + fn lower(_path: String, text: String) -> Result { + lines_of(&text) + } - without_workspaces!(); + without_workspaces!(); - fn reference_ranges() -> Vec { - Vec::new() - } + fn reference_ranges() -> Vec { + $ranges + } - every_import_is_external!(); + every_import_is_external!(); + } + }; } -impl Guest for Malformed { - fn extensions() -> Vec { - vec!["malformed".to_owned()] - } - - fn lower(_path: String, text: String) -> Result { - lines_of(&text) - } - - without_workspaces!(); - - fn reference_ranges() -> Vec { - erosion_range(0.7, 0.2, "Reversed") - } - - every_import_is_external!(); -} +stub_language_plugin!( + Alpha, + ["alpha"], + erosion_range(0.12, 0.56, "Alpha panel of 40 repositories, Table 3") +); +stub_language_plugin!(AlphaTwo, ["alpha"], Vec::new()); +stub_language_plugin!(DuplicateExtension, ["dup", "dup"], Vec::new()); +stub_language_plugin!(Beta, ["beta"], Vec::new()); +stub_language_plugin!( + Malformed, + ["malformed"], + erosion_range(0.7, 0.2, "Reversed") +); impl Guest for FlagsEveryLineInOnePackage { fn extensions() -> Vec { @@ -787,11 +791,11 @@ impl LanguagePlugin for ParallelProofPlugin { _repository_paths: &[RepoPath], _manifests: Vec, requests: Vec, - ) -> Vec { - requests + ) -> Result, codeint_model::LanguagePluginError> { + Ok(requests .iter() .map(|_| Resolution::External(String::new())) - .collect() + .collect()) } fn declared_dependencies( @@ -817,6 +821,18 @@ impl LanguagePlugin for ParallelProofPlugin { fn reference_ranges(&self) -> Result { Ok(ReferenceRanges::default()) } + + fn has_hazard_rules(&self) -> bool { + false + } + + fn hazard_rules(&self) -> Vec { + Vec::new() + } + + fn has_imports(&self) -> bool { + true + } } #[test] @@ -1080,6 +1096,89 @@ fn extension_conflict_error_and_remedy_name_codeint_jsonc_when_active() { ); } +#[test] +fn measure_snapshot_populates_per_language_coverage_and_hazard_rule_statements() { + struct WithHazardRules; + + impl Guest for WithHazardRules { + fn extensions() -> Vec { + vec!["haz".to_owned()] + } + + fn lower(_path: String, text: String) -> Result { + lines_of(&text) + } + + without_workspaces!(); + + fn reference_ranges() -> Vec { + Vec::new() + } + + every_import_is_external!(imports_only); + + fn has_hazard_rules() -> bool { + true + } + + fn hazard_rules() -> Vec { + vec![ + "delete-without-where".to_owned(), + "leading-wildcard-like".to_owned(), + ] + } + + fn has_imports() -> bool { + true + } + } + + const WITH_HAZARD_RULES: NamedLanguagePlugin<'static> = NamedLanguagePlugin { + name: "hazard-lang", + plugin: &WithHazardRules, + }; + + let snapshot = measure_test_snapshot( + &[("main.alpha", "one\n"), ("query.haz", "two\n")], + &[ALPHA, WITH_HAZARD_RULES], + ) + .expect("measure snapshot succeeds"); + + let facts_by_plugin: Vec<(&str, &[LanguageFacts])> = snapshot + .languages + .iter() + .map(|language| { + ( + language.plugin.as_str(), + language.model.languages.as_slice(), + ) + }) + .collect(); + assert_eq!( + facts_by_plugin, + vec![ + ( + "alpha", + &[LanguageFacts { + language: "alpha".to_owned(), + has_coverage: false, + has_hazard_rules: false, + has_imports: true, + }][..] + ), + ( + "hazard-lang", + &[LanguageFacts { + language: "hazard-lang".to_owned(), + has_coverage: false, + has_hazard_rules: true, + has_imports: true, + }][..] + ), + ] + ); +} + const TS_JS_RANGE: &str = "codeint panel of 20 TypeScript and JavaScript repositories, ADR 0008, codeint 0.1.0"; const VUE2_RANGE: &str = "codeint panel of 20 Vue 2 repositories, ADR 0014, codeint 0.4.0"; @@ -1228,6 +1327,74 @@ fn react_reference_ranges_select_adr_0020_and_preserve_vue_and_hybrid_precedence ); } +#[test] +fn no_imports_language_plugin_never_has_import_manifest_or_entry_point_functions_called() { + struct NoImports; + + impl Guest for NoImports { + fn extensions() -> Vec { + vec!["noimp".to_owned()] + } + + fn lower(_path: String, text: String) -> Result { + let mut model = lines_of(&text)?; + model.runtime_imports.push("./never-resolved".to_owned()); + model.program_start = true; + Ok(model) + } + + panic_on_import_calls!(); + + fn reference_ranges() -> Vec { + Vec::new() + } + + fn has_hazard_rules() -> bool { + false + } + + fn hazard_rules() -> Vec { + Vec::new() + } + + fn has_imports() -> bool { + false + } + } + + const NO_IMPORTS: NamedLanguagePlugin<'static> = NamedLanguagePlugin { + name: "no-imports", + plugin: &NoImports, + }; + + let snapshot = measure_test_snapshot( + &[("main.alpha", "one\n"), ("query.noimp", "two\n")], + &[ALPHA, NO_IMPORTS], + ) + .expect("measure snapshot skips import, manifest, and entry point calls"); + + let no_imports_lang = snapshot + .languages + .iter() + .find(|language| language.plugin == "no-imports") + .expect("no-imports language measured"); + assert_eq!(no_imports_lang.model.files.len(), 1); + assert!(!no_imports_lang.model.files[0].model.program_start); + assert!(no_imports_lang.model.runtime_imports.is_empty()); + assert!(no_imports_lang.model.declared_dependencies.is_empty()); + assert!(no_imports_lang.model.dependency_manifests.is_empty()); + assert!(no_imports_lang.model.manifest_used_dependencies.is_empty()); + assert_eq!( + no_imports_lang.model.languages, + vec![LanguageFacts { + language: "no-imports".to_owned(), + has_coverage: false, + has_hazard_rules: false, + has_imports: false, + }] + ); +} + #[test] fn package_scoped_reference_ranges_prefer_member_manifests_over_root() { let vue_script = "\n"; @@ -1291,3 +1458,72 @@ fn package_scoped_reference_ranges_prefer_member_manifests_over_root() { ], ); } + +#[test] +fn lowering_clears_language_plugin_coverage_and_unmeasured_plugins_emit_no_language_facts() { + struct SpoofingCoveragePlugin; + + impl Guest for SpoofingCoveragePlugin { + every_import_is_external!(); + without_workspaces!(); + + fn lower(_path: String, text: String) -> Result { + let functions = vec![codeint_model::language::Function { + line: 1, + end_line: 1, + decision_points: 1, + source_lines: 1, + name: Some("spoofed".to_owned()), + cognitive_complexity: 0, + coverage: Some(codeint_model::language::FunctionCoverage { + listed_lines: 10, + executed_lines: 10, + }), + }]; + Ok(FileModel { + functions, + ..lines_of(&text)? + }) + } + + fn extensions() -> Vec { + vec![String::from("cov")] + } + + fn reference_ranges() -> Vec { + Vec::new() + } + } + + const SPOOF: NamedLanguagePlugin<'static> = NamedLanguagePlugin { + name: "spoof-cov", + plugin: &SpoofingCoveragePlugin, + }; + + let snapshot = measure_test_snapshot(&[("src/main.cov", "fn spoofed() {}\n")], &[ALPHA, SPOOF]) + .expect("measure snapshot"); + + let alpha = snapshot + .languages + .iter() + .find(|language| language.plugin == "alpha") + .expect("alpha entry"); + assert!(alpha.model.files.is_empty()); + assert!(alpha.model.languages.is_empty()); + + let spoof = snapshot + .languages + .iter() + .find(|language| language.plugin == "spoof-cov") + .expect("spoof-cov entry"); + assert_eq!(spoof.model.languages.len(), 1); + assert_eq!(spoof.model.files[0].model.functions[0].coverage, None); + + let mut filtered = spoof.model.clone(); + super::filter_model_to_package( + &mut filtered, + &super::SelectedPackage::Member(RepoPath::new("packages/other").expect("path")), + ); + assert!(filtered.files.is_empty()); + assert!(filtered.languages.is_empty()); +} diff --git a/crates/cli/src/commit_measurement.rs b/crates/cli/src/commit_measurement.rs index 004843b6..9f6d6214 100644 --- a/crates/cli/src/commit_measurement.rs +++ b/crates/cli/src/commit_measurement.rs @@ -1,5 +1,6 @@ use codeint_config::Configuration; use codeint_git::{CommitId, Repository, ResultCache, Snapshot}; +use codeint_plugin_host::PLUGIN_INTERFACE_VERSION; use codeint_report::CommitMeasurement; use serde::Serialize; @@ -11,12 +12,13 @@ use crate::check::{ use crate::describe; const CODEINT_VERSION: &str = env!("CARGO_PKG_VERSION"); -const MEASUREMENT_CACHE_VERSION: u32 = 5; +const MEASUREMENT_CACHE_VERSION: u32 = 6; #[derive(Serialize)] struct MeasurementSettings<'configuration> { codeint_version: &'static str, cache_version: u32, + plugin_interface_version: String, language_plugins: Vec, configuration: &'configuration Configuration, #[serde(skip_serializing_if = "Option::is_none")] @@ -74,6 +76,7 @@ impl<'run> CommitMeasurer<'run> { settings: MeasurementSettings { codeint_version: CODEINT_VERSION, cache_version: MEASUREMENT_CACHE_VERSION, + plugin_interface_version: PLUGIN_INTERFACE_VERSION.to_owned(), language_plugins, configuration, package, diff --git a/crates/cli/src/doctor.rs b/crates/cli/src/doctor.rs index bb0fbc17..24e85fac 100644 --- a/crates/cli/src/doctor.rs +++ b/crates/cli/src/doctor.rs @@ -6,7 +6,9 @@ use codeint_config::{ PluginKind, PluginSource, SchemaVersionStatus, inspect_configuration, is_broken_symlink, }; use codeint_git::{GitError, Repository, Snapshot}; -use codeint_plugin_host::{sha256, sha256_hex}; +use codeint_plugin_host::{ + PLUGIN_INTERFACE_VERSION, PluginHostError, sha256, sha256_hex, verify_plugin_component, +}; use codeint_report::{DoctorCheck, DoctorReport}; use crate::check::{BUILT_IN_LANGUAGE_PLUGINS, find_workspace, read_manifests}; @@ -375,6 +377,7 @@ fn check_single_plugin( verify_plugin_file( id, &declaration.name, + declaration.kind, &resolved, &declaration.sha256.to_hex(), &declared_path.display().to_string(), @@ -443,6 +446,7 @@ fn inspect_cached_plugin( Ok(_) => Some(verify_plugin_file( id.to_owned(), &declaration.name, + declaration.kind, path, expected, &format!("cached from {url}"), @@ -468,6 +472,7 @@ fn inspect_cached_plugin( fn verify_plugin_file( id: String, name: &str, + kind: PluginKind, resolved_path: &Path, expected_hex: &str, label: &str, @@ -505,9 +510,61 @@ fn verify_plugin_file( "Verify the plugin file has not been modified, then update sha256 in {file_name} to match the trusted file." )); } + if let Err(error) = verify_plugin_component(name, resolved_path, kind, &bytes) { + return plugin_component_error(id, name, label, file_name, &error); + } DoctorCheck::pass( id, format!("External Wasm Plugin {name:?} verified ({label})"), ) .with_detail(format!("sha256: {expected_hex}")) } + +fn plugin_component_error( + id: String, + name: &str, + label: &str, + file_name: &'static str, + error: &PluginHostError, +) -> DoctorCheck { + match error { + PluginHostError::IncompatibleContractVersion { + expected, found, .. + } => DoctorCheck::error( + id, + format!( + "External Wasm Plugin {name:?} at {label} is not loadable: targets incompatible WIT contract {found}, requires {expected}" + ), + ) + .with_remedy(format!( + "Rebuild the Plugin against codeint:plugin@{PLUGIN_INTERFACE_VERSION} and update its sha256 in {file_name}." + )), + PluginHostError::Compile { reason, .. } => DoctorCheck::error( + id, + format!( + "External Wasm Plugin {name:?} at {label} is not loadable: cannot compile WebAssembly component" + ), + ) + .with_detail(reason.clone()) + .with_remedy(format!( + "Build the Plugin as a WebAssembly component targeting codeint:plugin@{PLUGIN_INTERFACE_VERSION} and update its sha256 in {file_name}." + )), + PluginHostError::Instantiate { reason, .. } => DoctorCheck::error( + id, + format!( + "External Wasm Plugin {name:?} at {label} is not loadable: component does not satisfy the codeint:plugin@{PLUGIN_INTERFACE_VERSION} sandbox contract" + ), + ) + .with_detail(reason.clone()) + .with_remedy(format!( + "Ensure the Plugin exports codeint:plugin/language@{PLUGIN_INTERFACE_VERSION} or codeint:plugin/metric@{PLUGIN_INTERFACE_VERSION} and imports no host capabilities." + )), + _ => DoctorCheck::error( + id, + format!("External Wasm Plugin {name:?} at {label} is not loadable: {error}"), + ) + .with_remedy(format!( + "Rebuild the Plugin against codeint:plugin@{PLUGIN_INTERFACE_VERSION} and update its sha256 in {file_name}." + )), + } +} diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 8e715297..1a30b561 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -84,7 +84,7 @@ fn check_remedy(error: &CheckError) -> &'static str { fn check_plugin_remedy(error: &CheckError) -> &'static str { match error { - CheckError::Resolve(_) => { + CheckError::Resolve { .. } => { "This is a defect in the Language plugin; report it to the author of the Language plugin." } CheckError::ReferenceRange(_) => { @@ -446,15 +446,15 @@ fn plugin_load_remedy(error: &PluginHostError, file: ConfigFileKind) -> Option<& ) } PluginHostError::Compile { .. } => { - "Build the plugin as a WebAssembly component targeting codeint:plugin@0.2.0." + "Build the plugin as a WebAssembly component targeting codeint:plugin@0.3.0." } PluginHostError::Instantiate { .. } => { - "Ensure the plugin exports codeint:plugin/language@0.2.0 or codeint:plugin/metric@0.2.0 and imports no host capabilities." + "Ensure the plugin exports codeint:plugin/language@0.3.0 or codeint:plugin/metric@0.3.0 and imports no host capabilities." } PluginHostError::IncompatibleContractVersion { .. } => choose_file_remedy( file, - "Rebuild the plugin against codeint:plugin@0.2.0 and update its sha256 in codeint.json.", - "Rebuild the plugin against codeint:plugin@0.2.0 and update its sha256 in codeint.jsonc.", + "Rebuild the plugin against codeint:plugin@0.3.0 and update its sha256 in codeint.json.", + "Rebuild the plugin against codeint:plugin@0.3.0 and update its sha256 in codeint.jsonc.", ), PluginHostError::NonHttpsUrl { .. } => choose_file_remedy( file, @@ -513,6 +513,12 @@ fn language_plugin_remedy(error: &LanguagePluginError, file: ConfigFileKind) -> "Raise plugin_limits.memory_mb or plugin_limits.timeout_ms in codeint.json if the Language plugin needs more resources, or fix the defect in the plugin.", "Raise plugin_limits.memory_mb or plugin_limits.timeout_ms in codeint.jsonc if the Language plugin needs more resources, or fix the defect in the plugin.", ), + LanguagePluginError::HazardLineOutOfRange { .. } => { + "Return 1-based Hazard line numbers within the file's line count from the Language plugin, or report the defect to its author." + } + LanguagePluginError::UnlistedHazardRule { .. } => { + "List every Hazard line rule name in the Language plugin's hazard-rules export, or report the defect to the plugin's author." + } _ => "Fix the defect in the Language plugin, or report it to the plugin's author.", } } diff --git a/crates/cli/src/trace.rs b/crates/cli/src/trace.rs index c4bec3d2..9f8f4004 100644 --- a/crates/cli/src/trace.rs +++ b/crates/cli/src/trace.rs @@ -4,9 +4,7 @@ use codeint_config::PluginHostConfig; use codeint_model::{CodeModel, RepoPath}; use codeint_report::{TraceError, TraceReport}; -use crate::check::{ - CheckError, WorkspaceContext, filter_model_to_package, select_workspace_package, -}; +use crate::check::{CheckError, WorkspaceContext}; #[derive(Debug, thiserror::Error)] pub(crate) enum TraceCommandError { @@ -28,11 +26,7 @@ pub(crate) fn trace( plugin_host: &PluginHostConfig, ) -> Result { let context = WorkspaceContext::load(folder, plugin_host)?; - let mut model = context.measure_working_tree_model()?; - if let Some(requested) = package { - let selected = select_workspace_package(&model.workspace, requested)?; - filter_model_to_package(&mut model, &selected); - } + let model = context.measure_working_tree_model_for_package(package)?; let from_path = resolve_model_path(from, folder, context.repository.root(), &model)?; let to_path = resolve_model_path(to, folder, context.repository.root(), &model)?; Ok(TraceReport::trace( diff --git a/crates/cli/tests/check.rs b/crates/cli/tests/check.rs index 368dc842..3634c2b8 100644 --- a/crates/cli/tests/check.rs +++ b/crates/cli/tests/check.rs @@ -5543,3 +5543,321 @@ fn plugin_host_error_remedies_name_codeint_jsonc_when_active() { "unexpected codeint.json in stderr: {stderr}" ); } + +fn build_sandbox_probes_wasm_dir() -> &'static std::path::PathBuf { + static DIR: std::sync::OnceLock = std::sync::OnceLock::new(); + DIR.get_or_init(|| { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let target_dir = root.join("target/wasm-fixtures"); + let manifest = root.join("crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml"); + let status = Command::new("cargo") + .args([ + "build", + "--workspace", + "--locked", + "--offline", + "--target", + "wasm32-wasip2", + ]) + .arg("--manifest-path") + .arg(&manifest) + .arg("--target-dir") + .arg(&target_dir) + .status() + .expect("build sandbox-probes wasm fixtures"); + assert!( + status.success(), + "sandbox-probes build exited with {status}" + ); + target_dir.join("wasm32-wasip2/debug") + }) +} + +fn sandbox_probe_repo( + plugin_name: &str, + wasm_file: &str, + target_name: &str, + mut config: serde_json::Value, + files: &[(&str, &str)], +) -> Repository { + let repository = Repository::new(); + let wasm = fs::read(build_sandbox_probes_wasm_dir().join(wasm_file)) + .unwrap_or_else(|error| panic!("read {wasm_file}: {error}")); + repository.write_bytes(target_name, &wasm); + let digest = codeint_plugin_host::sha256_hex(&codeint_plugin_host::sha256(&wasm)); + config["plugins"] = serde_json::json!([{ + "name": plugin_name, + "path": target_name, + "sha256": digest, + }]); + repository.write("codeint.json", &config.to_string()); + for &(path, contents) in files { + repository.write(path, contents); + } + repository.commit_all(); + repository +} + +fn check_json_with_exit( + repository: &Repository, + args: &[&str], + expected_exit: i32, +) -> serde_json::Value { + let output = repository.codeint(args); + let actual_exit = output.status.code(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(actual_exit, Some(expected_exit), "{args:?}: {stderr}"); + serde_json::from_slice(&output.stdout).expect("parse json report") +} + +fn no_imports_repo( + zones: serde_json::Value, + budgets: serde_json::Value, + entry_points: &[&str], + files: &[(&str, &str)], +) -> Repository { + let mut config = serde_json::json!({ + "boundaries": { + "strict_zones": true, + "zones": zones, + "rules": [] + }, + "budgets": budgets + }); + if !entry_points.is_empty() { + config["entry_points"] = serde_json::json!(entry_points); + } + sandbox_probe_repo( + "no-imports-lang", + "no_imports_language_plugin.wasm", + "no_imports.wasm", + config, + files, + ) +} + +fn folder_import_cycles_report(files: &[(&str, &str)]) -> serde_json::Value { + let repository = sandbox_probe_repo( + "folder-import", + "folder_import_language_plugin.wasm", + "folder_import.wasm", + serde_json::json!({}), + files, + ); + json_report(&repository)["source_sets"]["production"]["import_cycles"].clone() +} + +#[test] +fn folder_import_cycle_reports_only_participating_files_and_no_sibling_links() { + let import_cycles = folder_import_cycles_report(&[ + ("pkg/alpha/a1.fld", "use pkg/beta\nfn a1()\n"), + ("pkg/alpha/a2.fld", "fn a2()\n"), + ("pkg/beta/b1.fld", "use pkg/leaf\nfn b1()\n"), + ("pkg/beta/b2.fld", "use pkg/alpha\nfn b2()\n"), + ("pkg/leaf/l1.fld", "fn l1()\n"), + ("pkg/leaf/l2.fld", "fn l2()\n"), + ]); + let findings = import_cycles["findings"] + .as_array() + .expect("import_cycles.findings array"); + + assert_eq!(import_cycles["modules"], 6); + assert_eq!(import_cycles["modules_in_import_cycles"], 2); + assert_eq!(import_cycles["unresolved_imports"]["count"], 0); + assert_eq!(findings.len(), 1); + assert_eq!( + findings[0]["modules"], + serde_json::json!(["pkg/alpha/a1.fld", "pkg/beta/b2.fld"]) + ); +} + +#[test] +fn acyclic_multi_file_folder_imports_report_no_import_cycles() { + let import_cycles = folder_import_cycles_report(&[ + ( + "pkg/app/main.fld", + "use pkg/left\nuse pkg/right\nfn main()\n", + ), + ("pkg/left/l1.fld", "use pkg/shared\nfn l1()\n"), + ("pkg/left/l2.fld", "fn l2()\n"), + ("pkg/right/r1.fld", "fn r1()\n"), + ("pkg/right/r2.fld", "use pkg/shared\nfn r2()\n"), + ("pkg/shared/s1.fld", "fn s1()\n"), + ("pkg/shared/s2.fld", "fn s2()\n"), + ]); + + assert_eq!(import_cycles["modules"], 7); + assert_eq!(import_cycles["modules_in_import_cycles"], 0); + assert_eq!(import_cycles["ratio"], 0.0); + assert_eq!(import_cycles["findings"], serde_json::json!([])); + assert_eq!(import_cycles["unresolved_imports"]["count"], 0); +} + +#[test] +fn mixed_repo_import_totals_and_budgets_count_only_languages_with_imports() { + let noimp_files: Vec<(String, String)> = (1..=8) + .map(|index| { + ( + format!("packages/app/queries/q{index}.noimp"), + format!("fn query_{index}()\n"), + ) + }) + .collect(); + let root_manifest = serde_json::json!({ + "name": "totals-root", + "private": true, + "workspaces": ["packages/*"], + }) + .to_string(); + let app_manifest = serde_json::json!({ + "name": "totals-app", + "main": "src/a.ts", + "dependencies": { "unused-dep": "^1.0.0" }, + }) + .to_string(); + let mut files: Vec<(&str, &str)> = vec![ + ("package.json", &root_manifest), + ("packages/app/package.json", &app_manifest), + ( + "packages/app/src/a.ts", + "import { b } from './b';\nexport const a = (): number => b();\n", + ), + ( + "packages/app/src/b.ts", + "import { a } from './a';\nexport const b = (): number => a();\n", + ), + ( + "packages/app/src/orphan.ts", + "export const orphan = (): number => 1;\n", + ), + ("packages/app/queries/q1_test.noimp", "fn test_query_1()\n"), + ]; + files.extend( + noimp_files + .iter() + .map(|(path, content)| (path.as_str(), content.as_str())), + ); + let repository = no_imports_repo( + serde_json::json!({ "app": { "patterns": ["packages/app/src/**"] } }), + serde_json::json!({ + "production": { + "import_cycles": 0.5, + "orphan_files": 0.25, + "boundaries": 0.0 + }, + "unused_dependencies": 0.5 + }), + &[], + &files, + ); + + let report = check_json_with_exit(&repository, &["check", "--format", "json"], 1); + assert_eq!(report["files"], 12); + assert_eq!(report.get("import_metrics_note"), None); + + let prod = &report["source_sets"]["production"]; + assert_eq!(prod["files"], 11); + assert_eq!(prod["import_cycles"]["modules"], 3); + assert_eq!(prod["import_cycles"]["modules_in_import_cycles"], 2); + assert_eq!(prod["import_cycles"]["ratio"], 0.6667); + + let ts_prod = &report["languages"]["typescript-javascript"]["source_sets"]["production"]; + assert_eq!( + prod["import_cycles"]["modules"], + ts_prod["import_cycles"]["modules"] + ); + assert_eq!( + prod["import_cycles"]["ratio"], + ts_prod["import_cycles"]["ratio"] + ); + + let packages = prod["packages"].as_array().expect("production packages"); + let app_package = packages + .iter() + .find(|package| package["path"] == "packages/app") + .expect("packages/app entry"); + assert_eq!(app_package["files"], 11); + assert_eq!(app_package["import_cycles"]["modules_in_import_cycles"], 2); + assert_eq!(app_package["import_cycles"]["ratio"], 0.6667); + + assert_eq!(prod["orphan_files"]["evaluated_files"], 3); + assert_eq!(prod["orphan_files"]["orphan_files"], 1); + assert_eq!(prod["orphan_files"]["ratio"], 0.3333); + assert_eq!( + prod["orphan_files"]["ratio"], + ts_prod["orphan_files"]["ratio"] + ); + + assert_eq!(prod["boundaries"]["ratio"], 0.0); + assert_eq!(prod["boundaries"]["findings"], serde_json::json!([])); + + assert_eq!(report["dependencies"]["unused_dependencies"]["declared"], 1); + assert_eq!(report["dependencies"]["unused_dependencies"]["unused"], 1); + assert_eq!(report["dependencies"]["unused_dependencies"]["ratio"], 1.0); + + let test_set = &report["source_sets"]["test"]; + assert_eq!(test_set["files"], 1); + assert_eq!(test_set.get("import_cycles"), None); + assert_eq!(test_set.get("boundaries"), None); + assert_eq!(test_set.get("orphan_files"), None); + + let over_budget = report["over_budget"].as_array().expect("over_budget array"); + let failed_metrics: Vec<&str> = over_budget + .iter() + .map(|entry| entry["metric"].as_str().expect("metric key")) + .collect(); + assert_eq!( + failed_metrics, + vec!["import_cycles", "orphan_files", "unused_dependencies"] + ); + + let diff_report = check_json_with_exit(&repository, &["diff", "HEAD", "--format", "json"], 1); + assert_eq!( + diff_report["source_sets"]["production"]["import_cycles"]["head_ratio"], + 0.6667 + ); + assert_eq!( + diff_report["source_sets"]["production"]["boundaries"]["head_ratio"], + 0.0 + ); +} + +#[test] +fn no_imports_only_repo_shows_absent_import_totals_and_budgets_do_not_trip() { + let repository = no_imports_repo( + serde_json::json!({}), + serde_json::json!({ + "production": { + "import_cycles": 0.0, + "orphan_files": 0.0, + "boundaries": 0.0 + }, + "unused_dependencies": 0.0, + "unlisted_dependencies": 0.0, + "dev_in_production_dependencies": 0.0 + }), + &["queries/a.noimp"], + &[ + ("queries/a.noimp", "fn query_a()\n"), + ("queries/b.noimp", "fn query_b()\n"), + ("queries/a_test.noimp", "fn test_query_a()\n"), + ], + ); + + let report = check_json_with_exit(&repository, &["check", "--format", "json"], 0); + assert_eq!(report["files"], 3); + assert!( + report["import_metrics_note"] + .as_str() + .is_some_and(|note| note.contains("has no imports")), + "expected import_metrics_note in report: {report}" + ); + assert_eq!(report.get("dependencies"), None); + assert_eq!(report.get("over_budget"), None); + for source_set in ["production", "test"] { + let section = &report["source_sets"][source_set]; + assert_eq!(section.get("import_cycles"), None); + assert_eq!(section.get("orphan_files"), None); + assert_eq!(section.get("boundaries"), None); + } +} diff --git a/crates/cli/tests/integration/boundaries.rs b/crates/cli/tests/integration/boundaries.rs index d9580344..3fbc8e04 100644 --- a/crates/cli/tests/integration/boundaries.rs +++ b/crates/cli/tests/integration/boundaries.rs @@ -2,9 +2,12 @@ use std::fs; use std::path::Path; use std::process::{Command, Output}; +use codeint_plugin_host::{sha256, sha256_hex}; use serde_json::Value; use tempfile::TempDir; +use crate::common::folder_import_plugin_wasm; + const GIT_ENV: [(&str, &str); 6] = [ ("GIT_CONFIG_GLOBAL", "/dev/null"), ("GIT_CONFIG_NOSYSTEM", "1"), @@ -762,3 +765,143 @@ fn diff_classifies_boundary_findings_and_gates_new_regressions_without_failing_o "src/domain/legacy.ts" ); } + +fn fixture_with_folder_import_plugin( + boundaries_json: &str, + files: &[(&str, &str)], +) -> BoundaryFixture { + let fixture = BoundaryFixture::init(files); + let wasm_bytes = fs::read(folder_import_plugin_wasm()).expect("read folder import wasm"); + let hash = sha256_hex(&sha256(&wasm_bytes)); + let plugin_dest = fixture + .0 + .path() + .join("plugins/folder_import_language_plugin.wasm"); + fs::create_dir_all(plugin_dest.parent().expect("plugin parent")).expect("mkdir plugins"); + fs::write(plugin_dest, wasm_bytes).expect("write folder import wasm"); + let config = format!( + r#"{{ + "plugins": [ + {{ + "name": "folder-import-lang", + "path": "plugins/folder_import_language_plugin.wasm", + "sha256": "{hash}" + }} + ], + "boundaries": {boundaries_json} +}}"# + ); + fixture.write("codeint.json", &config); + fixture +} + +#[test] +fn check_multi_file_import_flags_only_forbidden_targets_and_matches_configured_rule() { + let fixture = fixture_with_folder_import_plugin( + r#"{ + "zones": { + "ui": { "patterns": ["ui/**"] }, + "public": { "patterns": ["shared/public.fld"] }, + "secret": { "patterns": ["shared/secret.fld"] } + }, + "rules": [ + { + "from": "ui", + "deny": ["secret"], + "reason": "UI must not depend on secret files" + } + ] + }"#, + &[ + ("shared/public.fld", "fn api()\n"), + ("shared/secret.fld", "fn internal()\n"), + ("ui/page.fld", "use shared\nfn render()\n"), + ], + ); + + let json = fixture.check_json(0); + let boundaries = &json["source_sets"]["production"]["boundaries"]; + assert_eq!(boundaries["resolved_imports"], 2); + let findings = boundary_findings(&json, "production"); + assert_eq!(findings.len(), 1, "got: {findings:?}"); + let finding = &findings[0]; + assert_eq!(finding["kind"], "zone_rule"); + assert_eq!(finding["importer"], "ui/page.fld"); + assert_eq!(finding["target"], "shared/secret.fld"); + assert_eq!(finding["specifier"], "shared"); + assert_eq!(finding["source_zone"], "ui"); + assert_eq!(finding["target_zone"], "secret"); + assert_eq!(finding["reason"], "UI must not depend on secret files"); + assert!( + !findings + .iter() + .any(|item| item["target"] == "shared/public.fld") + ); +} + +#[test] +fn check_multi_file_import_flags_each_forbidden_target_with_distinct_ids() { + let fixture = fixture_with_folder_import_plugin( + r#"{ + "zones": { + "ui": { "patterns": ["ui/**"] }, + "public": { "patterns": ["public/**"] }, + "secret": { "patterns": ["secret/**"] } + }, + "rules": [ + { + "from": "ui", + "allow": ["public"], + "reason": "UI may import public modules only" + } + ] + }"#, + &[ + ("secret/alpha.fld", "fn alpha()\n"), + ("secret/beta.fld", "fn beta()\n"), + ("public/ok.fld", "fn ok()\n"), + ("ui/page.fld", "use secret\nuse public\nfn render()\n"), + ], + ); + + let json = fixture.check_json(0); + let boundaries = &json["source_sets"]["production"]["boundaries"]; + assert_eq!(boundaries["resolved_imports"], 3); + let findings = boundary_findings(&json, "production"); + assert_eq!(findings.len(), 2, "got: {findings:?}"); + let targets: Vec<&str> = findings + .iter() + .map(|item| item["target"].as_str().expect("target path")) + .collect(); + assert_eq!(targets, vec!["secret/alpha.fld", "secret/beta.fld"]); + for finding in &findings { + assert_eq!(finding["kind"], "zone_rule"); + assert_eq!(finding["importer"], "ui/page.fld"); + assert_eq!(finding["specifier"], "secret"); + assert_eq!(finding["source_zone"], "ui"); + assert_eq!(finding["target_zone"], "secret"); + assert_eq!(finding["reason"], "UI may import public modules only"); + } + let first_id = findings[0]["id"].as_str().expect("first id"); + let second_id = findings[1]["id"].as_str().expect("second id"); + assert!(!first_id.is_empty()); + assert_ne!(first_id, second_id); + + let sarif = fixture.sarif_boundary_results(None, &["check", "--format", "sarif"], 0); + assert_eq!(sarif.len(), 2); + let sarif_targets: Vec<&str> = sarif + .iter() + .map(|result| { + result["relatedLocations"][0]["physicalLocation"]["artifactLocation"]["uri"] + .as_str() + .expect("sarif related target") + }) + .collect(); + assert_eq!(sarif_targets, vec!["secret/alpha.fld", "secret/beta.fld"]); + + let markdown = fixture.run_stdout(None, &["check", "--format", "markdown"], 0); + assert!(markdown.contains("`ui/page.fld`")); + assert!(markdown.contains("`secret/alpha.fld`")); + assert!(markdown.contains("`secret/beta.fld`")); + assert!(!markdown.contains("`public/ok.fld`")); +} diff --git a/crates/cli/tests/integration/common/mod.rs b/crates/cli/tests/integration/common/mod.rs index 496905fb..ce3dd7f5 100644 --- a/crates/cli/tests/integration/common/mod.rs +++ b/crates/cli/tests/integration/common/mod.rs @@ -1,10 +1,57 @@ use std::io::Write; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; +use std::sync::OnceLock; use serde_json::{Value, json}; use tempfile::TempDir; +static FOLDER_IMPORT_WASM: OnceLock = OnceLock::new(); +static NO_IMPORTS_WASM: OnceLock = OnceLock::new(); + +fn build_sandbox_probe_wasm(package: &str, file_name: &str) -> PathBuf { + let workspace_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../.."); + let manifest_path = + workspace_root.join("crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml"); + let target_dir = workspace_root.join("target/wasm-fixtures"); + let status = Command::new("cargo") + .args([ + "build", + "-p", + package, + "--locked", + "--offline", + "--target", + "wasm32-wasip2", + ]) + .arg("--manifest-path") + .arg(manifest_path) + .arg("--target-dir") + .arg(&target_dir) + .status() + .expect("build sandbox probe wasm"); + assert!(status.success(), "{package} build exited with {status}"); + target_dir.join("wasm32-wasip2/debug").join(file_name) +} + +pub(crate) fn folder_import_plugin_wasm() -> &'static Path { + FOLDER_IMPORT_WASM.get_or_init(|| { + build_sandbox_probe_wasm( + "folder-import-language-plugin", + "folder_import_language_plugin.wasm", + ) + }) +} + +pub(crate) fn no_imports_language_plugin_wasm() -> &'static Path { + NO_IMPORTS_WASM.get_or_init(|| { + build_sandbox_probe_wasm( + "no-imports-language-plugin", + "no_imports_language_plugin.wasm", + ) + }) +} + pub(crate) fn init_git_repo(files: &[(&str, &str)]) -> TempDir { let dir = TempDir::new().unwrap(); let run_git = |args: &[&str]| { diff --git a/crates/cli/tests/integration/diff.rs b/crates/cli/tests/integration/diff.rs index d82acb48..28dc1b0f 100644 --- a/crates/cli/tests/integration/diff.rs +++ b/crates/cli/tests/integration/diff.rs @@ -1,6 +1,6 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fs; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use serde_json::{Value, json}; @@ -1452,13 +1452,7 @@ fn legacy_cached_measurement_without_clone_families_misses_and_recomputes() { assert_eq!(initial_families["unchanged"], 1); assert_eq!(initial_families["new"].as_array().map(Vec::len), Some(0)); - let entries: Vec<_> = fs::read_dir(fixture.result_cache.path()) - .expect("list result cache") - .map(|entry| entry.expect("cache entry").path()) - .collect(); - assert_eq!(entries.len(), 1); - let mut cached: Value = - serde_json::from_slice(&fs::read(&entries[0]).expect("read cache")).expect("parse cache"); + let (cache_path, mut cached) = read_single_result_cache_entry(fixture.result_cache.path()); for source_set in ["production", "test", "generated", "vendored"] { cached["result"][source_set] .as_object_mut() @@ -1466,7 +1460,7 @@ fn legacy_cached_measurement_without_clone_families_misses_and_recomputes() { .remove("clone_families"); } fs::write( - &entries[0], + &cache_path, serde_json::to_vec(&cached).expect("encode legacy cache"), ) .expect("overwrite legacy cache"); @@ -1477,3 +1471,103 @@ fn legacy_cached_measurement_without_clone_families_misses_and_recomputes() { assert_eq!(recomputed_families["unchanged"], 1); assert_eq!(recomputed_families["new"].as_array().map(Vec::len), Some(0)); } + +fn read_single_result_cache_entry(cache_folder: &Path) -> (PathBuf, Value) { + let entries: Vec<_> = fs::read_dir(cache_folder) + .expect("list result cache") + .map(|entry| entry.expect("cache entry").path()) + .collect(); + assert_eq!(entries.len(), 1); + let stored: Value = + serde_json::from_slice(&fs::read(&entries[0]).expect("read cache")).expect("parse cache"); + let keys: BTreeSet<&str> = stored + .as_object() + .expect("cache entry is a JSON object") + .keys() + .map(String::as_str) + .collect(); + assert_eq!(keys, BTreeSet::from(["commit", "result", "settings"])); + (entries.into_iter().next().expect("one cache entry"), stored) +} + +fn read_cached_settings_and_result(cache_folder: &Path) -> (Value, Value) { + let (_, stored) = read_single_result_cache_entry(cache_folder); + let settings: Value = serde_json::from_str( + stored["settings"] + .as_str() + .expect("cache entry settings is a JSON string"), + ) + .expect("parse cache entry settings"); + (settings, stored["result"].clone()) +} + +#[test] +fn a_result_cached_under_plugin_interface_0_2_0_is_not_reused_and_recomputes() { + let fixture = Fixture::with_an_eroded_file_removed_since_main(); + let _initial = fixture.diff_json("main"); + let (current_settings, mut stale_result) = + read_cached_settings_and_result(fixture.result_cache.path()); + stale_result["production"]["erosion"]["findings_worst_first"][0]["path"] = + json!("src/stale-from-0-2-0.ts"); + + let mut pre_step_v0_2_0_settings = current_settings.clone(); + let pre_step_map = pre_step_v0_2_0_settings + .as_object_mut() + .expect("settings is a JSON object"); + pre_step_map.insert("cache_version".to_owned(), json!(5)); + pre_step_map.remove("plugin_interface_version"); + + let mut explicit_v0_2_0_settings = current_settings.clone(); + let explicit_map = explicit_v0_2_0_settings + .as_object_mut() + .expect("settings is a JSON object"); + explicit_map.insert("plugin_interface_version".to_owned(), json!("0.2.0")); + + let repository = codeint_git::Repository::discover(fixture.root()).expect("open fixture repo"); + let commit = repository.resolve("main").expect("resolve main commit"); + + for legacy_settings in [pre_step_v0_2_0_settings, explicit_v0_2_0_settings] { + let seeded_cache = tempfile::tempdir().expect("create seeded result cache folder"); + codeint_git::ResultCache::in_folder(seeded_cache.path().to_path_buf()) + .write(commit, &legacy_settings, &stale_result) + .expect("seed 0.2.0 cache entry"); + + let output = fixture + .codeint_diff_with_result_cache(seeded_cache.path(), &["main", "--format", "json"]); + assert_eq!( + output.status.code(), + Some(0), + "codeint diff failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + let report: Value = serde_json::from_slice(&output.stdout).expect("the report is JSON"); + assert_eq!( + paths_of(&report["source_sets"]["production"]["erosion"]["resolved"]), + ["src/removed.ts"] + ); + let entries = fs::read_dir(seeded_cache.path()) + .expect("list seeded result cache folder") + .count(); + assert_eq!(entries, 2); + } + + assert_eq!(current_settings["plugin_interface_version"], json!("0.3.0")); + assert_eq!(current_settings["cache_version"], json!(6)); +} + +#[test] +fn a_result_cached_under_plugin_interface_0_3_0_is_reused_on_subsequent_runs() { + let fixture = Fixture::with_an_eroded_file_removed_since_main(); + let first = fixture.diff_json("main"); + let (settings, _) = read_cached_settings_and_result(fixture.result_cache.path()); + assert_eq!(settings["plugin_interface_version"], json!("0.3.0")); + + fixture.forget_committed_file("main:src/removed.ts"); + let second = fixture.diff_json("main"); + + assert_eq!(second, first); + let entries = fs::read_dir(fixture.result_cache.path()) + .expect("list result cache folder") + .count(); + assert_eq!(entries, 1); +} diff --git a/crates/cli/tests/integration/doctor.rs b/crates/cli/tests/integration/doctor.rs index 19181c26..acfce797 100644 --- a/crates/cli/tests/integration/doctor.rs +++ b/crates/cli/tests/integration/doctor.rs @@ -1,12 +1,63 @@ use std::collections::BTreeMap; use std::fs; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::{Command, Output}; +use std::sync::OnceLock; use codeint_plugin_host::{sha256, sha256_hex}; use serde_json::{Value, json}; use tempfile::TempDir; +static DOCTOR_SAMPLE_PLUGIN: OnceLock = OnceLock::new(); +static DOCTOR_SANDBOX_PROBES: OnceLock = OnceLock::new(); + +fn compile_fixture_dir(manifest_rel: &str, workspace: bool) -> PathBuf { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../.."); + let target = root.join("target/wasm-fixtures"); + let mut cmd = Command::new("cargo"); + cmd.args([ + "build", + "--locked", + "--offline", + "--target", + "wasm32-wasip2", + ]); + if workspace { + cmd.arg("--workspace"); + } + let status = cmd + .args([ + "--manifest-path", + &root.join(manifest_rel).to_string_lossy(), + ]) + .args(["--target-dir", &target.to_string_lossy()]) + .status() + .expect("build wasm fixture"); + assert!(status.success(), "wasm fixture build failed: {status}"); + target.join("wasm32-wasip2/debug") +} + +fn sample_plugin_bytes() -> Vec { + let path = DOCTOR_SAMPLE_PLUGIN.get_or_init(|| { + compile_fixture_dir( + "crates/plugin-host/tests/fixtures/sample-plugin/Cargo.toml", + false, + ) + .join("sample_mini_plugin.wasm") + }); + fs::read(path).expect("read compiled sample plugin") +} + +pub(crate) fn sandbox_probe_bytes(file_name: &str) -> Vec { + let dir = DOCTOR_SANDBOX_PROBES.get_or_init(|| { + compile_fixture_dir( + "crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml", + true, + ) + }); + fs::read(dir.join(file_name)).expect("read compiled sandbox probe") +} + struct DoctorFixture { dir: TempDir, cache: TempDir, @@ -334,9 +385,9 @@ fn doctor_verifies_external_wasm_plugins_and_fails_on_missing_or_mismatched_sha2 "error" ); - let wasm_bytes = b"\0asm\x01\0\0\0"; - fixture.write("plugins/sample.wasm", wasm_bytes); - let actual_hash = sha256_hex(&sha256(wasm_bytes)); + let wasm_bytes = sample_plugin_bytes(); + fixture.write("plugins/sample.wasm", &wasm_bytes); + let actual_hash = sha256_hex(&sha256(&wasm_bytes)); fixture.write_local_plugin("sample-plugin", "plugins/sample.wasm", zeros); let mismatch_report = fixture.run_json(&[], 1); @@ -515,3 +566,71 @@ fn doctor_plugin_error_remedies_name_codeint_jsonc_when_active() { ); } } + +#[test] +fn doctor_reports_v0_2_0_language_and_metric_plugins_as_not_loadable() { + let cases = [ + ( + "legacy-v02-lang", + "language", + "legacy_v0_2_0_language_plugin.wasm", + "codeint:plugin/language@0.2.0", + "codeint:plugin/language@0.3.0", + ), + ( + "legacy-v02-metric", + "metric", + "legacy_v0_2_0_metric_plugin.wasm", + "codeint:plugin/metric@0.2.0", + "codeint:plugin/metric@0.3.0", + ), + ]; + + for (name, kind, wasm_file, found_interface, expected_interface) in cases { + let fixture = DoctorFixture::git_repo_with_ts(); + let bytes = sandbox_probe_bytes(wasm_file); + let digest = sha256_hex(&sha256(&bytes)); + let rel_path = format!("plugins/{wasm_file}"); + fixture.write(&rel_path, &bytes); + fixture.write_plugin_config(json!({ + "name": name, + "kind": kind, + "path": rel_path, + "sha256": digest + })); + + let report = fixture.run_json(&[], 1); + assert_eq!(report["status"], "error", "report: {report}"); + let check = find_check(&report, &format!("plugin:{name}")); + assert_eq!(check["status"], "error", "check: {check}"); + let summary = check["summary"].as_str().unwrap_or_default(); + assert!( + summary.contains("not loadable") + && summary.contains(name) + && summary.contains(found_interface) + && summary.contains("0.2.0") + && summary.contains(expected_interface) + && summary.contains("0.3.0"), + "expected summary to report {name} not loadable with both versions, got: {summary:?}" + ); + let remedy = check["remedy"].as_str().unwrap_or_default(); + assert!( + remedy.to_ascii_lowercase().contains("rebuild") && remedy.contains("0.3.0"), + "expected remedy to instruct rebuilding against 0.3.0, got: {remedy:?}" + ); + } + + let invalid_fixture = DoctorFixture::git_repo_with_ts(); + let invalid_bytes = b"\0asm\x01\0\0\0"; + let invalid_hash = sha256_hex(&sha256(invalid_bytes)); + invalid_fixture.write("plugins/bad.wasm", invalid_bytes); + invalid_fixture.write_local_plugin("bad-plugin", "plugins/bad.wasm", &invalid_hash); + let invalid_report = invalid_fixture.run_json(&[], 1); + assert_check_field( + &invalid_report, + "plugin:bad-plugin", + "error", + "summary", + "not loadable", + ); +} diff --git a/crates/cli/tests/integration/orphan_files.rs b/crates/cli/tests/integration/orphan_files.rs index 1f3aca16..9df7d450 100644 --- a/crates/cli/tests/integration/orphan_files.rs +++ b/crates/cli/tests/integration/orphan_files.rs @@ -1,10 +1,12 @@ use std::path::Path; use std::process::Command; +use codeint_plugin_host::{sha256, sha256_hex}; use serde_json::{Value, json}; use tempfile::TempDir; use crate::common::{init_git_repo, mcp_payload, mcp_tool_call, send_mcp_requests}; +use crate::doctor::sandbox_probe_bytes; 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")); @@ -466,3 +468,87 @@ fn non_workspace_subdirectory_package_excludes_package_tooling_from_orphans() { assert_production_orphans(repo.path(), 2, &["frontend/src/dead.ts"]); } + +#[test] +fn folder_import_language_plugin_marks_all_imported_folder_files_reachable_and_flags_orphans() { + let wasm_bytes = sandbox_probe_bytes("folder_import_language_plugin.wasm"); + let digest = sha256_hex(&sha256(&wasm_bytes)); + let config = json!({ + "plugins": [{ + "name": "folder-import-lang", + "kind": "language", + "path": "plugins/folder_import_language_plugin.wasm", + "sha256": digest + }] + }) + .to_string(); + let repo = init_git_repo(&[ + ("codeint.json", config.as_str()), + ("fld.workspace", "entry: app/main.fld\n"), + ("app/main.fld", "use core\nuse solo\nfn main()\n"), + ("core/alpha.fld", "fn alpha()\n"), + ("core/beta.fld", "use nested\nfn beta()\n"), + ("core/alpha_test.fld", "use helpers\nfn test_alpha()\n"), + ("nested/first.fld", "fn first()\n"), + ("nested/second.fld", "fn second()\n"), + ("solo/only.fld", "fn only()\n"), + ("unused/orphan_a.fld", "fn orphan_a()\n"), + ("unused/orphan_b.fld", "fn orphan_b()\n"), + ("helpers/mock_a.fld", "fn mock_a()\n"), + ("helpers/mock_b.fld", "use helpers_deep\nfn mock_b()\n"), + ("helpers_deep/deep_a.fld", "fn deep_a()\n"), + ("helpers_deep/deep_b.fld", "fn deep_b()\n"), + ("tests/suite_test.fld", "use helpers\nfn test_helpers()\n"), + ]); + let plugin_path = repo + .path() + .join("plugins/folder_import_language_plugin.wasm"); + std::fs::create_dir_all(plugin_path.parent().expect("plugin parent")) + .expect("create plugins dir"); + std::fs::write(&plugin_path, &wasm_bytes).expect("write folder import wasm plugin"); + + let report = check_json(repo.path(), 0); + let orphan = production_orphans(&report); + assert_eq!(orphan["evaluated_files"], 12); + assert_eq!(orphan["entry_points"], 1); + assert_eq!(orphan["orphan_files"], 6); + assert_eq!(orphan["unreferenced"], 2); + assert_eq!(orphan["test_only"], 4); + + let findings = orphan["findings"].as_array().expect("orphan findings"); + let expected_importers: &[&str] = &["core/alpha_test.fld", "tests/suite_test.fld"]; + let observed: Vec<(&str, &str, Vec<&str>)> = findings + .iter() + .map(|entry| { + let importers = entry + .get("test_importers") + .and_then(Value::as_array) + .map(|list| { + list.iter() + .map(|item| item.as_str().expect("test importer path")) + .collect() + }) + .unwrap_or_default(); + ( + entry["path"].as_str().expect("finding path"), + entry["kind"].as_str().expect("finding kind"), + importers, + ) + }) + .collect(); + let expected: Vec<(&str, &str, &[&str])> = vec![ + ("helpers/mock_a.fld", "test-only", expected_importers), + ("helpers/mock_b.fld", "test-only", expected_importers), + ("helpers_deep/deep_a.fld", "test-only", expected_importers), + ("helpers_deep/deep_b.fld", "test-only", expected_importers), + ("unused/orphan_a.fld", "unreferenced", &[]), + ("unused/orphan_b.fld", "unreferenced", &[]), + ]; + assert_eq!( + observed + .iter() + .map(|(path, kind, importers)| (*path, *kind, importers.as_slice())) + .collect::>(), + expected + ); +} diff --git a/crates/cli/tests/integration/report.rs b/crates/cli/tests/integration/report.rs index 57842cae..a8677aff 100644 --- a/crates/cli/tests/integration/report.rs +++ b/crates/cli/tests/integration/report.rs @@ -3,8 +3,11 @@ use std::io::Write; use std::path::Path; use std::process::{Command, Output, Stdio}; +use codeint_plugin_host::{sha256, sha256_hex}; use tempfile::TempDir; +use crate::common::no_imports_language_plugin_wasm; + const GIT_ENV: [(&str, &str); 6] = [ ("GIT_CONFIG_GLOBAL", "/dev/null"), ("GIT_CONFIG_NOSYSTEM", "1"), @@ -811,3 +814,496 @@ fn rerenders_check_and_diff_json_with_cognitive_complexity_and_dependencies_loss "deps-diff.json", ); } + +fn install_no_imports_plugin(root: &Path) -> String { + let bytes = fs::read(no_imports_language_plugin_wasm()).expect("read no-imports wasm"); + let target = root.join("plugins/no_imports_language_plugin.wasm"); + fs::create_dir_all(target.parent().expect("plugin parent")).expect("mkdir plugins"); + fs::write(&target, &bytes).expect("write no-imports wasm"); + sha256_hex(&sha256(&bytes)) +} + +fn assert_import_metrics_absent_in_section(section: &serde_json::Value, label: &str) { + assert_eq!( + section.get("dependencies"), + None, + "{label} must omit dependencies" + ); + let note = section + .get("import_metrics_note") + .and_then(serde_json::Value::as_str) + .unwrap_or_else(|| panic!("{label} must include import_metrics_note: {section}")); + assert!( + !note.contains('\n'), + "{label} import_metrics_note must be one line: {note:?}" + ); + assert!( + note.contains("has no imports"), + "{label} import_metrics_note must explain language has no imports: {note:?}" + ); + let source_sets = section["source_sets"] + .as_object() + .unwrap_or_else(|| panic!("{label} missing source_sets")); + assert!(!source_sets.is_empty(), "{label} source_sets empty"); + for (source_set_name, source_set) in source_sets { + assert_eq!( + source_set.get("import_cycles"), + None, + "{label}.{source_set_name} must omit import_cycles" + ); + assert_eq!( + source_set.get("orphan_files"), + None, + "{label}.{source_set_name} must omit orphan_files" + ); + assert_eq!( + source_set.get("boundaries"), + None, + "{label}.{source_set_name} must omit boundaries" + ); + assert!(source_set.get("erosion").is_some()); + assert!(source_set.get("cognitive_complexity").is_some()); + assert!(source_set.get("duplication").is_some()); + assert!(source_set.get("verbosity").is_some()); + if let Some(packages) = source_set + .get("packages") + .and_then(serde_json::Value::as_array) + { + for package in packages { + assert_eq!( + package.get("import_cycles"), + None, + "{label}.{source_set_name} package {} must omit import_cycles", + package["path"] + ); + } + } + } +} + +fn assert_toon_omits_import_metrics(toon_section: &str, label: &str) { + assert!( + toon_section.contains("import_metrics_note:") && toon_section.contains("has no imports"), + "{label} TOON must include one-line import_metrics_note:\n{toon_section}" + ); + for forbidden in [ + "import_cycles:", + "orphan_files:", + "boundaries:", + "dependencies:", + "unused_dependencies:", + "unlisted_dependencies:", + "dev_in_production_dependencies:", + ] { + assert!( + !toon_section.contains(forbidden), + "{label} TOON must omit {forbidden}:\n{toon_section}" + ); + } +} + +struct NoImportsCheckOutputs { + json: serde_json::Value, + toon: String, + markdown: String, + sarif: serde_json::Value, +} + +fn run_no_imports_check_with_parity( + files: &[(&str, &str)], + entry_points: &[&str], + zones: serde_json::Value, + rules: serde_json::Value, + budgets: Option, +) -> NoImportsCheckOutputs { + let (dir, cache) = setup_workspace(files); + let hash = install_no_imports_plugin(dir.path()); + let mut config = serde_json::json!({ + "plugins": [{ + "name": "no-imports-lang", + "path": "plugins/no_imports_language_plugin.wasm", + "sha256": hash, + }], + "entry_points": entry_points, + "boundaries": { + "strict_zones": true, + "zones": zones, + "rules": rules, + }, + }); + if let Some(budgets) = budgets { + config["budgets"] = budgets; + } + let config_text = serde_json::to_string_pretty(&config).expect("serialize config"); + populate(dir.path(), &[("codeint.json", &config_text)]); + + let run_format = |format: &str| { + let out = invoke( + dir.path(), + cache.path(), + &["check", "--format", format], + None, + ); + assert_eq!( + out.status.code(), + Some(0), + "check --format {format} failed: {}", + utf8(&out.stderr) + ); + out.stdout + }; + let json_bytes = run_format("json"); + let json_text = utf8(&json_bytes); + let toon_text = utf8(&run_format("toon")); + let markdown_text = utf8(&run_format("markdown")); + let sarif_text = utf8(&run_format("sarif")); + for (format, expected) in [ + ("json", json_text.as_str()), + ("toon", toon_text.as_str()), + ("markdown", markdown_text.as_str()), + ("sarif", sarif_text.as_str()), + ] { + let rerendered = invoke( + dir.path(), + cache.path(), + &["report", "-", "--format", format], + Some(&json_bytes), + ); + assert_eq!( + rerendered.status.code(), + Some(0), + "report - --format {format} failed: {}", + utf8(&rerendered.stderr) + ); + assert_eq!( + utf8(&rerendered.stdout), + expected, + "report - parity mismatch for --format {format}" + ); + } + let json: serde_json::Value = serde_json::from_slice(&json_bytes).expect("parse json"); + let sarif: serde_json::Value = serde_json::from_str(&sarif_text).expect("parse sarif"); + NoImportsCheckOutputs { + json, + toon: toon_text, + markdown: markdown_text, + sarif, + } +} + +fn assert_markdown_omits_import_metrics_with_reason(markdown_section: &str, label: &str) { + assert!( + markdown_section.contains("This language has no imports, so Import cycles, Orphan files, Import boundaries, and Dependency hygiene are not measured."), + "{label} Markdown must include one-line no-imports reason:\n{markdown_section}" + ); + for required in [ + "| Erosion |", + "| Cognitive complexity |", + "| Duplication |", + "| Verbosity |", + ] { + assert!( + markdown_section.contains(required), + "{label} Markdown must still show {required}:\n{markdown_section}" + ); + } + for forbidden in [ + "| Import cycles |", + "| Boundaries |", + "| Orphan files |", + "| Unused dependencies |", + "| Unlisted dependencies |", + "| Dev dependencies in production |", + "## Dependencies", + "| not measured |", + ] { + assert!( + !markdown_section.contains(forbidden), + "{label} Markdown must omit {forbidden}:\n{markdown_section}" + ); + } +} + +fn assert_sarif_has_no_import_findings_for_extension( + sarif: &serde_json::Value, + extension: &str, + label: &str, +) { + const IMPORT_RULE_IDS: [&str; 6] = [ + "import_cycles", + "orphan_files", + "boundaries", + "unused_dependencies", + "unlisted_dependencies", + "dev_in_production_dependencies", + ]; + assert_eq!(sarif["version"], "2.1.0", "{label} must be SARIF 2.1.0"); + assert!( + sarif["$schema"] + .as_str() + .is_some_and(|schema| schema.contains("sarif-schema-2.1.0.json")), + "{label} missing SARIF 2.1.0 schema" + ); + let runs = sarif["runs"].as_array().expect("SARIF runs array"); + assert_eq!(runs.len(), 1, "{label} expected one SARIF run"); + let results = runs[0]["results"].as_array().expect("SARIF results array"); + for result in results { + let rule_id = result["ruleId"].as_str().unwrap_or(""); + if !IMPORT_RULE_IDS.contains(&rule_id) { + continue; + } + let message = result["message"]["text"].as_str().unwrap_or(""); + assert!( + !message.contains(extension), + "{label} SARIF import finding ({rule_id}) references {extension}: {result}" + ); + for key in ["locations", "relatedLocations"] { + if let Some(locations) = result.get(key).and_then(serde_json::Value::as_array) { + for location in locations { + let uri = location["physicalLocation"]["artifactLocation"]["uri"] + .as_str() + .unwrap_or(""); + assert!( + !uri.ends_with(extension), + "{label} SARIF import finding ({rule_id}) points at {uri}: {result}" + ); + } + } + } + } +} + +fn run_mixed_no_imports_repo( + include_ts_import_findings: bool, + zones: serde_json::Value, +) -> NoImportsCheckOutputs { + let mut files = vec![ + ( + "package.json", + r#"{"name":"root","private":true,"workspaces":["packages/*"]}"#, + ), + ( + "packages/app/package.json", + r#"{"name":"app","main":"src/index.ts","dependencies":{"unused-pkg":"^1.0.0"},"devDependencies":{"dev-pkg":"^1.0.0"}}"#, + ), + ( + "packages/app/src/orphan.ts", + "export const unused = (): number => 2;\n", + ), + ("packages/app/queries/users.noimp", "fn select_users()\n"), + ( + "packages/app/queries/users_test.noimp", + "fn test_select_users()\n", + ), + ]; + if include_ts_import_findings { + files.extend([ + ( + "packages/app/src/index.ts", + "import ghost from \"unlisted-pkg\";\nimport devOnly from \"dev-pkg\";\nimport { a } from \"./cycle_a\";\nexport const ok = (): number => Number(ghost) + Number(devOnly) + a();\n", + ), + ( + "packages/app/src/cycle_a.ts", + "import { b } from \"./cycle_b\";\nexport const a = (): number => b() + 1;\n", + ), + ( + "packages/app/src/cycle_b.ts", + "import { a } from \"./cycle_a\";\nexport const b = (): number => a() + 1;\n", + ), + ]); + } else { + files.push(( + "packages/app/src/index.ts", + "export const ok = (): number => 1;\n", + )); + } + run_no_imports_check_with_parity( + &files, + &[ + "packages/app/src/index.ts", + "packages/app/queries/users.noimp", + ], + zones, + serde_json::json!([{ "from": "app", "allow": ["app"] }]), + None, + ) +} + +fn run_no_imports_only_repo(zones: serde_json::Value) -> NoImportsCheckOutputs { + run_no_imports_check_with_parity( + &[ + ("queries/users.noimp", "fn select_users()\n"), + ("queries/users_test.noimp", "fn test_select_users()\n"), + ], + &["queries/users.noimp"], + zones, + serde_json::json!([]), + Some(serde_json::json!({ "production": { "import_cycles": 0.0 } })), + ) +} + +#[test] +fn no_imports_language_omits_import_metrics_with_reason_in_json_and_toon() { + let outputs = run_mixed_no_imports_repo( + false, + serde_json::json!({ + "app": { "patterns": ["packages/app/src/**"] }, + "queries": { "patterns": ["packages/app/queries/**"] }, + }), + ); + let doc = outputs.json; + let toon = outputs.toon; + + let no_imports = &doc["languages"]["no-imports-lang"]; + assert_import_metrics_absent_in_section(no_imports, "languages.no-imports-lang"); + let no_imports_packages = no_imports["source_sets"]["production"]["packages"] + .as_array() + .expect("no-imports-lang production packages"); + assert!( + !no_imports_packages.is_empty(), + "expected workspace package entry in no-imports-lang section" + ); + + let ts = &doc["languages"]["typescript-javascript"]; + assert_eq!(ts.get("import_metrics_note"), None); + assert!(ts.get("dependencies").is_some()); + assert!(ts["dependencies"].get("unused_dependencies").is_some()); + assert!(ts["dependencies"].get("unlisted_dependencies").is_some()); + assert!( + ts["dependencies"] + .get("dev_in_production_dependencies") + .is_some() + ); + let ts_prod = &ts["source_sets"]["production"]; + assert!(ts_prod.get("import_cycles").is_some()); + assert!(ts_prod.get("orphan_files").is_some()); + assert!(ts_prod.get("boundaries").is_some()); + let ts_packages = ts_prod["packages"].as_array().expect("ts packages"); + assert!(ts_packages[0].get("import_cycles").is_some()); + + let no_imports_start = toon + .find("\n \"no-imports-lang\":\n") + .unwrap_or_else(|| panic!("no-imports-lang section in TOON:\n{toon}")); + let ts_start = toon + .find("\n \"typescript-javascript\":\n") + .unwrap_or_else(|| panic!("typescript-javascript section in TOON:\n{toon}")); + assert!(no_imports_start < ts_start); + let no_imports_toon = &toon[no_imports_start..ts_start]; + let ts_toon = &toon[ts_start..]; + assert_toon_omits_import_metrics(no_imports_toon, "languages.no-imports-lang"); + assert!(ts_toon.contains("import_cycles:")); + assert!(ts_toon.contains("orphan_files:")); + assert!(ts_toon.contains("boundaries:")); + assert!(ts_toon.contains("dependencies:")); + assert!(!ts_toon.contains("import_metrics_note:")); +} + +#[test] +fn no_imports_only_repo_omits_import_metrics_with_reason_in_json_and_toon() { + let outputs = + run_no_imports_only_repo(serde_json::json!({ "queries": { "patterns": ["queries/**"] } })); + let doc = outputs.json; + let toon = outputs.toon; + assert_eq!(doc.get("languages"), None); + assert_eq!(doc.get("over_budget"), None); + assert_import_metrics_absent_in_section(&doc, "top-level no-imports-only repo"); + assert_toon_omits_import_metrics(&toon, "top-level no-imports-only repo"); +} + +#[test] +fn no_imports_language_omits_import_metrics_in_markdown_and_has_no_import_findings_in_sarif() { + let outputs = run_mixed_no_imports_repo( + true, + serde_json::json!({ + "app": { "patterns": ["packages/app/src/**"] }, + }), + ); + + let md = &outputs.markdown; + let no_imports_start = md + .find("## Language plugin `no-imports-lang`") + .unwrap_or_else(|| panic!("no-imports-lang heading missing in Markdown:\n{md}")); + let ts_start = md + .find("## Language plugin `typescript-javascript`") + .unwrap_or_else(|| panic!("typescript-javascript heading missing in Markdown:\n{md}")); + let findings_start = md + .find("## Production Findings") + .unwrap_or_else(|| panic!("Production Findings heading missing in Markdown:\n{md}")); + assert!(no_imports_start < ts_start && ts_start < findings_start); + + let no_imports_md = &md[no_imports_start..ts_start]; + let ts_md = &md[ts_start..findings_start]; + let findings_md = &md[findings_start..]; + + assert_markdown_omits_import_metrics_with_reason(no_imports_md, "languages.no-imports-lang"); + assert!( + no_imports_md.contains("| `packages/app` |"), + "expected workspace package row in no-imports-lang Markdown:\n{no_imports_md}" + ); + assert!( + !findings_md.contains(".noimp"), + "findings Markdown must not report import findings for .noimp files:\n{findings_md}" + ); + + assert!( + !ts_md.contains("has no imports"), + "typescript-javascript Markdown must not show no-imports note:\n{ts_md}" + ); + for required in [ + "| Import cycles |", + "| Boundaries |", + "| Orphan files |", + "| Unused dependencies |", + "| Unlisted dependencies |", + "| Dev dependencies in production |", + ] { + assert!( + ts_md.contains(required), + "typescript-javascript Markdown must keep {required}:\n{ts_md}" + ); + } + + assert_sarif_has_no_import_findings_for_extension(&outputs.sarif, ".noimp", "mixed repo"); + let rule_ids: std::collections::HashSet<&str> = outputs.sarif["runs"][0]["results"] + .as_array() + .expect("SARIF results") + .iter() + .filter_map(|result| result["ruleId"].as_str()) + .collect(); + for expected_ts_rule in [ + "import_cycles", + "orphan_files", + "unused_dependencies", + "unlisted_dependencies", + "dev_in_production_dependencies", + ] { + assert!( + rule_ids.contains(expected_ts_rule), + "expected TypeScript {expected_ts_rule} finding in mixed-repo SARIF; saw {rule_ids:?}" + ); + } +} + +#[test] +fn no_imports_only_repo_omits_import_metrics_in_markdown_and_has_no_import_findings_in_sarif() { + let outputs = + run_no_imports_only_repo(serde_json::json!({ "other": { "patterns": ["other/**"] } })); + + assert_markdown_omits_import_metrics_with_reason( + &outputs.markdown, + "top-level no-imports-only repo", + ); + assert_sarif_has_no_import_findings_for_extension( + &outputs.sarif, + ".noimp", + "no-imports-only repo", + ); + assert!( + outputs.sarif["runs"][0]["results"] + .as_array() + .expect("SARIF results") + .is_empty(), + "no-imports-only repo with clean functions must have zero SARIF results: {}", + outputs.sarif + ); +} diff --git a/crates/cli/tests/integration/trace.rs b/crates/cli/tests/integration/trace.rs index 9d608805..7ce3c1f7 100644 --- a/crates/cli/tests/integration/trace.rs +++ b/crates/cli/tests/integration/trace.rs @@ -1,9 +1,13 @@ +use std::fs; use std::path::Path; use std::process::{Command, Output}; +use codeint_plugin_host::{sha256, sha256_hex}; use serde_json::{Value, json}; -use crate::common::{init_git_repo, mcp_payload, mcp_tool_call, send_mcp_requests}; +use crate::common::{ + folder_import_plugin_wasm, init_git_repo, mcp_payload, mcp_tool_call, send_mcp_requests, +}; fn run_trace(dir: &Path, args: &[&str]) -> Output { Command::new(env!("CARGO_BIN_EXE_codeint")) @@ -62,6 +66,7 @@ fn trace_finds_shortest_runtime_import_path_in_cli_json_text_and_toon() { assert_eq!(parsed["connected"], true); assert_eq!(parsed["shortest_distance"], 2); assert_eq!(parsed["truncated"], false); + assert!(parsed.get("multi_file_imports").is_none()); assert_eq!( parsed["paths"], json!([["src/a.ts", "src/d.ts", "src/target.ts"]]) @@ -105,6 +110,7 @@ fn trace_all_returns_multiple_shortest_paths_deterministically_with_cap() { let parsed = trace_json(repo.path(), &["src/entry.ts", "src/leaf.ts", "--all"]); assert_eq!(parsed["shortest_distance"], 2); assert_eq!(parsed["truncated"], false); + assert!(parsed.get("multi_file_imports").is_none()); assert_eq!( parsed["paths"], json!([ @@ -281,3 +287,117 @@ fn trace_works_across_source_sets_and_python_and_rejects_zero_max_paths() { ); assert_eq!(zero_cap.status.code(), Some(2)); } + +#[test] +fn trace_lists_every_file_of_a_folder_import_and_explains_reachability() { + let wasm_bytes = fs::read(folder_import_plugin_wasm()).expect("read folder import wasm"); + let wasm_hash = sha256_hex(&sha256(&wasm_bytes)); + let config = format!( + r#"{{"plugins":[{{"name":"folder-import-lang","path":"plugins/folder_import_language_plugin.wasm","sha256":"{wasm_hash}"}}]}}"# + ); + let repo = init_git_repo(&[ + ("codeint.json", &config), + ( + "src/app.fld", + "program main\nuse pkg/mid\nuse pkg/unused\nfn main()\n", + ), + ("pkg/mid/a.fld", "use pkg/leaf\nfn alpha()\n"), + ("pkg/mid/b.fld", "use pkg/leaf\nfn beta()\n"), + ("pkg/mid/sibling.fld", "fn sibling()\n"), + ("pkg/leaf/end.fld", "fn end()\n"), + ("pkg/leaf/other.fld", "fn other()\n"), + ("pkg/unused/u1.fld", "fn u1()\n"), + ("pkg/unused/u2.fld", "fn u2()\n"), + ]); + let plugin_dest = repo + .path() + .join("plugins/folder_import_language_plugin.wasm"); + fs::create_dir_all(plugin_dest.parent().unwrap()).unwrap(); + fs::write(&plugin_dest, &wasm_bytes).unwrap(); + + let all_json = trace_json(repo.path(), &["src/app.fld", "pkg/leaf/end.fld", "--all"]); + assert_eq!(all_json["from"], "src/app.fld"); + assert_eq!(all_json["to"], "pkg/leaf/end.fld"); + assert_eq!(all_json["from_entry_point"], "program-start mark"); + assert_eq!(all_json["connected"], true); + assert_eq!(all_json["shortest_distance"], 2); + assert_eq!( + all_json["paths"], + json!([ + ["src/app.fld", "pkg/mid/a.fld", "pkg/leaf/end.fld"], + ["src/app.fld", "pkg/mid/b.fld", "pkg/leaf/end.fld"], + ]) + ); + assert_eq!( + all_json["multi_file_imports"], + json!([ + { + "importer": "src/app.fld", + "specifier": "pkg/mid", + "targets": ["pkg/mid/a.fld", "pkg/mid/b.fld", "pkg/mid/sibling.fld"], + }, + { + "importer": "pkg/mid/a.fld", + "specifier": "pkg/leaf", + "targets": ["pkg/leaf/end.fld", "pkg/leaf/other.fld"], + }, + { + "importer": "pkg/mid/b.fld", + "specifier": "pkg/leaf", + "targets": ["pkg/leaf/end.fld", "pkg/leaf/other.fld"], + }, + ]) + ); + + let all_text = trace_text(repo.path(), &["src/app.fld", "pkg/leaf/end.fld", "--all"]); + assert_eq!( + all_text, + [ + "Entry point: src/app.fld (program-start mark)", + "src/app.fld -> pkg/mid/a.fld -> pkg/leaf/end.fld", + "src/app.fld -> pkg/mid/b.fld -> pkg/leaf/end.fld", + "Import pkg/mid in src/app.fld leads to: pkg/mid/a.fld, pkg/mid/b.fld, pkg/mid/sibling.fld", + "Import pkg/leaf in pkg/mid/a.fld leads to: pkg/leaf/end.fld, pkg/leaf/other.fld", + "Import pkg/leaf in pkg/mid/b.fld leads to: pkg/leaf/end.fld, pkg/leaf/other.fld", + ] + .join("\n") + ); + + let toon_output = run_trace(repo.path(), &["src/app.fld", "pkg/leaf/end.fld", "--all"]); + assert!( + toon_output.status.success(), + "trace toon failed: {}", + String::from_utf8_lossy(&toon_output.stderr) + ); + let toon = String::from_utf8(toon_output.stdout).unwrap(); + assert!(toon.contains("multi_file_imports"), "toon: {toon}"); + assert!(toon.contains("pkg/mid/sibling.fld"), "toon: {toon}"); + assert!(toon.contains("pkg/leaf/other.fld"), "toon: {toon}"); + + let direct_json = trace_json(repo.path(), &["src/app.fld", "pkg/mid/sibling.fld"]); + assert_eq!(direct_json["connected"], true); + assert_eq!(direct_json["shortest_distance"], 1); + assert_eq!( + direct_json["paths"], + json!([["src/app.fld", "pkg/mid/sibling.fld"]]) + ); + assert_eq!( + direct_json["multi_file_imports"], + json!([ + { + "importer": "src/app.fld", + "specifier": "pkg/mid", + "targets": ["pkg/mid/a.fld", "pkg/mid/b.fld", "pkg/mid/sibling.fld"], + } + ]) + ); + assert_eq!( + trace_text(repo.path(), &["src/app.fld", "pkg/mid/sibling.fld"]), + [ + "Entry point: src/app.fld (program-start mark)", + "src/app.fld -> pkg/mid/sibling.fld", + "Import pkg/mid in src/app.fld leads to: pkg/mid/a.fld, pkg/mid/b.fld, pkg/mid/sibling.fld", + ] + .join("\n") + ); +} diff --git a/crates/cli/tests/plugins.rs b/crates/cli/tests/plugins.rs index d3125864..6955fac5 100644 --- a/crates/cli/tests/plugins.rs +++ b/crates/cli/tests/plugins.rs @@ -110,13 +110,14 @@ fn copy_metric_plugin_into(repo_root: &Path, relative: &str) -> String { copy_wasm_into(built_sample_metric_plugin(), repo_root, relative) } -fn assert_sandbox_probe_exits_2(plugin_name: &str, wasm_file: &str, denied_interface: &str) { +fn run_check_with_sandbox_probe(plugin_name: &str, kind: Option<&str>, wasm_file: &str) -> Output { let repo = init_repo(); let hash = copy_wasm_into( &built_sandbox_probe(wasm_file), repo.path(), &format!("plugins/{wasm_file}"), ); + let kind_line = kind.map_or_else(String::new, |kind| format!(r#""kind": "{kind}","#)); write_file( repo.path(), "codeint.json", @@ -125,6 +126,7 @@ fn assert_sandbox_probe_exits_2(plugin_name: &str, wasm_file: &str, denied_inter "plugins": [ {{ "name": "{plugin_name}", + {kind_line} "path": "plugins/{wasm_file}", "sha256": "{hash}" }} @@ -135,7 +137,6 @@ fn assert_sandbox_probe_exits_2(plugin_name: &str, wasm_file: &str, denied_inter write_file(repo.path(), "src/app.ts", "export const ok = 1;\n"); let output = run_codeint(repo.path(), &["check"]); - assert_eq!( output.status.code(), Some(2), @@ -143,6 +144,11 @@ fn assert_sandbox_probe_exits_2(plugin_name: &str, wasm_file: &str, denied_inter output.status.code(), String::from_utf8_lossy(&output.stderr) ); + output +} + +fn assert_sandbox_probe_exits_2(plugin_name: &str, wasm_file: &str, denied_interface: &str) { + let output = run_check_with_sandbox_probe(plugin_name, None, wasm_file); let stderr = String::from_utf8_lossy(&output.stderr); assert!( stderr.contains("cannot instantiate Plugin") @@ -153,6 +159,48 @@ fn assert_sandbox_probe_exits_2(plugin_name: &str, wasm_file: &str, denied_inter ); } +fn assert_check_exits_2(dir: &Path, expected_substrings: &[&str]) { + let output = run_codeint(dir, &["check"]); + assert_eq!( + output.status.code(), + Some(2), + "expected exit 2, got {:?}\nstderr: {}", + output.status.code(), + String::from_utf8_lossy(&output.stderr) + ); + let stderr = String::from_utf8_lossy(&output.stderr); + for expected in expected_substrings { + assert!( + stderr.contains(expected), + "expected {expected:?} in stderr, got: {stderr}" + ); + } +} + +fn assert_skipped_reason(report: &Value, expected_path: &str, expected_substrings: &[&str]) { + assert_eq!(report["skipped"][0]["path"], expected_path); + let reason = report["skipped"][0]["reason"] + .as_str() + .expect("skipped reason string"); + for expected in expected_substrings { + assert!( + reason.contains(expected), + "expected {expected:?} in skipped reason, got: {reason}" + ); + } +} + +fn run_check_json_with_env(dir: &Path, envs: &[(&str, &Path)]) -> Value { + let output = run_codeint_with_env(dir, &["check", "--format", "json"], envs); + assert_eq!( + output.status.code(), + Some(0), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).expect("valid JSON report") +} + #[test] fn missing_sha256_hash_is_a_configuration_error_and_exits_2() { let repo = init_repo(); @@ -161,15 +209,7 @@ fn missing_sha256_hash_is_a_configuration_error_and_exits_2() { "codeint.json", r#"{ "plugins": [{ "name": "sample-mini", "path": "plugins/sample.wasm" }] }"#, ); - - let output = run_codeint(repo.path(), &["check"]); - - assert_eq!(output.status.code(), Some(2)); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("plugins[0]") && stderr.contains("sha256"), - "expected missing sha256 error, got: {stderr}" - ); + assert_check_exits_2(repo.path(), &["plugins[0]", "sha256"]); } #[test] @@ -180,45 +220,25 @@ fn invalid_sha256_hash_is_a_configuration_error_and_exits_2() { "codeint.json", r#"{ "plugins": [{ "name": "sample-mini", "path": "plugins/sample.wasm", "sha256": "not-a-hash" }] }"#, ); - - let output = run_codeint(repo.path(), &["check"]); - - assert_eq!(output.status.code(), Some(2)); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("plugins[0].sha256") && stderr.contains("64-character"), - "expected invalid sha256 error, got: {stderr}" - ); + assert_check_exits_2(repo.path(), &["plugins[0].sha256", "64-character"]); } #[test] fn hash_mismatch_refuses_to_load_the_plugin_and_exits_2() { let repo = init_repo(); let _actual = copy_plugin_into(repo.path(), "plugins/sample.wasm"); - write_file( + write_plugin_config( repo.path(), - "codeint.json", - r#"{ - "plugins": [ - { - "name": "sample-mini", - "path": "plugins/sample.wasm", - "sha256": "0000000000000000000000000000000000000000000000000000000000000000" - } - ] - }"#, + "sample-mini", + None, + "plugins/sample.wasm", + "0000000000000000000000000000000000000000000000000000000000000000", + "", ); write_file(repo.path(), "src/app.mini", "fn main() {\n return 1\n}\n"); - - let output = run_codeint(repo.path(), &["check"]); - - assert_eq!(output.status.code(), Some(2)); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("SHA-256 hash mismatch") - && stderr.contains("sample-mini") - && stderr.contains("sample.wasm"), - "expected hash mismatch naming plugin and path, got: {stderr}" + assert_check_exits_2( + repo.path(), + &["SHA-256 hash mismatch", "sample-mini", "sample.wasm"], ); } @@ -226,20 +246,13 @@ fn hash_mismatch_refuses_to_load_the_plugin_and_exits_2() { fn sample_external_plugin_measures_its_fixture_language_end_to_end_through_codeint_check() { let repo = init_repo(); let hash = copy_plugin_into(repo.path(), "plugins/sample.wasm"); - write_file( + write_plugin_config( repo.path(), - "codeint.json", - &format!( - r#"{{ - "plugins": [ - {{ - "name": "sample-mini", - "path": "plugins/sample.wasm", - "sha256": "{hash}" - }} - ] - }}"# - ), + "sample-mini", + None, + "plugins/sample.wasm", + &hash, + "", ); write_file( repo.path(), @@ -254,16 +267,7 @@ fn sample_external_plugin_measures_its_fixture_language_end_to_end_through_codei write_file(repo.path(), "src/types.d.mini", "fn extern_decl() {}\n"); write_file(repo.path(), "src/broken.mini", "SYNTAX_ERROR\n"); - let output = run_codeint(&repo.path().join("src"), &["check", "--format", "json"]); - - assert_eq!( - output.status.code(), - Some(0), - "stderr: {}", - String::from_utf8_lossy(&output.stderr) - ); - let report: Value = - serde_json::from_slice(&output.stdout).expect("codeint check prints valid JSON"); + let report = run_check_json_report(&repo.path().join("src")); assert_eq!(report["files"], 2); assert_eq!(report["source_lines"], 8); assert_eq!( @@ -418,17 +422,15 @@ fn two_external_plugins_claiming_one_extension_in_overlapping_languages_folders_ "fn main() {\n return 1\n}\n", ); - let output = run_codeint(repo.path(), &["check"]); - - assert_eq!(output.status.code(), Some(2)); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("alpha-mini") - && stderr.contains("zeta-mini") - && stderr.contains(".mini") - && stderr.contains("src/sub/app.mini") - && stderr.contains("languages"), - "expected extension conflict error, got: {stderr}" + assert_check_exits_2( + repo.path(), + &[ + "alpha-mini", + "zeta-mini", + ".mini", + "src/sub/app.mini", + "languages", + ], ); } @@ -471,16 +473,7 @@ fn assigning_separate_directories_in_languages_resolves_external_plugin_extensio "fn zeta() {\n pass;\n return 2\n}\n", ); - let output = run_codeint(repo.path(), &["check", "--format", "json"]); - - assert_eq!( - output.status.code(), - Some(0), - "stderr: {}", - String::from_utf8_lossy(&output.stderr) - ); - let report: Value = - serde_json::from_slice(&output.stdout).expect("codeint check prints valid JSON"); + let report = run_check_json_report(repo.path()); assert_eq!(report["files"], 2, "unexpected report: {report}"); assert_eq!( report["languages"]["alpha-mini"]["files"], 1, @@ -513,7 +506,15 @@ fn short_ts_function(name: &str) -> String { format!("export function {name}(x: number): number {{\n return x + 1;\n}}\n") } -fn write_metric_plugin_config(repo_root: &Path, hash: &str, extra_fields: &str) { +fn write_plugin_config( + repo_root: &Path, + name: &str, + kind: Option<&str>, + path: &str, + hash: &str, + extra_fields: &str, +) { + let kind_line = kind.map_or_else(String::new, |kind| format!(r#""kind": "{kind}","#)); let trailing = if extra_fields.is_empty() { String::new() } else { @@ -526,9 +527,9 @@ fn write_metric_plugin_config(repo_root: &Path, hash: &str, extra_fields: &str) r#"{{ "plugins": [ {{ - "name": "long-functions", - "kind": "metric", - "path": "plugins/long_functions.wasm", + "name": "{name}", + {kind_line} + "path": "{path}", "sha256": "{hash}" }} ]{trailing} @@ -537,6 +538,17 @@ fn write_metric_plugin_config(repo_root: &Path, hash: &str, extra_fields: &str) ); } +fn write_metric_plugin_config(repo_root: &Path, hash: &str, extra_fields: &str) { + write_plugin_config( + repo_root, + "long-functions", + Some("metric"), + "plugins/long_functions.wasm", + hash, + extra_fields, + ); +} + #[test] fn sample_external_metric_plugin_appears_next_to_builtin_metrics_in_check_reports() { let repo = init_repo(); @@ -552,15 +564,7 @@ fn sample_external_metric_plugin_appears_next_to_builtin_metrics_in_check_report ), ); - let json_output = run_codeint(repo.path(), &["check", "--format", "json"]); - assert_eq!( - json_output.status.code(), - Some(0), - "stderr: {}", - String::from_utf8_lossy(&json_output.stderr) - ); - let report: Value = - serde_json::from_slice(&json_output.stdout).expect("codeint check prints valid JSON"); + let report = run_check_json_report(repo.path()); let prod = &report["source_sets"]["production"]; assert!(prod.get("erosion").is_some()); assert!(prod.get("duplication").is_some()); @@ -638,13 +642,7 @@ fn external_metric_plugin_works_with_budgets_in_check() { r#""budgets": { "production": { "long_functions": 0.5 } }"#, ); - let passing_output = run_codeint(repo.path(), &["check", "--format", "json"]); - assert_eq!( - passing_output.status.code(), - Some(0), - "stderr: {}", - String::from_utf8_lossy(&passing_output.stderr) - ); + let _ = run_check_json_report(repo.path()); } #[test] @@ -880,14 +878,7 @@ fn https_url_plugin_downloads_once_caches_by_sha256_and_runs_offline_after_serve ("CODEINT_CACHE_DIR", cache_dir.path()), ("CODEINT_TEST_CA_CERT", server.cert_path()), ]; - let first = run_codeint_with_env(repo.path(), &["check", "--format", "json"], &envs); - assert_eq!( - first.status.code(), - Some(0), - "stderr: {}", - String::from_utf8_lossy(&first.stderr) - ); - let report: Value = serde_json::from_slice(&first.stdout).expect("valid JSON report"); + let report = run_check_json_with_env(repo.path(), &envs); assert_eq!(report["files"], 1); assert_eq!( report["source_sets"]["production"]["verbosity"]["flagged_lines"], @@ -906,19 +897,8 @@ fn https_url_plugin_downloads_once_caches_by_sha256_and_runs_offline_after_serve server.stop(); - let second = run_codeint_with_env( - repo.path(), - &["check", "--format", "json"], - &[("CODEINT_CACHE_DIR", cache_dir.path())], - ); - assert_eq!( - second.status.code(), - Some(0), - "expected cache hit after server stopped, stderr: {}", - String::from_utf8_lossy(&second.stderr) - ); - let second_report: Value = - serde_json::from_slice(&second.stdout).expect("valid JSON report from cache"); + let second_report = + run_check_json_with_env(repo.path(), &[("CODEINT_CACHE_DIR", cache_dir.path())]); assert_eq!(second_report["files"], 1); assert_eq!( second_report["source_sets"]["production"]["verbosity"]["flagged_lines"], @@ -980,14 +960,7 @@ fn plain_http_and_non_https_plugin_urls_are_refused_with_exit_2() { "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", ); - let output = run_codeint(repo.path(), &["check"]); - - assert_eq!(output.status.code(), Some(2), "url {bad_url}"); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("insecure-mini") && stderr.contains("HTTPS"), - "expected HTTPS-required error naming plugin for {bad_url}, got: {stderr}" - ); + assert_check_exits_2(repo.path(), &["insecure-mini", "HTTPS"]); } } @@ -1006,15 +979,7 @@ fn plugin_entry_must_specify_either_path_or_url_not_neither_or_both() { ] }"#, ); - let neither = run_codeint(neither_repo.path(), &["check"]); - assert_eq!(neither.status.code(), Some(2)); - let neither_stderr = String::from_utf8_lossy(&neither.stderr); - assert!( - neither_stderr.contains("missing-source") - && neither_stderr.contains("path") - && neither_stderr.contains("url"), - "expected missing source error, got: {neither_stderr}" - ); + assert_check_exits_2(neither_repo.path(), &["missing-source", "path", "url"]); let both_repo = init_repo(); write_file( @@ -1031,185 +996,93 @@ fn plugin_entry_must_specify_either_path_or_url_not_neither_or_both() { ] }"#, ); - let both = run_codeint(both_repo.path(), &["check"]); - assert_eq!(both.status.code(), Some(2)); - let both_stderr = String::from_utf8_lossy(&both.stderr); - assert!( - both_stderr.contains("both-sources") && both_stderr.contains("not both"), - "expected ambiguous source error, got: {both_stderr}" - ); + assert_check_exits_2(both_repo.path(), &["both-sources", "not both"]); } -#[test] -fn language_plugin_that_loops_forever_skips_the_file_and_finishes_the_run() { +fn init_single_probe_repo( + plugin_name: &str, + kind: Option<&str>, + wasm_file: &str, + extra_config: &str, +) -> (TempDir, String) { let repo = init_repo(); - let hash = copy_wasm_into( - &built_sandbox_probe("loop_language_plugin.wasm"), + let plugin_rel = format!("plugins/{wasm_file}"); + let hash = copy_wasm_into(&built_sandbox_probe(wasm_file), repo.path(), &plugin_rel); + write_plugin_config( repo.path(), - "plugins/loop_lang.wasm", + plugin_name, + kind, + &plugin_rel, + &hash, + extra_config, ); - write_file( - repo.path(), - "codeint.json", - &format!( - r#"{{ - "plugins": [ - {{ - "name": "loop-lang", - "path": "plugins/loop_lang.wasm", - "sha256": "{hash}" - }} - ], - "plugin_limits": {{ - "timeout_ms": 50 - }} - }}"# - ), + (repo, hash) +} + +#[test] +fn language_plugin_that_loops_forever_skips_the_file_and_finishes_the_run() { + let (repo, _hash) = init_single_probe_repo( + "loop-lang", + None, + "loop_language_plugin.wasm", + r#""plugin_limits": { "timeout_ms": 50 }"#, ); write_file(repo.path(), "src/hang.loop", "LOOP_FOREVER\n"); write_file(repo.path(), "src/healthy.loop", "ok line 1\nok line 2\n"); - let output = run_codeint(repo.path(), &["check", "--format", "json"]); - - assert_eq!( - output.status.code(), - Some(0), - "stderr: {}", - String::from_utf8_lossy(&output.stderr) - ); - let report: Value = - serde_json::from_slice(&output.stdout).expect("codeint check prints valid JSON"); + let report = run_check_json_report(repo.path()); assert_eq!(report["files"], 1); assert_eq!(report["source_lines"], 2); - assert_eq!(report["skipped"][0]["path"], "src/hang.loop"); - let reason = report["skipped"][0]["reason"] - .as_str() - .expect("skipped reason string"); - assert!( - reason.contains("loop-lang") && reason.contains("time limit") && reason.contains("50 ms"), - "unexpected skipped reason: {reason}" + assert_skipped_reason( + &report, + "src/hang.loop", + &["loop-lang", "time limit", "50 ms"], ); } #[test] fn language_plugin_that_grows_memory_past_cap_skips_the_file_and_raised_limit_takes_effect() { - let repo = init_repo(); - let hash = copy_wasm_into( - &built_sandbox_probe("memory_hog_language_plugin.wasm"), - repo.path(), - "plugins/hog_lang.wasm", - ); - write_file( - repo.path(), - "codeint.json", - &format!( - r#"{{ - "plugins": [ - {{ - "name": "hog-lang", - "path": "plugins/hog_lang.wasm", - "sha256": "{hash}" - }} - ], - "plugin_limits": {{ - "memory_mb": 2 - }} - }}"# - ), + let (repo, hash) = init_single_probe_repo( + "hog-lang", + None, + "memory_hog_language_plugin.wasm", + r#""plugin_limits": { "memory_mb": 2 }"#, ); write_file(repo.path(), "src/heavy.hog", "ALLOC_2MB\n"); write_file(repo.path(), "src/light.hog", "ok\n"); - let tight_output = run_codeint(repo.path(), &["check", "--format", "json"]); - assert_eq!( - tight_output.status.code(), - Some(0), - "stderr: {}", - String::from_utf8_lossy(&tight_output.stderr) - ); - let tight_report: Value = - serde_json::from_slice(&tight_output.stdout).expect("codeint check prints valid JSON"); + let tight_report = run_check_json_report(repo.path()); assert_eq!(tight_report["files"], 1); - assert_eq!(tight_report["skipped"][0]["path"], "src/heavy.hog"); - let reason = tight_report["skipped"][0]["reason"] - .as_str() - .expect("skipped reason string"); - assert!( - reason.contains("hog-lang") && reason.contains("memory cap") && reason.contains("2 MiB"), - "unexpected skipped reason: {reason}" + assert_skipped_reason( + &tight_report, + "src/heavy.hog", + &["hog-lang", "memory cap", "2 MiB"], ); - write_file( + write_plugin_config( repo.path(), - "codeint.json", - &format!( - r#"{{ - "plugins": [ - {{ - "name": "hog-lang", - "path": "plugins/hog_lang.wasm", - "sha256": "{hash}" - }} - ], - "plugin_limits": {{ - "memory_mb": 8 - }} - }}"# - ), + "hog-lang", + None, + "plugins/memory_hog_language_plugin.wasm", + &hash, + r#""plugin_limits": { "memory_mb": 8 }"#, ); - let raised_output = run_codeint(repo.path(), &["check", "--format", "json"]); - assert_eq!( - raised_output.status.code(), - Some(0), - "stderr: {}", - String::from_utf8_lossy(&raised_output.stderr) - ); - let raised_report: Value = - serde_json::from_slice(&raised_output.stdout).expect("codeint check prints valid JSON"); + let raised_report = run_check_json_report(repo.path()); assert_eq!(raised_report["files"], 2); assert!(raised_report.get("skipped").is_none()); } #[test] fn metric_plugin_that_loops_forever_stops_the_run_with_exit_2_and_names_the_plugin() { - let repo = init_repo(); - let hash = copy_wasm_into( - &built_sandbox_probe("loop_metric_plugin.wasm"), - repo.path(), - "plugins/loop_metric.wasm", - ); - write_file( - repo.path(), - "codeint.json", - &format!( - r#"{{ - "plugins": [ - {{ - "name": "runaway-metric", - "kind": "metric", - "path": "plugins/loop_metric.wasm", - "sha256": "{hash}" - }} - ], - "plugin_limits": {{ - "timeout_ms": 50 - }} - }}"# - ), + let (repo, _hash) = init_single_probe_repo( + "runaway-metric", + Some("metric"), + "loop_metric_plugin.wasm", + r#""plugin_limits": { "timeout_ms": 50 }"#, ); write_file(repo.path(), "src/app.ts", "export const ok = 1;\n"); - - let output = run_codeint(repo.path(), &["check"]); - - assert_eq!(output.status.code(), Some(2)); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("runaway-metric") - && stderr.contains("time limit") - && stderr.contains("50 ms"), - "expected time limit error naming runaway-metric, got: {stderr}" - ); + assert_check_exits_2(repo.path(), &["runaway-metric", "time limit", "50 ms"]); } #[test] @@ -1249,3 +1122,687 @@ fn invalid_plugin_limits_print_the_offending_key_and_exit_2() { ); } } + +fn assert_legacy_v0_2_0_plugin_stops_check( + plugin_name: &str, + kind: &str, + wasm_file: &str, + found_interface: &str, + expected_interface: &str, +) { + let output = run_check_with_sandbox_probe(plugin_name, Some(kind), wasm_file); + assert!( + output.stdout.is_empty(), + "expected empty stdout before any report is written, got: {}", + String::from_utf8_lossy(&output.stdout) + ); + let stderr = String::from_utf8_lossy(&output.stderr); + let lines: Vec<&str> = stderr.lines().collect(); + assert!( + lines.len() >= 2, + "expected error line and rebuild remedy line, got: {stderr}" + ); + assert!( + lines[0].contains(plugin_name) + && lines[0].contains(found_interface) + && lines[0].contains("0.2.0") + && lines[0].contains(expected_interface) + && lines[0].contains("0.3.0"), + "expected stderr line 1 to name plugin and both versions, got: {}", + lines[0] + ); + assert!( + lines[1].to_ascii_lowercase().contains("rebuild") && lines[1].contains("0.3.0"), + "expected stderr line 2 to instruct rebuilding against 0.3.0, got: {}", + lines[1] + ); +} + +#[test] +fn v0_2_0_language_plugin_stops_check_with_exit_2_and_rebuild_remedy() { + assert_legacy_v0_2_0_plugin_stops_check( + "legacy-v02-lang", + "language", + "legacy_v0_2_0_language_plugin.wasm", + "codeint:plugin/language@0.2.0", + "codeint:plugin/language@0.3.0", + ); +} + +#[test] +fn v0_2_0_metric_plugin_stops_check_with_exit_2_and_rebuild_remedy() { + assert_legacy_v0_2_0_plugin_stops_check( + "legacy-v02-metric", + "metric", + "legacy_v0_2_0_metric_plugin.wasm", + "codeint:plugin/metric@0.2.0", + "codeint:plugin/metric@0.3.0", + ); +} + +fn assert_exact_language_findings(findings: &[Value], expected: &[(&str, &str)]) { + let language_findings: Vec<&Value> = findings + .iter() + .filter(|finding| { + finding["path"] + .as_str() + .is_some_and(|path| path.starts_with("languages/")) + }) + .collect(); + assert_eq!( + language_findings.len(), + expected.len(), + "expected only measured languages in model.languages, got: {language_findings:?}" + ); + for (path, message) in expected { + assert!( + language_findings + .iter() + .any(|finding| finding["path"] == *path && finding["message"] == *message), + "expected ({path}, {message}) in {language_findings:?}" + ); + } +} + +#[test] +fn coverage_reader_metric_plugin_receives_per_language_coverage_statement_from_check() { + let (repo, _hash) = init_single_probe_repo( + "coverage-reader", + Some("metric"), + "coverage_reader_metric_plugin.wasm", + "", + ); + write_file( + repo.path(), + "src/app.ts", + "export function greet(name: string): string { return name; }\n", + ); + + let report = run_check_json_report(repo.path()); + let findings = report["source_sets"]["production"]["coverage_reader"]["findings"] + .as_array() + .expect("coverage_reader findings list"); + assert_exact_language_findings( + findings, + &[( + "languages/typescript-javascript", + "language=typescript-javascript has_coverage=false", + )], + ); +} + +fn init_program_start_repo() -> (TempDir, String) { + let (repo, hash) = init_single_probe_repo( + "program-start", + None, + "program_start_language_plugin.wasm", + "", + ); + write_file( + repo.path(), + "cmd/app/main.prog", + "program main\nuse internal/util/live.prog\n", + ); + write_file(repo.path(), "internal/util/live.prog", "library live\n"); + (repo, hash) +} + +fn run_trace(dir: &Path, from: &str, to: &str, format: &str) -> String { + let output = run_codeint(dir, &["trace", from, to, "--format", format]); + assert_eq!( + output.status.code(), + Some(0), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).expect("utf8") +} + +#[test] +fn marked_production_file_is_an_entry_point_for_orphan_files_alongside_globs_while_marked_tests_stay_out() + { + let (repo, hash) = init_program_start_repo(); + write_file(repo.path(), "internal/util/orphan.prog", "library orphan\n"); + write_file( + repo.path(), + "internal/util/test_only.prog", + "library test_only\n", + ); + write_file( + repo.path(), + "cmd/app/main.test.prog", + "program main\nuse internal/util/test_only.prog\n", + ); + write_file(repo.path(), "cmd/app/extra_test.prog", "program main\n"); + write_file(repo.path(), "dist/gen.prog", "program main\n"); + write_file(repo.path(), "vendor/third.prog", "program main\n"); + + let report = run_check_json_report(repo.path()); + let orphan = &report["source_sets"]["production"]["orphan_files"]; + assert_eq!(orphan["entry_points"], 1, "report: {report}"); + assert_eq!(orphan["evaluated_files"], 4, "report: {report}"); + assert_eq!(orphan["orphan_files"], 2, "report: {report}"); + assert_eq!(orphan["unreferenced"], 1, "report: {report}"); + assert_eq!(orphan["test_only"], 1, "report: {report}"); + let findings = orphan["findings"].as_array().expect("orphan findings"); + assert_eq!(findings.len(), 2); + assert_eq!(findings[0]["path"], "internal/util/orphan.prog"); + assert_eq!(findings[0]["kind"], "unreferenced"); + assert_eq!(findings[1]["path"], "internal/util/test_only.prog"); + assert_eq!(findings[1]["kind"], "test-only"); + assert_eq!( + findings[1]["test_importers"], + serde_json::json!(["cmd/app/main.test.prog"]) + ); + + write_file( + repo.path(), + "internal/util/extra_entry.prog", + "library extra_entry\nuse ./via_glob.prog\n", + ); + write_file( + repo.path(), + "internal/util/via_glob.prog", + "library via_glob\n", + ); + write_plugin_config( + repo.path(), + "program-start", + None, + "plugins/program_start_language_plugin.wasm", + &hash, + r#""entry_points": ["internal/util/extra_entry.prog"]"#, + ); + + let glob_report = run_check_json_report(repo.path()); + let glob_orphan = &glob_report["source_sets"]["production"]["orphan_files"]; + assert_eq!(glob_orphan["entry_points"], 2, "report: {glob_report}"); + assert_eq!(glob_orphan["evaluated_files"], 6, "report: {glob_report}"); + assert_eq!(glob_orphan["orphan_files"], 2, "report: {glob_report}"); + let glob_paths: Vec<&str> = glob_orphan["findings"] + .as_array() + .expect("orphan findings") + .iter() + .map(|item| item["path"].as_str().expect("path")) + .collect(); + assert_eq!( + glob_paths, + vec!["internal/util/orphan.prog", "internal/util/test_only.prog"] + ); +} + +#[test] +fn trace_names_program_start_mark_for_marked_production_file_and_omits_it_for_test_files() { + let (repo, _hash) = init_program_start_repo(); + write_file( + repo.path(), + "cmd/app/main.test.prog", + "program main\nuse internal/util/live.prog\n", + ); + + let traced: Value = serde_json::from_str(&run_trace( + repo.path(), + "cmd/app/main.prog", + "internal/util/live.prog", + "json", + )) + .expect("valid trace JSON"); + assert_eq!(traced["from"], "cmd/app/main.prog"); + assert_eq!(traced["to"], "internal/util/live.prog"); + assert_eq!(traced["from_entry_point"], "program-start mark"); + assert!(traced.get("to_entry_point").is_none()); + assert_eq!(traced["connected"], true); + assert_eq!( + traced["paths"], + serde_json::json!([["cmd/app/main.prog", "internal/util/live.prog"]]) + ); + + let text = run_trace( + repo.path(), + "cmd/app/main.prog", + "internal/util/live.prog", + "text", + ); + assert_eq!( + text.trim(), + "Entry point: cmd/app/main.prog (program-start mark)\ncmd/app/main.prog -> internal/util/live.prog" + ); + + let toon = run_trace( + repo.path(), + "cmd/app/main.prog", + "internal/util/live.prog", + "toon", + ); + assert!( + toon.contains("from_entry_point: program-start mark"), + "toon: {toon}" + ); + assert!(!toon.contains("to_entry_point:"), "toon: {toon}"); + + let reverse: Value = serde_json::from_str(&run_trace( + repo.path(), + "internal/util/live.prog", + "cmd/app/main.prog", + "json", + )) + .expect("valid reverse trace JSON"); + assert!(reverse.get("from_entry_point").is_none()); + assert_eq!(reverse["to_entry_point"], "program-start mark"); + assert_eq!(reverse["connected"], false); + + let reverse_text = run_trace( + repo.path(), + "internal/util/live.prog", + "cmd/app/main.prog", + "text", + ); + assert_eq!( + reverse_text.trim(), + "Entry point: cmd/app/main.prog (program-start mark)\nNo runtime import path from internal/util/live.prog to cmd/app/main.prog" + ); + + let test_file_trace: Value = serde_json::from_str(&run_trace( + repo.path(), + "cmd/app/main.test.prog", + "internal/util/live.prog", + "json", + )) + .expect("valid test trace JSON"); + assert!(test_file_trace.get("from_entry_point").is_none()); + assert!(test_file_trace.get("to_entry_point").is_none()); + + let test_file_text = run_trace( + repo.path(), + "cmd/app/main.test.prog", + "internal/util/live.prog", + "text", + ); + assert_eq!( + test_file_text.trim(), + "cmd/app/main.test.prog -> internal/util/live.prog" + ); + + write_file( + repo.path(), + "scripts/main.prog", + "program main\nuse internal/util/live.prog\n", + ); + let tooling_trace: Value = serde_json::from_str(&run_trace( + repo.path(), + "scripts/main.prog", + "internal/util/live.prog", + "json", + )) + .expect("valid tooling trace JSON"); + assert!(tooling_trace.get("from_entry_point").is_none()); + assert!(tooling_trace.get("to_entry_point").is_none()); + + let (pkg_repo, _hash) = init_single_probe_repo( + "folder-import-lang", + None, + "folder_import_language_plugin.wasm", + "", + ); + write_file(pkg_repo.path(), "fld.workspace", "packages/app\n"); + write_file( + pkg_repo.path(), + "packages/app/src/main.fld", + "program main\nfn main()\n", + ); + write_file( + pkg_repo.path(), + "packages/app/scripts/tool.fld", + "program main\nfn tool()\n", + ); + let pkg_trace_out = run_codeint( + pkg_repo.path(), + &[ + "trace", + "--package", + "packages/app", + "packages/app/scripts/tool.fld", + "packages/app/scripts/tool.fld", + "--format", + "json", + ], + ); + assert_eq!( + pkg_trace_out.status.code(), + Some(0), + "stderr: {}", + String::from_utf8_lossy(&pkg_trace_out.stderr) + ); + let pkg_trace: Value = serde_json::from_slice(&pkg_trace_out.stdout).expect("pkg trace json"); + assert!(pkg_trace.get("from_entry_point").is_none()); + assert!(pkg_trace.get("to_entry_point").is_none()); +} + +fn init_paired_language_and_metric_repo( + language_name: &str, + language_wasm: &str, + metric_name: &str, + metric_wasm: &str, +) -> TempDir { + let repo = init_repo(); + let lang_rel = format!("plugins/{language_wasm}"); + let metric_rel = format!("plugins/{metric_wasm}"); + let lang_hash = copy_wasm_into(&built_sandbox_probe(language_wasm), repo.path(), &lang_rel); + let metric_hash = copy_wasm_into(&built_sandbox_probe(metric_wasm), repo.path(), &metric_rel); + write_file( + repo.path(), + "codeint.json", + &format!( + r#"{{ + "plugins": [ + {{ + "name": "{language_name}", + "kind": "language", + "path": "{lang_rel}", + "sha256": "{lang_hash}" + }}, + {{ + "name": "{metric_name}", + "kind": "metric", + "path": "{metric_rel}", + "sha256": "{metric_hash}" + }} + ] + }}"# + ), + ); + repo +} + +fn init_hazard_rules_repo_with_metric() -> TempDir { + init_paired_language_and_metric_repo( + "hazard-lang", + "hazard_rules_language_plugin.wasm", + "hazard-facts", + "hazard_facts_metric_plugin.wasm", + ) +} + +fn run_check_json_report(repo: &Path) -> Value { + let output = run_codeint(repo, &["check", "--format", "json"]); + assert_eq!( + output.status.code(), + Some(0), + "expected exit 0, got {:?}\nstderr: {}", + output.status.code(), + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).expect("parse json report") +} + +fn run_paired_language_and_metric_probe_check( + language_name: &str, + language_wasm: &str, + metric_name: &str, + metric_wasm: &str, + extra_file: (&str, &str), +) -> Value { + let repo = init_paired_language_and_metric_repo( + language_name, + language_wasm, + metric_name, + metric_wasm, + ); + write_file( + repo.path(), + "src/app.ts", + "export function greet(name: string): string { return name; }\n", + ); + write_file(repo.path(), extra_file.0, extra_file.1); + run_check_json_report(repo.path()) +} + +fn run_check_hazard_facts_findings(repo: &Path) -> Vec { + let report = run_check_json_report(repo); + report["source_sets"]["production"]["hazard_facts"]["findings"] + .as_array() + .expect("hazard_facts findings list") + .clone() +} + +fn assert_exit_2_without_stdout(repo: &Path, args: &[&str], expected_substrings: &[&str]) { + let output = run_codeint(repo, args); + assert_eq!( + output.status.code(), + Some(2), + "args {args:?}: expected exit 2, got {:?}\nstderr: {}", + output.status.code(), + String::from_utf8_lossy(&output.stderr) + ); + assert!( + output.stdout.is_empty(), + "args {args:?}: expected no report on stdout, got: {}", + String::from_utf8_lossy(&output.stdout) + ); + let stderr = String::from_utf8_lossy(&output.stderr); + for expected in expected_substrings { + assert!( + stderr.contains(expected), + "args {args:?}: expected {expected:?} in stderr, got: {stderr}" + ); + } +} + +#[test] +fn hazard_facts_metric_plugin_reads_per_language_hazard_rules_from_check() { + let repo = init_hazard_rules_repo_with_metric(); + write_file( + repo.path(), + "src/app.ts", + "export function greet(name: string): string { return name; }\n", + ); + write_file(repo.path(), "queries/clean.haz", "SELECT id FROM users;\n"); + + let findings = run_check_hazard_facts_findings(repo.path()); + assert_exact_language_findings( + &findings, + &[ + ( + "languages/hazard-lang", + "language=hazard-lang has_hazard_rules=true", + ), + ( + "languages/typescript-javascript", + "language=typescript-javascript has_hazard_rules=false", + ), + ], + ); +} + +#[test] +fn empty_resolved_import_list_stops_check_with_exit_2_naming_plugin() { + let (repo, _hash) = init_single_probe_repo( + "folder-import-lang", + None, + "folder_import_language_plugin.wasm", + "", + ); + write_file(repo.path(), "src/app.fld", "use empty\nfn main()\n"); + assert_exit_2_without_stdout( + repo.path(), + &["check", "--format", "json"], + &["folder-import-lang", "empty list"], + ); +} + +#[test] +fn hazard_line_beyond_end_of_file_stops_check_with_exit_2_naming_plugin_file_and_line() { + let (repo, _hash) = init_single_probe_repo( + "hazard-lang", + Some("language"), + "hazard_rules_language_plugin.wasm", + "", + ); + write_file( + repo.path(), + "queries/beyond.haz", + "SELECT 1;\nHAZARD_BEYOND_EOF\nSELECT 2;\n", + ); + commit_all(repo.path(), "commit file with out-of-range hazard line"); + + for args in [&["check", "--format", "json"][..], &["diff", "HEAD"][..]] { + assert_exit_2_without_stdout( + repo.path(), + args, + &["hazard-lang", "queries/beyond.haz", "line 4"], + ); + } + + write_file( + repo.path(), + "queries/beyond.haz", + "SELECT 1;\nHAZARD_LINE_ZERO\n", + ); + assert_exit_2_without_stdout( + repo.path(), + &["check", "--format", "json"], + &["hazard-lang", "queries/beyond.haz", "line 0"], + ); +} + +#[test] +fn hazard_line_on_last_line_of_file_is_accepted_with_and_without_trailing_newline() { + let repo = init_hazard_rules_repo_with_metric(); + write_file( + repo.path(), + "queries/with_newline.haz", + "SELECT id FROM users;\nDELETE FROM sessions;\n", + ); + write_file( + repo.path(), + "queries/without_newline.haz", + "SELECT id FROM users;\nDELETE FROM sessions;", + ); + + let findings = run_check_hazard_facts_findings(repo.path()); + for expected_path in ["queries/with_newline.haz", "queries/without_newline.haz"] { + let expected_id = format!("hazard:{expected_path}:2:delete-without-where"); + assert!( + findings.iter().any(|finding| { + finding["path"] == expected_path + && finding["line"] == 2 + && finding["id"] == expected_id + }), + "expected last-line hazard for {expected_path}, got: {findings:?}" + ); + } +} + +fn init_unlisted_hazard_probe_repo(source: &str) -> TempDir { + let (repo, _hash) = init_single_probe_repo( + "unlisted-hazard-lang", + None, + "unlisted_hazard_rule_language_plugin.wasm", + "", + ); + write_file(repo.path(), "src/query.uhr", source); + repo +} + +#[test] +fn unlisted_hazard_line_rule_stops_check_with_exit_2_naming_plugin_file_and_rule() { + let repo = init_unlisted_hazard_probe_repo("SELECT 1;\nUNLISTED_HAZARD\n"); + assert_exit_2_without_stdout( + repo.path(), + &["check", "--format", "json"], + &[ + "unlisted-hazard-lang", + "src/query.uhr", + "unlisted-secret-rule", + ], + ); +} + +#[test] +fn listed_hazard_line_rule_is_accepted_by_check() { + let repo = init_unlisted_hazard_probe_repo("SELECT 1;\nALLOWED_HAZARD\n"); + let report = run_check_json_report(repo.path()); + assert_eq!(report["files"], 1); +} + +#[test] +fn no_imports_language_plugin_check_skips_import_calls_and_metric_reads_has_imports() { + let report = run_paired_language_and_metric_probe_check( + "no-imports-lang", + "no_imports_language_plugin.wasm", + "import-capability", + "import_capability_metric_plugin.wasm", + ("queries/users.noimp", "fn select_users()\n"), + ); + let findings = report["source_sets"]["production"]["import_capability"]["findings"] + .as_array() + .expect("import_capability findings list"); + assert_exact_language_findings( + findings, + &[ + ( + "languages/no-imports-lang", + "language=no-imports-lang has_imports=false", + ), + ( + "languages/typescript-javascript", + "language=typescript-javascript has_imports=true", + ), + ], + ); +} + +#[test] +fn no_imports_only_repo_omits_import_cycles_and_dependencies_across_check_diff_and_trend() { + let (repo, _hash) = init_single_probe_repo( + "no-imports-lang", + None, + "no_imports_language_plugin.wasm", + r#""budgets": { "unused_dependencies": 0.0 }"#, + ); + write_file( + repo.path(), + "package.json", + r#"{"name":"docs-site","dependencies":{"left-pad":"^1.0.0"}}"#, + ); + write_file(repo.path(), "queries/users.noimp", "fn select_users()\n"); + commit_all(repo.path(), "initial no-imports commit"); + write_file(repo.path(), "queries/orders.noimp", "fn select_orders()\n"); + + let check = run_check_json_report(repo.path()); + assert!( + check["source_sets"]["production"] + .get("import_cycles") + .is_none() + ); + assert!(check.get("dependencies").is_none()); + + let diff_out = run_codeint(repo.path(), &["diff", "HEAD", "--format", "json"]); + assert_eq!( + diff_out.status.code(), + Some(0), + "diff stderr: {}", + String::from_utf8_lossy(&diff_out.stderr) + ); + let diff: Value = serde_json::from_slice(&diff_out.stdout).expect("parse diff json"); + assert!( + diff["source_sets"]["production"] + .get("import_cycles") + .is_none() + ); + assert!(diff.get("dependencies").is_none()); + + let trend_out = run_codeint(repo.path(), &["trend", "--format", "json"]); + assert_eq!( + trend_out.status.code(), + Some(0), + "trend stderr: {}", + String::from_utf8_lossy(&trend_out.stderr) + ); + let trend: Value = serde_json::from_slice(&trend_out.stdout).expect("parse trend json"); + assert!( + trend["source_sets"]["production"][0] + .get("import_cycles") + .is_none() + ); +} diff --git a/crates/metrics/src/boundaries.rs b/crates/metrics/src/boundaries.rs index 0188a423..553d49af 100644 --- a/crates/metrics/src/boundaries.rs +++ b/crates/metrics/src/boundaries.rs @@ -1,8 +1,13 @@ +use std::collections::HashSet; + use codeint_model::{CodeModel, ImportResolution, RepoPath, token_text_hash}; use crate::FindingId; use crate::finding_id::FindingIds; +#[cfg(test)] +mod tests; + const BOUNDARIES_METRIC_KEY: &str = "boundaries"; #[derive(Clone, Debug, PartialEq, Eq)] @@ -108,17 +113,23 @@ fn evaluate_imports( let mut resolved_imports = 0usize; let mut pending = Vec::new(); for runtime_import in &model.runtime_imports { - let ImportResolution::Resolved(target) = &runtime_import.resolution else { + let ImportResolution::Resolved(targets) = &runtime_import.resolution else { continue; }; - resolved_imports += 1; - if let Some(finding) = check_import_edge( - &runtime_import.importer, - target, - &runtime_import.specifier, - policy, - ) { - pending.push(finding); + let mut seen_targets = HashSet::with_capacity(targets.len()); + for target in targets { + if !seen_targets.insert(target) { + continue; + } + resolved_imports += 1; + if let Some(finding) = check_import_edge( + &runtime_import.importer, + target, + &runtime_import.specifier, + policy, + ) { + pending.push(finding); + } } } (resolved_imports, pending) diff --git a/crates/metrics/src/boundaries/tests.rs b/crates/metrics/src/boundaries/tests.rs new file mode 100644 index 00000000..fc2e15be --- /dev/null +++ b/crates/metrics/src/boundaries/tests.rs @@ -0,0 +1,225 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use codeint_model::{CodeModel, ImportResolution, RepoPath, RuntimeImport, SourceFile, SourceSet}; + +use super::{Boundaries, BoundaryEdgeCheck, BoundaryFindingKind, BoundaryPolicy}; +use crate::test_support::{empty_source_file, repo_path as path}; + +fn production_file(name: &str) -> SourceFile { + empty_source_file(name, SourceSet::Production, 1) +} + +struct StubPolicy { + zones: BTreeMap, + public_files: BTreeMap>, + decisions: BTreeMap<(String, String), BoundaryEdgeCheck>, +} + +impl StubPolicy { + fn new(zones: &[(&str, &str)]) -> StubPolicy { + StubPolicy { + zones: zones + .iter() + .map(|&(file, zone)| (file.to_owned(), zone.to_owned())) + .collect(), + public_files: BTreeMap::new(), + decisions: BTreeMap::new(), + } + } + + fn with_decision( + mut self, + source_zone: &str, + target_zone: &str, + decision: BoundaryEdgeCheck, + ) -> StubPolicy { + self.decisions + .insert((source_zone.to_owned(), target_zone.to_owned()), decision); + self + } + + fn with_public_files(mut self, zone: &str, files: &[&str]) -> StubPolicy { + self.public_files.insert( + zone.to_owned(), + files.iter().map(|file| (*file).to_owned()).collect(), + ); + self + } +} + +impl BoundaryPolicy for StubPolicy { + fn zone_of(&self, target: &RepoPath) -> Option<&str> { + self.zones.get(target.as_str()).map(String::as_str) + } + + fn has_public_files(&self, zone: &str) -> bool { + self.public_files.contains_key(zone) + } + + fn is_public_file(&self, zone: &str, target: &RepoPath) -> bool { + self.public_files + .get(zone) + .is_none_or(|allowed| allowed.contains(target.as_str())) + } + + fn check_import(&self, source_zone: &str, target_zone: &str) -> BoundaryEdgeCheck { + self.decisions + .get(&(source_zone.to_owned(), target_zone.to_owned())) + .cloned() + .unwrap_or(BoundaryEdgeCheck::Allowed) + } + + fn strict_zones(&self) -> bool { + false + } +} + +fn model_with_multi_target_import( + files: &[&str], + importer: &str, + specifier: &str, + targets: &[&str], +) -> CodeModel { + CodeModel { + files: files.iter().copied().map(production_file).collect(), + runtime_imports: vec![RuntimeImport { + importer: path(importer), + specifier: specifier.to_owned(), + resolution: ImportResolution::Resolved(targets.iter().copied().map(path).collect()), + }], + ..CodeModel::default() + } +} + +#[test] +fn multi_file_import_flags_only_targets_on_the_forbidden_side() { + let model = model_with_multi_target_import( + &["ui/page.fld", "shared/public.fld", "shared/secret.fld"], + "ui/page.fld", + "shared", + &["shared/public.fld", "shared/secret.fld"], + ); + let policy = StubPolicy::new(&[ + ("ui/page.fld", "ui"), + ("shared/public.fld", "public"), + ("shared/secret.fld", "secret"), + ]) + .with_decision( + "ui", + "secret", + BoundaryEdgeCheck::DeniedByDenyRule { + reason: Some("UI must not depend on secret files".to_owned()), + }, + ); + + let measured = Boundaries::measure(&model, &policy); + + assert_eq!(measured.resolved_imports(), 2); + assert_eq!(measured.ratio(), 0.5); + let findings = measured.findings(); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].kind, BoundaryFindingKind::ZoneRule); + assert_eq!(findings[0].importer, path("ui/page.fld")); + assert_eq!(findings[0].target, Some(path("shared/secret.fld"))); + assert_eq!(findings[0].specifier.as_deref(), Some("shared")); + assert_eq!(findings[0].source_zone.as_deref(), Some("ui")); + assert_eq!(findings[0].target_zone.as_deref(), Some("secret")); + assert_eq!( + findings[0].reason.as_deref(), + Some("UI must not depend on secret files") + ); +} + +#[test] +fn multi_file_import_with_public_files_flags_only_non_public_targets() { + let model = model_with_multi_target_import( + &["ui/page.fld", "shared/public.fld", "shared/secret.fld"], + "ui/page.fld", + "shared", + &["shared/public.fld", "shared/secret.fld"], + ); + let policy = StubPolicy::new(&[ + ("ui/page.fld", "ui"), + ("shared/public.fld", "shared"), + ("shared/secret.fld", "shared"), + ]) + .with_public_files("shared", &["shared/public.fld"]); + + let measured = Boundaries::measure(&model, &policy); + + assert_eq!(measured.resolved_imports(), 2); + let findings = measured.findings(); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].kind, BoundaryFindingKind::PublicFiles); + assert_eq!(findings[0].importer, path("ui/page.fld")); + assert_eq!(findings[0].target, Some(path("shared/secret.fld"))); + assert_eq!(findings[0].specifier.as_deref(), Some("shared")); + assert_eq!(findings[0].source_zone.as_deref(), Some("ui")); + assert_eq!(findings[0].target_zone.as_deref(), Some("shared")); +} + +#[test] +fn multi_file_import_to_multiple_forbidden_targets_emits_distinct_stable_findings() { + let policy = StubPolicy::new(&[ + ("ui/page.fld", "ui"), + ("secret/a.fld", "secret"), + ("secret/b.fld", "secret"), + ]) + .with_decision( + "ui", + "secret", + BoundaryEdgeCheck::DeniedByAllowRule { + reason: Some("UI may import public modules only".to_owned()), + }, + ); + let reversed = model_with_multi_target_import( + &["ui/page.fld", "secret/a.fld", "secret/b.fld"], + "ui/page.fld", + "secret", + &["secret/b.fld", "secret/a.fld"], + ); + let ordered = model_with_multi_target_import( + &["ui/page.fld", "secret/a.fld", "secret/b.fld"], + "ui/page.fld", + "secret", + &["secret/a.fld", "secret/b.fld"], + ); + + let from_reversed = Boundaries::measure(&reversed, &policy); + let from_ordered = Boundaries::measure(&ordered, &policy); + + assert_eq!(from_reversed.resolved_imports(), 2); + assert_eq!(from_reversed.ratio(), 1.0); + assert_eq!(from_reversed.findings(), from_ordered.findings()); + let findings = from_reversed.findings(); + assert_eq!(findings.len(), 2); + assert_eq!(findings[0].importer, path("ui/page.fld")); + assert_eq!(findings[0].target, Some(path("secret/a.fld"))); + assert_eq!(findings[1].importer, path("ui/page.fld")); + assert_eq!(findings[1].target, Some(path("secret/b.fld"))); + assert_ne!(findings[0].id, findings[1].id); +} + +#[test] +fn duplicate_targets_in_a_single_resolved_import_are_counted_once() { + let policy = StubPolicy::new(&[("ui/page.fld", "ui"), ("secret/a.fld", "secret")]) + .with_decision( + "ui", + "secret", + BoundaryEdgeCheck::DeniedByDenyRule { + reason: Some("no direct secret import".to_owned()), + }, + ); + let model = model_with_multi_target_import( + &["ui/page.fld", "secret/a.fld"], + "ui/page.fld", + "secret", + &["secret/a.fld", "secret/a.fld"], + ); + + let measured = Boundaries::measure(&model, &policy); + + assert_eq!(measured.resolved_imports(), 1); + assert_eq!(measured.findings().len(), 1); + assert_eq!(measured.findings()[0].target, Some(path("secret/a.fld"))); +} diff --git a/crates/metrics/src/cognitive_complexity/tests.rs b/crates/metrics/src/cognitive_complexity/tests.rs index 3ba24fec..853bff2f 100644 --- a/crates/metrics/src/cognitive_complexity/tests.rs +++ b/crates/metrics/src/cognitive_complexity/tests.rs @@ -12,7 +12,9 @@ fn file(path: &str, functions: Vec, tokens: Vec) -> SourceFile functions, tokens, flagged_lines: Vec::new(), + hazard_lines: Vec::new(), runtime_imports: Vec::new(), + program_start: false, }, } } @@ -38,6 +40,7 @@ fn flags_only_functions_over_15_and_sorts_worst_first() { source_lines: 10, name: Some("flatAtThreshold".to_owned()), cognitive_complexity: 15, + coverage: None, }, Function { line: 12, @@ -46,6 +49,7 @@ fn flags_only_functions_over_15_and_sorts_worst_first() { source_lines: 12, name: Some("nestedModerate".to_owned()), cognitive_complexity: 16, + coverage: None, }, Function { line: 27, @@ -54,6 +58,7 @@ fn flags_only_functions_over_15_and_sorts_worst_first() { source_lines: 14, name: None, cognitive_complexity: 24, + coverage: None, }, ], vec![token(1, 10), token(12, 20), token(27, 30)], @@ -93,6 +98,7 @@ fn finding_id_stays_stable_when_function_moves_lines_and_by_package_sums_to_tota source_lines: 10, name: Some("deep".to_owned()), cognitive_complexity: 20, + coverage: None, }], vec![token(2, 111), token(3, 222)], ), @@ -105,6 +111,7 @@ fn finding_id_stays_stable_when_function_moves_lines_and_by_package_sums_to_tota source_lines: 5, name: Some("simple".to_owned()), cognitive_complexity: 5, + coverage: None, }], vec![token(1, 333)], ), @@ -122,6 +129,7 @@ fn finding_id_stays_stable_when_function_moves_lines_and_by_package_sums_to_tota source_lines: 10, name: Some("deep".to_owned()), cognitive_complexity: 20, + coverage: None, }], vec![token(21, 111), token(22, 222)], )], diff --git a/crates/metrics/src/dependencies/tests.rs b/crates/metrics/src/dependencies/tests.rs index fbf3ec54..6e4fd74a 100644 --- a/crates/metrics/src/dependencies/tests.rs +++ b/crates/metrics/src/dependencies/tests.rs @@ -1,24 +1,15 @@ use std::collections::BTreeSet; use codeint_model::{ - CodeModel, DeclaredDep, DepKind, DependencyManifest, FileModel, ImportResolution, - ManifestUsedDep, RepoPath, RuntimeImport, SourceFile, SourceSet, Workspace, + CodeModel, DeclaredDep, DepKind, DependencyManifest, ImportResolution, ManifestUsedDep, + RepoPath, RuntimeImport, SourceFile, SourceSet, Workspace, }; use super::{DependencyHygiene, UnusedDependencyKind}; +use crate::test_support::empty_source_file; fn source_file(path: &str, source_set: SourceSet) -> SourceFile { - SourceFile { - path: RepoPath::new(path).expect("valid path"), - model: FileModel { - source_set, - source_lines: 10, - functions: Vec::new(), - tokens: Vec::new(), - flagged_lines: Vec::new(), - runtime_imports: Vec::new(), - }, - } + empty_source_file(path, source_set, 10) } fn manifest(package_root: &str, path: &str) -> DependencyManifest { @@ -105,7 +96,7 @@ fn detects_unused_unlisted_and_dev_in_production_while_ignoring_builtins_and_res import_with( "src/app.ts", "./helper", - ImportResolution::Resolved(RepoPath::new("src/helper.ts").unwrap()), + ImportResolution::Resolved(vec![RepoPath::new("src/helper.ts").unwrap()]), ), import_with( "src/app.ts", diff --git a/crates/metrics/src/duplication/tests.rs b/crates/metrics/src/duplication/tests.rs index 5a985575..095a1590 100644 --- a/crates/metrics/src/duplication/tests.rs +++ b/crates/metrics/src/duplication/tests.rs @@ -29,7 +29,9 @@ fn file(path: &str, lines: &[&str]) -> SourceFile { functions: Vec::new(), tokens, flagged_lines: Vec::new(), + hazard_lines: Vec::new(), runtime_imports: Vec::new(), + program_start: false, }, } } @@ -469,6 +471,7 @@ fn whole_function(line_count: usize) -> Vec { source_lines: u32::try_from(line_count).expect("few lines"), name: None, cognitive_complexity: 0, + coverage: None, }] } @@ -639,6 +642,7 @@ fn three_near_clones_cluster_into_one_clone_family_with_stable_id_across_line_sh source_lines: u32::try_from(second.len()).expect("few lines"), name: None, cognitive_complexity: 0, + coverage: None, }]; let shifted_run = Duplication::measure_with_near_clones( &model(vec![ diff --git a/crates/metrics/src/erosion/tests.rs b/crates/metrics/src/erosion/tests.rs index 325c5a9e..b0f3dc08 100644 --- a/crates/metrics/src/erosion/tests.rs +++ b/crates/metrics/src/erosion/tests.rs @@ -18,7 +18,9 @@ fn model_with(functions: Vec) -> CodeModel { line: 1, }], flagged_lines: Vec::new(), + hazard_lines: Vec::new(), runtime_imports: Vec::new(), + program_start: false, }, }], workspace: Workspace::default(), @@ -36,6 +38,7 @@ fn eroded_functions_preserve_name_line_range_and_cognitive_complexity() { source_lines: 18, name: Some("routeRequest".to_owned()), cognitive_complexity: 22, + coverage: None, }, Function { line: 22, @@ -44,6 +47,7 @@ fn eroded_functions_preserve_name_line_range_and_cognitive_complexity() { source_lines: 14, name: None, cognitive_complexity: 16, + coverage: None, }, ]); diff --git a/crates/metrics/src/impact.rs b/crates/metrics/src/impact.rs index b3d290e2..45d88348 100644 --- a/crates/metrics/src/impact.rs +++ b/crates/metrics/src/impact.rs @@ -57,93 +57,30 @@ impl ImpactAnalysis { .enumerate() .map(|(index, file)| (&file.path, index)) .collect(); - - let mut unique_target_indices: BTreeSet = BTreeSet::new(); - for target in targets { - let Some(&index) = index_of.get(target) else { - return Err(ImpactError::TargetNotInCodeModel { - path: target.clone(), - }); - }; - unique_target_indices.insert(index); - } - - let mut forward: Vec> = vec![BTreeSet::new(); model.files.len()]; - let mut reverse: Vec> = vec![BTreeSet::new(); model.files.len()]; - for runtime_import in &model.runtime_imports { - if let ImportResolution::Resolved(target) = &runtime_import.resolution - && let (Some(&from), Some(&to)) = - (index_of.get(&runtime_import.importer), index_of.get(target)) - && from != to - { - forward[from].insert(to); - reverse[to].insert(from); - } - } - + let unique_target_indices = resolve_target_indices(targets, &index_of)?; + let (forward, reverse) = build_import_graphs(model, &index_of); let has_workspace_members = model.workspace.has_members(); - let package_name = |path: &RepoPath| -> Option { - has_workspace_members.then(|| model.workspace.package_of(path).to_string()) - }; - - let mut target_rows: Vec = unique_target_indices - .iter() - .map(|&index| { - let file = &model.files[index]; - ImpactTarget { - path: file.path.clone(), - source_set: file.model.source_set, - package: package_name(&file.path), - fan_in: reverse[index].len(), - fan_out: forward[index].len(), - transitive_import_weight: reverse_reachable_count(&reverse, index, max_depth), - } - }) - .collect(); - target_rows.sort_by(|left, right| left.path.cmp(&right.path)); - + let target_rows = build_target_rows( + model, + &unique_target_indices, + &forward, + &reverse, + max_depth, + has_workspace_members, + ); let distances = multi_source_reverse_bfs(&reverse, &unique_target_indices, max_depth); - let mut dependents: Vec = distances - .into_iter() - .enumerate() - .filter_map(|(index, distance)| { - let distance = distance?; - if distance == 0 { - return None; - } - let file = &model.files[index]; - Some(ImpactDependent { - path: file.path.clone(), - distance, - source_set: file.model.source_set, - package: package_name(&file.path), - }) - }) - .collect(); - dependents.sort_by(|left, right| { - left.distance - .cmp(&right.distance) - .then_with(|| left.path.cmp(&right.path)) - }); - + let dependents = collect_dependents(model, distances, has_workspace_members); let direct_dependents = dependents.iter().filter(|dep| dep.distance == 1).count(); - let transitive_dependents = dependents.len() - direct_dependents; let total_dependents = dependents.len(); - + let transitive_dependents = total_dependents - direct_dependents; let fan_out = unique_target_indices .iter() .flat_map(|&index| forward[index].iter().copied()) .filter(|target_import| !unique_target_indices.contains(target_import)) .collect::>() .len(); - - let affected_packages: Vec = if has_workspace_members { - dependents - .iter() - .filter_map(|dep| dep.package.clone()) - .collect::>() - .into_iter() - .collect() + let affected_packages = if has_workspace_members { + collect_affected_packages(&dependents) } else { Vec::new() }; @@ -179,17 +116,125 @@ impl ImpactAnalysis { self.summary.total_dependents = total_dependents; self.summary.fan_in = direct_dependents; self.summary.transitive_import_weight = total_dependents; - self.affected_packages = self - .dependents - .iter() - .filter_map(|dep| dep.package.clone()) - .collect::>() - .into_iter() - .collect(); + self.affected_packages = collect_affected_packages(&self.dependents); self } } +fn resolve_target_indices( + targets: &[RepoPath], + index_of: &HashMap<&RepoPath, usize>, +) -> Result, ImpactError> { + let mut unique_target_indices = BTreeSet::new(); + for target in targets { + let Some(&index) = index_of.get(target) else { + return Err(ImpactError::TargetNotInCodeModel { + path: target.clone(), + }); + }; + unique_target_indices.insert(index); + } + Ok(unique_target_indices) +} + +fn build_import_graphs( + model: &CodeModel, + index_of: &HashMap<&RepoPath, usize>, +) -> (Vec>, Vec>) { + let mut forward = vec![BTreeSet::new(); model.files.len()]; + let mut reverse = vec![BTreeSet::new(); model.files.len()]; + for runtime_import in &model.runtime_imports { + let ImportResolution::Resolved(targets) = &runtime_import.resolution else { + continue; + }; + let Some(&from) = index_of.get(&runtime_import.importer) else { + continue; + }; + for target in targets { + if let Some(&to) = index_of.get(target) + && from != to + { + forward[from].insert(to); + reverse[to].insert(from); + } + } + } + (forward, reverse) +} + +fn package_name_for( + model: &CodeModel, + path: &RepoPath, + has_workspace_members: bool, +) -> Option { + has_workspace_members.then(|| model.workspace.package_of(path).to_string()) +} + +fn build_target_rows( + model: &CodeModel, + unique_target_indices: &BTreeSet, + forward: &[BTreeSet], + reverse: &[BTreeSet], + max_depth: Option, + has_workspace_members: bool, +) -> Vec { + let mut target_rows: Vec = unique_target_indices + .iter() + .map(|&index| { + let file = &model.files[index]; + ImpactTarget { + path: file.path.clone(), + source_set: file.model.source_set, + package: package_name_for(model, &file.path, has_workspace_members), + fan_in: reverse[index].len(), + fan_out: forward[index].len(), + transitive_import_weight: reverse_reachable_count(reverse, index, max_depth), + } + }) + .collect(); + target_rows.sort_by(|left, right| left.path.cmp(&right.path)); + target_rows +} + +fn collect_dependents( + model: &CodeModel, + distances: Vec>, + has_workspace_members: bool, +) -> Vec { + let mut dependents: Vec = distances + .into_iter() + .enumerate() + .filter_map(|(index, distance)| { + let distance = distance?; + if distance == 0 { + return None; + } + let file = &model.files[index]; + Some(ImpactDependent { + path: file.path.clone(), + distance, + source_set: file.model.source_set, + package: package_name_for(model, &file.path, has_workspace_members), + }) + }) + .collect(); + dependents.sort_by(|left, right| { + left.distance + .cmp(&right.distance) + .then_with(|| left.path.cmp(&right.path)) + }); + dependents +} + +fn collect_affected_packages(dependents: &[ImpactDependent]) -> Vec { + dependents + .iter() + .filter_map(|dep| dep.package.clone()) + .collect::>() + .into_iter() + .collect() +} + fn reverse_reachable_count( reverse: &[BTreeSet], start: usize, diff --git a/crates/metrics/src/import_cycles.rs b/crates/metrics/src/import_cycles.rs index e3b04d6b..87f255ff 100644 --- a/crates/metrics/src/import_cycles.rs +++ b/crates/metrics/src/import_cycles.rs @@ -62,15 +62,9 @@ impl ImportCycles { .enumerate() .map(|(index, path)| (*path, index)) .collect(); - let mut imports = vec![Vec::new(); modules.len()]; - for runtime_import in &model.runtime_imports { - if let ImportResolution::Resolved(target) = &runtime_import.resolution - && let (Some(&from), Some(&to)) = - (index_of.get(&runtime_import.importer), index_of.get(target)) - { - imports[from].push(to); - } - } + let imports = crate::build_resolved_import_adjacency(model, modules.len(), |path| { + index_of.get(path).copied() + }); let mut cycle_modules: Vec> = strongly_connected_components(&imports) .into_iter() .filter(|component| match component.as_slice() { diff --git a/crates/metrics/src/import_cycles/tests.rs b/crates/metrics/src/import_cycles/tests.rs index 9074fd23..aaf02f9d 100644 --- a/crates/metrics/src/import_cycles/tests.rs +++ b/crates/metrics/src/import_cycles/tests.rs @@ -1,38 +1,23 @@ -use codeint_model::{ - CodeModel, FileModel, ImportResolution, RepoPath, RuntimeImport, SourceFile, SourceSet, -}; +use codeint_model::{CodeModel, ImportResolution, RepoPath, RuntimeImport, SourceFile, SourceSet}; use super::{ImportCycles, UnresolvedImport}; - -fn path(text: &str) -> RepoPath { - RepoPath::new(text).expect("a valid path") -} +use crate::test_support::{empty_source_file, repo_path as path}; fn module(name: &str) -> SourceFile { - SourceFile { - path: path(name), - model: FileModel { - source_set: SourceSet::Production, - source_lines: 1, - functions: Vec::new(), - tokens: Vec::new(), - flagged_lines: Vec::new(), - runtime_imports: Vec::new(), - }, - } + empty_source_file(name, SourceSet::Production, 1) } fn resolved(importer: &str, target: &str) -> RuntimeImport { RuntimeImport { importer: path(importer), specifier: format!("./{target}"), - resolution: ImportResolution::Resolved(path(target)), + resolution: ImportResolution::Resolved(vec![path(target)]), } } fn graph(modules: &[&str], imports: &[(&str, &str)]) -> CodeModel { CodeModel { - files: modules.iter().map(|name| module(name)).collect(), + files: modules.iter().copied().map(module).collect(), runtime_imports: imports .iter() .map(|(importer, target)| resolved(importer, target)) @@ -190,3 +175,105 @@ fn unresolved_imports_are_listed_by_importer_in_source_order_and_others_are_not( ] ); } + +fn resolved_many(importer: &str, specifier: &str, targets: &[&str]) -> RuntimeImport { + RuntimeImport { + importer: path(importer), + specifier: specifier.to_owned(), + resolution: ImportResolution::Resolved(targets.iter().copied().map(path).collect()), + } +} + +#[test] +fn multi_file_resolved_import_cycle_includes_only_participating_modules() { + let model = CodeModel { + files: ["a/a1.fld", "a/a2.fld", "b/b1.fld", "b/b2.fld", "c/c1.fld"] + .into_iter() + .map(module) + .collect(), + runtime_imports: vec![ + resolved_many("a/a1.fld", "b", &["b/b1.fld", "b/b2.fld"]), + resolved_many("b/b1.fld", "c", &["c/c1.fld"]), + resolved_many("b/b2.fld", "a", &["a/a1.fld", "a/a2.fld"]), + ], + ..CodeModel::default() + }; + + let cycles = ImportCycles::measure(&model); + + assert_eq!(cycle_members(&cycles), [["a/a1.fld", "b/b2.fld"]]); + assert_eq!(cycles.modules_in_import_cycles(), 2); + assert_eq!(cycles.modules(), 5); +} + +#[test] +fn duplicate_and_reordered_multi_file_targets_produce_identical_cycles_and_ids() { + let canonical = CodeModel { + files: ["a/a1.fld", "a/a2.fld", "b/b1.fld", "b/b2.fld"] + .into_iter() + .map(module) + .collect(), + runtime_imports: vec![ + resolved_many("a/a1.fld", "b", &["b/b1.fld", "b/b2.fld"]), + resolved_many("b/b2.fld", "a", &["a/a1.fld", "a/a2.fld"]), + ], + ..CodeModel::default() + }; + let duplicated = CodeModel { + files: ["b/b2.fld", "a/a2.fld", "b/b1.fld", "a/a1.fld"] + .into_iter() + .map(module) + .collect(), + runtime_imports: vec![ + resolved_many("b/b2.fld", "a", &["a/a2.fld", "a/a1.fld", "a/a1.fld"]), + resolved_many("a/a1.fld", "b", &["b/b2.fld", "b/b1.fld", "b/b2.fld"]), + resolved_many("a/a1.fld", "b", &["b/b2.fld", "b/b1.fld"]), + ], + ..CodeModel::default() + }; + + let canonical_cycles = ImportCycles::measure(&canonical); + let duplicated_cycles = ImportCycles::measure(&duplicated); + + assert_eq!(duplicated_cycles.cycles(), canonical_cycles.cycles()); + assert_eq!( + cycle_members(&duplicated_cycles), + [["a/a1.fld", "b/b2.fld"]] + ); + assert_eq!(duplicated_cycles.modules_in_import_cycles(), 2); +} + +#[test] +fn acyclic_multi_file_resolved_imports_form_no_import_cycle() { + let model = CodeModel { + files: [ + "app/main.fld", + "left/l1.fld", + "left/l2.fld", + "right/r1.fld", + "right/r2.fld", + "shared/s1.fld", + "shared/s2.fld", + ] + .into_iter() + .map(module) + .collect(), + runtime_imports: vec![ + resolved_many("app/main.fld", "left", &["left/l1.fld", "left/l2.fld"]), + resolved_many("app/main.fld", "right", &["right/r1.fld", "right/r2.fld"]), + resolved_many("left/l1.fld", "shared", &["shared/s1.fld", "shared/s2.fld"]), + resolved_many( + "right/r2.fld", + "shared", + &["shared/s1.fld", "shared/s2.fld"], + ), + ], + ..CodeModel::default() + }; + + let cycles = ImportCycles::measure(&model); + + assert!(cycles.cycles().is_empty()); + assert_eq!(cycles.modules_in_import_cycles(), 0); + assert_eq!(cycles.modules(), 7); +} diff --git a/crates/metrics/src/lib.rs b/crates/metrics/src/lib.rs index fccf55eb..426cbe2f 100644 --- a/crates/metrics/src/lib.rs +++ b/crates/metrics/src/lib.rs @@ -33,5 +33,65 @@ pub use finding_id::FindingId; pub use impact::{ImpactAnalysis, ImpactDependent, ImpactError, ImpactSummary, ImpactTarget}; pub use import_cycles::{ImportCycle, ImportCycles, ModuleShare, UnresolvedImport}; pub use line_share::LineShare; -pub use trace::{DEFAULT_MAX_TRACE_PATHS, TraceError, TraceResult, trace_imports}; +pub use trace::{DEFAULT_MAX_TRACE_PATHS, MultiFileImport, TraceError, TraceResult, trace_imports}; pub use verbosity::{FlaggedLineFinding, Verbosity}; + +pub fn is_non_runtime_tooling_path( + model: &codeint_model::CodeModel, + path: &codeint_model::RepoPath, +) -> bool { + tooling_paths::ToolingPaths::from_model(model).is_non_runtime_tooling_path(path) +} + +pub(crate) fn build_resolved_import_adjacency( + model: &codeint_model::CodeModel, + node_count: usize, + index_of: impl Fn(&codeint_model::RepoPath) -> Option, +) -> Vec> { + let mut adjacency = vec![Vec::new(); node_count]; + for runtime_import in &model.runtime_imports { + if let codeint_model::ImportResolution::Resolved(targets) = &runtime_import.resolution + && let Some(from) = index_of(&runtime_import.importer) + { + for target in targets { + if let Some(to) = index_of(target) { + adjacency[from].push(to); + } + } + } + } + for neighbors in &mut adjacency { + neighbors.sort_unstable(); + neighbors.dedup(); + } + adjacency +} + +#[cfg(test)] +pub(crate) mod test_support { + use codeint_model::{FileModel, RepoPath, SourceFile, SourceSet}; + + pub(crate) fn repo_path(text: &str) -> RepoPath { + RepoPath::new(text).expect("valid repo path") + } + + pub(crate) fn empty_source_file( + name: &str, + source_set: SourceSet, + source_lines: u32, + ) -> SourceFile { + SourceFile { + path: repo_path(name), + model: FileModel { + source_set, + source_lines, + functions: Vec::new(), + tokens: Vec::new(), + flagged_lines: Vec::new(), + hazard_lines: Vec::new(), + runtime_imports: Vec::new(), + program_start: false, + }, + } + } +} diff --git a/crates/metrics/src/orphan_files.rs b/crates/metrics/src/orphan_files.rs index 4574a6b5..255b75e1 100644 --- a/crates/metrics/src/orphan_files.rs +++ b/crates/metrics/src/orphan_files.rs @@ -222,22 +222,25 @@ fn build_import_graphs( 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 { + let ImportResolution::Resolved(targets) = &runtime_import.resolution else { continue; }; - let (Some(&from), Some(&to)) = - (index_of.get(&runtime_import.importer), index_of.get(target)) - else { + let Some(&from) = index_of.get(&runtime_import.importer) 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); + for target in targets { + let Some(&to) = 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); + } } } } diff --git a/crates/metrics/src/orphan_files/tests.rs b/crates/metrics/src/orphan_files/tests.rs index 2e438f2f..a67ffb69 100644 --- a/crates/metrics/src/orphan_files/tests.rs +++ b/crates/metrics/src/orphan_files/tests.rs @@ -18,7 +18,9 @@ fn source_file(name: &str, source_set: SourceSet) -> SourceFile { functions: Vec::new(), tokens: Vec::new(), flagged_lines: Vec::new(), + hazard_lines: Vec::new(), runtime_imports: Vec::new(), + program_start: false, }, } } @@ -38,7 +40,7 @@ fn build_model( .map(|(from, to)| RuntimeImport { importer: repo_path(from), specifier: format!("./{to}"), - resolution: ImportResolution::Resolved(repo_path(to)), + resolution: ImportResolution::Resolved(vec![repo_path(to)]), }) .collect(), workspace: Workspace::new(workspace_members.iter().copied().map(repo_path)), @@ -475,3 +477,116 @@ fn excludes_nested_example_subpackage_from_orphan_roots_and_evaluated_files() { "pkgs/foo/lib/dead.dart", ); } + +#[test] +fn multi_file_resolved_imports_mark_all_targets_and_transitive_folders_reachable() { + let mut model = build_model( + &[ + ("app/main.fld", SourceSet::Production), + ("core/alpha.fld", SourceSet::Production), + ("core/beta.fld", SourceSet::Production), + ("core/alpha_test.fld", SourceSet::Test), + ("nested/first.fld", SourceSet::Production), + ("nested/second.fld", SourceSet::Production), + ("solo/only.fld", SourceSet::Production), + ("unused/orphan_a.fld", SourceSet::Production), + ("unused/orphan_b.fld", SourceSet::Production), + ("helpers/mock_a.fld", SourceSet::Production), + ("helpers/mock_b.fld", SourceSet::Production), + ("helpers_deep/deep_a.fld", SourceSet::Production), + ("helpers_deep/deep_b.fld", SourceSet::Production), + ("tests/suite_test.fld", SourceSet::Test), + ], + &[], + &[], + ); + let multi_import = |importer: &str, specifier: &str, targets: &[&str]| RuntimeImport { + importer: repo_path(importer), + specifier: specifier.to_owned(), + resolution: ImportResolution::Resolved(targets.iter().copied().map(repo_path).collect()), + }; + model.runtime_imports = vec![ + multi_import( + "app/main.fld", + "core", + &["core/alpha.fld", "core/alpha_test.fld", "core/beta.fld"], + ), + multi_import("app/main.fld", "solo", &["solo/only.fld"]), + multi_import( + "core/beta.fld", + "nested", + &["nested/first.fld", "nested/second.fld"], + ), + multi_import( + "core/alpha_test.fld", + "helpers", + &["helpers/mock_a.fld", "helpers/mock_b.fld"], + ), + multi_import( + "tests/suite_test.fld", + "helpers", + &["helpers/mock_a.fld", "helpers/mock_b.fld"], + ), + multi_import( + "helpers/mock_b.fld", + "helpers_deep", + &["helpers_deep/deep_a.fld", "helpers_deep/deep_b.fld"], + ), + ]; + + let measured = OrphanFiles::measure(&model, &[repo_path("app/main.fld")]) + .expect("entry point activates orphan-file detection"); + + assert_eq!(measured.evaluated_files(), 12); + assert_eq!(measured.entry_points(), &[repo_path("app/main.fld")]); + assert_eq!(measured.unreferenced_count(), 2); + assert_eq!(measured.test_only_count(), 4); + + let expected_importers: &[&str] = &["core/alpha_test.fld", "tests/suite_test.fld"]; + let expected: Vec<(&str, OrphanFileKind, &[&str])> = vec![ + ( + "helpers/mock_a.fld", + OrphanFileKind::TestOnly, + expected_importers, + ), + ( + "helpers/mock_b.fld", + OrphanFileKind::TestOnly, + expected_importers, + ), + ( + "helpers_deep/deep_a.fld", + OrphanFileKind::TestOnly, + expected_importers, + ), + ( + "helpers_deep/deep_b.fld", + OrphanFileKind::TestOnly, + expected_importers, + ), + ("unused/orphan_a.fld", OrphanFileKind::Unreferenced, &[]), + ("unused/orphan_b.fld", OrphanFileKind::Unreferenced, &[]), + ]; + let summary: Vec<(&str, OrphanFileKind, Vec<&str>)> = measured + .findings() + .iter() + .map(|finding| { + ( + finding.path.as_str(), + finding.kind, + finding + .test_importers + .iter() + .map(RepoPath::as_str) + .collect(), + ) + }) + .collect(); + assert_eq!( + summary + .iter() + .map(|(path, kind, importers)| (*path, *kind, importers.as_slice())) + .collect::>(), + expected + ); +} diff --git a/crates/metrics/src/trace.rs b/crates/metrics/src/trace.rs index 22bb97f2..97b11d41 100644 --- a/crates/metrics/src/trace.rs +++ b/crates/metrics/src/trace.rs @@ -1,4 +1,4 @@ -use std::collections::{BTreeMap, VecDeque}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::error::Error; use std::fmt; @@ -28,6 +28,13 @@ impl fmt::Display for TraceError { impl Error for TraceError {} +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MultiFileImport { + pub importer: RepoPath, + pub specifier: String, + pub targets: Vec, +} + #[derive(Clone, Debug, PartialEq, Eq)] pub struct TraceResult { pub from: RepoPath, @@ -35,6 +42,7 @@ pub struct TraceResult { pub connected: bool, pub shortest_distance: Option, pub paths: Vec>, + pub multi_file_imports: Vec, pub truncated: bool, } @@ -69,10 +77,13 @@ pub fn trace_imports( connected: true, shortest_distance: Some(0), paths: vec![vec![from.clone()]], + multi_file_imports: Vec::new(), truncated: false, }); } - let adjacency = build_adjacency(model, &index_of, modules.len()); + let adjacency = crate::build_resolved_import_adjacency(model, modules.len(), |path| { + index_of.get(path).copied() + }); let (dist, parents) = shortest_path_dag(&adjacency, from_idx, to_idx); let Some(target_distance) = dist[to_idx] else { return Ok(TraceResult { @@ -81,12 +92,14 @@ pub fn trace_imports( connected: false, shortest_distance: None, paths: Vec::new(), + multi_file_imports: Vec::new(), truncated: false, }); }; let forward = build_forward_shortest_dag(&parents, to_idx, modules.len()); let limit = if all_shortest { max_paths } else { 1 }; let (index_paths, truncated) = collect_shortest_paths(&forward, from_idx, to_idx, limit); + let multi_file_imports = collect_multi_file_imports(model, &index_of, &modules, &index_paths); let paths = index_paths .into_iter() .map(|chain| { @@ -102,29 +115,95 @@ pub fn trace_imports( connected: true, shortest_distance: Some(target_distance), paths, + multi_file_imports, truncated: all_shortest && truncated, }) } -fn build_adjacency( +fn collect_multi_file_imports( model: &CodeModel, index_of: &BTreeMap<&RepoPath, usize>, - node_count: usize, -) -> Vec> { - let mut adjacency = vec![Vec::new(); node_count]; + modules: &[&RepoPath], + index_paths: &[Vec], +) -> Vec { + let by_importer = index_multi_file_imports(model, index_of); + if by_importer.is_empty() { + return Vec::new(); + } + let mut seen: BTreeSet<(usize, &str, &[usize])> = BTreeSet::new(); + let mut result = Vec::new(); + for chain in index_paths { + for edge in chain.windows(2) { + record_multi_file_edge( + edge[0], + edge[1], + &by_importer, + modules, + &mut seen, + &mut result, + ); + } + } + result +} + +fn index_multi_file_imports<'a>( + model: &'a CodeModel, + index_of: &BTreeMap<&RepoPath, usize>, +) -> BTreeMap)>> { + let mut by_importer: BTreeMap)>> = BTreeMap::new(); for runtime_import in &model.runtime_imports { - if let ImportResolution::Resolved(target) = &runtime_import.resolution - && let (Some(&from), Some(&to)) = - (index_of.get(&runtime_import.importer), index_of.get(target)) - { - adjacency[from].push(to); + let ImportResolution::Resolved(targets) = &runtime_import.resolution else { + continue; + }; + let Some(&from_idx) = index_of.get(&runtime_import.importer) else { + continue; + }; + let mut target_indices: Vec = targets + .iter() + .filter_map(|target| index_of.get(target).copied()) + .collect(); + target_indices.sort_unstable(); + target_indices.dedup(); + if target_indices.len() > 1 { + by_importer + .entry(from_idx) + .or_default() + .push((runtime_import.specifier.as_str(), target_indices)); } } - for neighbors in &mut adjacency { - neighbors.sort_unstable(); - neighbors.dedup(); + for imports in by_importer.values_mut() { + imports.sort(); + imports.dedup(); + } + by_importer +} + +fn record_multi_file_edge<'a>( + from_idx: usize, + to_idx: usize, + by_importer: &'a BTreeMap)>>, + modules: &[&RepoPath], + seen: &mut BTreeSet<(usize, &'a str, &'a [usize])>, + result: &mut Vec, +) { + let Some(imports) = by_importer.get(&from_idx) else { + return; + }; + for (specifier, target_indices) in imports { + if target_indices.binary_search(&to_idx).is_ok() + && seen.insert((from_idx, *specifier, target_indices.as_slice())) + { + result.push(MultiFileImport { + importer: modules[from_idx].clone(), + specifier: (*specifier).to_owned(), + targets: target_indices + .iter() + .map(|&index| modules[index].clone()) + .collect(), + }); + } } - adjacency } fn shortest_path_dag( diff --git a/crates/metrics/src/trace/tests.rs b/crates/metrics/src/trace/tests.rs index 647b9f22..aa163726 100644 --- a/crates/metrics/src/trace/tests.rs +++ b/crates/metrics/src/trace/tests.rs @@ -2,7 +2,7 @@ use codeint_model::{ CodeModel, FileModel, ImportResolution, RepoPath, RuntimeImport, SourceFile, SourceSet, }; -use super::{DEFAULT_MAX_TRACE_PATHS, TraceError, trace_imports}; +use super::{DEFAULT_MAX_TRACE_PATHS, MultiFileImport, TraceError, trace_imports}; fn repo_path(path: &str) -> RepoPath { RepoPath::new(path).unwrap() @@ -19,7 +19,9 @@ fn model_with_edges(files: &[&str], edges: &[(&str, &str)]) -> CodeModel { functions: Vec::new(), tokens: Vec::new(), flagged_lines: Vec::new(), + hazard_lines: Vec::new(), runtime_imports: Vec::new(), + program_start: false, }, }); } @@ -27,7 +29,7 @@ fn model_with_edges(files: &[&str], edges: &[(&str, &str)]) -> CodeModel { model.runtime_imports.push(RuntimeImport { importer: repo_path(from), specifier: (*to).to_owned(), - resolution: ImportResolution::Resolved(repo_path(to)), + resolution: ImportResolution::Resolved(vec![repo_path(to)]), }); } model @@ -120,5 +122,133 @@ fn trace_terminates_on_dense_cycle_without_looping() { assert!(!result.connected); assert_eq!(result.shortest_distance, None); assert!(result.paths.is_empty()); + assert!(result.multi_file_imports.is_empty()); assert!(!result.truncated); } + +#[test] +fn trace_records_multi_file_imports_along_returned_paths_and_omits_single_and_unused_ones() { + let mut model = model_with_edges( + &[ + "src/app.fld", + "pkg/mid/a.fld", + "pkg/mid/b.fld", + "pkg/mid/sibling.fld", + "pkg/leaf/end.fld", + "pkg/leaf/other.fld", + "pkg/unused/x.fld", + "pkg/unused/y.fld", + ], + &[], + ); + model.runtime_imports.push(RuntimeImport { + importer: repo_path("src/app.fld"), + specifier: "pkg/mid".to_owned(), + resolution: ImportResolution::Resolved(vec![ + repo_path("pkg/mid/b.fld"), + repo_path("pkg/mid/sibling.fld"), + repo_path("pkg/mid/a.fld"), + repo_path("pkg/mid/a.fld"), + ]), + }); + model.runtime_imports.push(RuntimeImport { + importer: repo_path("src/app.fld"), + specifier: "pkg/unused".to_owned(), + resolution: ImportResolution::Resolved(vec![ + repo_path("pkg/unused/x.fld"), + repo_path("pkg/unused/y.fld"), + ]), + }); + model.runtime_imports.push(RuntimeImport { + importer: repo_path("pkg/mid/a.fld"), + specifier: "pkg/leaf".to_owned(), + resolution: ImportResolution::Resolved(vec![ + repo_path("pkg/leaf/other.fld"), + repo_path("pkg/leaf/end.fld"), + ]), + }); + model.runtime_imports.push(RuntimeImport { + importer: repo_path("pkg/mid/b.fld"), + specifier: "pkg/leaf/end".to_owned(), + resolution: ImportResolution::Resolved(vec![ + repo_path("pkg/leaf/end.fld"), + repo_path("pkg/leaf/end.fld"), + ]), + }); + + let all = trace_imports( + &model, + &repo_path("src/app.fld"), + &repo_path("pkg/leaf/end.fld"), + true, + DEFAULT_MAX_TRACE_PATHS, + ) + .unwrap(); + assert!(all.connected); + assert_eq!(all.shortest_distance, Some(2)); + assert_eq!( + all.paths, + vec![ + vec![ + repo_path("src/app.fld"), + repo_path("pkg/mid/a.fld"), + repo_path("pkg/leaf/end.fld"), + ], + vec![ + repo_path("src/app.fld"), + repo_path("pkg/mid/b.fld"), + repo_path("pkg/leaf/end.fld"), + ], + ] + ); + assert_eq!( + all.multi_file_imports, + vec![ + MultiFileImport { + importer: repo_path("src/app.fld"), + specifier: "pkg/mid".to_owned(), + targets: vec![ + repo_path("pkg/mid/a.fld"), + repo_path("pkg/mid/b.fld"), + repo_path("pkg/mid/sibling.fld"), + ], + }, + MultiFileImport { + importer: repo_path("pkg/mid/a.fld"), + specifier: "pkg/leaf".to_owned(), + targets: vec![ + repo_path("pkg/leaf/end.fld"), + repo_path("pkg/leaf/other.fld") + ], + }, + ] + ); + + let direct = trace_imports( + &model, + &repo_path("src/app.fld"), + &repo_path("pkg/mid/sibling.fld"), + false, + DEFAULT_MAX_TRACE_PATHS, + ) + .unwrap(); + assert_eq!( + direct.paths, + vec![vec![ + repo_path("src/app.fld"), + repo_path("pkg/mid/sibling.fld") + ]] + ); + assert_eq!( + direct.multi_file_imports, + vec![MultiFileImport { + importer: repo_path("src/app.fld"), + specifier: "pkg/mid".to_owned(), + targets: vec![ + repo_path("pkg/mid/a.fld"), + repo_path("pkg/mid/b.fld"), + repo_path("pkg/mid/sibling.fld"), + ], + }] + ); +} diff --git a/crates/metrics/src/verbosity/tests.rs b/crates/metrics/src/verbosity/tests.rs index 63168f52..2f5b6275 100644 --- a/crates/metrics/src/verbosity/tests.rs +++ b/crates/metrics/src/verbosity/tests.rs @@ -19,7 +19,9 @@ fn file(path: &str, source_lines: u32, flagged: &[(u32, &str)]) -> SourceFile { rule: rule.to_owned(), }) .collect(), + hazard_lines: Vec::new(), runtime_imports: Vec::new(), + program_start: false, }, } } diff --git a/crates/model/HOW-TO.md b/crates/model/HOW-TO.md index 091aa0fb..94274a5f 100644 --- a/crates/model/HOW-TO.md +++ b/crates/model/HOW-TO.md @@ -40,7 +40,9 @@ impl Guest for Plain { functions: Vec::new(), tokens, flagged_lines: Vec::new(), + hazard_lines: Vec::new(), runtime_imports: Vec::new(), + program_start: false, }) } @@ -82,10 +84,22 @@ impl Guest for Plain { source: "Plain text panel of 40 repositories, Table 3".to_owned(), }] } + + fn has_hazard_rules() -> bool { + false + } + + fn hazard_rules() -> Vec { + Vec::new() + } + + fn has_imports() -> bool { + true + } } ``` -- The interface is defined once, in [wit/language.wit](../../wit/language.wit), as the versioned package `codeint:plugin@0.2.0`. +- The interface is defined once, in [wit/language.wit](../../wit/language.wit), as the versioned package `codeint:plugin@0.3.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. @@ -113,8 +127,15 @@ impl Guest for Plain { `metric` is the Metric's key in the report: `erosion`, `verbosity`, `duplication`, or `import_cycles`. `low` and `high` are ratios with `0 <= low <= high <= 1`. Return no entry for a Metric that has no published Reference range in this language; never borrow a range measured in another language. +- `has_hazard_rules` states whether this Language plugin defines Hazard line rules, and `hazard_rules` returns their stable names (empty when `has_hazard_rules` is `false`). + The five built-in Language plugins return `false` and an empty list. +- `has_imports` states whether the language has runtime imports, manifests, and entry points. + When `has_imports` returns `false`, codeint never calls `manifest_paths`, `workspace_packages`, `resolve_imports`, `declared_dependencies`, or `entry_points`. + The five built-in Language plugins return `true`. - Each `Function` has `line` and `end-line`, the lines where it starts and ends, counted from 1; `end-line` equals `line` for a function on one line. The core reads the tokens from `line` to `end-line` as the content of the function's Finding identity. + Each `Function` also carries `coverage: Option` with `listed_lines` and `executed_lines`. + A Language plugin always sets `coverage` to `None`; codeint fills coverage facts from Coverage reports before Metrics run. - `tokens` lists every token of the file in source order, each with its kind, the hash of its text, and the 1-based line on which it starts. Leave out whitespace and comments; the core finds Clone groups from this stream. - `kind` says whether a token is an identifier, a literal, another token, or a token of an import or export declaration. @@ -127,12 +148,18 @@ impl Guest for Plain { - `flagged_lines` lists each Flagged line as `FlaggedLine { line, rule }`, with `line` counted from 1 and `rule` the stable identifier of the Flagged-line rule, such as `else-after-return`. A line that matches two rules appears once per rule. The Flagged-line rules live in the Language plugin; the core never inspects code to find them. +- `hazard_lines` lists each Hazard line as `HazardLine { line, rule }`, with `line` counted from 1 and `rule` a stable rule name listed by `hazard_rules`. + A `HazardLine` never holds source text. + A line that matches two rules appears once per rule. + Return an empty list when `has_hazard_rules` returns `false`; the five built-in Language plugins always return an empty list. - `runtime_imports` lists the specifier of each import that runs when the file runs, in source order; leave out type-only imports. +- `program_start` is `false` unless the source text marks the file as a program start, such as a Go `package main` file. + The five built-in Language plugins always set `program_start` to `false`. - `manifest_paths` receives every file path of the repository snapshot and returns the paths of the files that finding workspace packages and resolving imports need to read, such as each `package.json` and `tsconfig.json` file. 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` with the canonical third-party package name, `Builtin` for a standard-library or runtime built-in module, or `Unresolved` with the reason. + Return one `Resolution` per request, in request order: `Resolved` with a non-empty list of paths 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`. @@ -153,7 +180,7 @@ assert_eq!(model.source_lines, 2); - Before lowering, call `choose_manifests(plugin, repository_paths)` once per Language plugin and read each path it returns, once, as `Manifest { path, text }`. Pass those manifests to `workspace_packages`, and after lowering to `resolve_runtime_imports(plugin, repository_paths, manifests, &importers)` with the files the plugin lowered. `choose_manifests` fails with `ResolveError::UnknownManifest` when the plugin names a path outside the snapshot. - `resolve_runtime_imports` returns one `RuntimeImport` per runtime import for `CodeModel::runtime_imports`, and a `ResolveError` when the plugin answers the wrong number of requests or names a file outside the snapshot. + `resolve_runtime_imports` returns one `RuntimeImport` per runtime import for `CodeModel::runtime_imports`, and a `ResolveError` when the plugin answers the wrong number of requests, returns an empty `Resolved` target list, or names a file outside the snapshot. - `codeint_model::LowerError` is the core's error; it converts from the WIT `lower-error` and names the failure in its message. - A `LowerError` never stops the run. Push a `LowerError::DeclarationOnly` file onto `CodeModel::declaration_only`, and every other failure onto `CodeModel::skipped` as a `SkippedFile` whose `reason` is the error's message. @@ -227,7 +254,7 @@ for (source_set, files) in source_sets.iter() { - `into_source_sets` moves each file into the `CodeModel` of its Source set. - It moves each `RuntimeImport` into the `CodeModel` of its importer's Source set, so an import of a file in another Source set adds no edge there. - Every Source set gets a `CodeModel`, empty when no file belongs to it. -- Every Source set's `CodeModel` keeps the whole `workspace`, so each Source set splits into the same workspace packages. +- Every Source set's `CodeModel` keeps the whole `workspace` and `languages`, so each Source set splits into the same workspace packages and carries the same per-language facts. - `iter` yields the Source sets in the order Production, Test, Generated, Vendored. - A skipped or declaration-only file belongs to no Source set. Read `skipped` and `declaration_only` before the split; the split leaves them out. @@ -260,6 +287,6 @@ use codeint_model::CodeModel; let total = CodeModel::merge([typescript_model, python_model]); ``` -- `merge` joins the files, skipped files, declaration-only files, runtime imports, declared dependencies, dependency manifests, manifest-used dependencies, and workspace packages of every model. +- `merge` joins the files, skipped files, declaration-only files, runtime imports, declared dependencies, dependency manifests, manifest-used dependencies, workspace packages, and per-language facts (`languages`) of every model. - Give each Language plugin's `CodeModel` the whole `workspace` that every plugin found, so each per-language section lists the same workspace packages as the total. -- It orders files, skipped files, and declaration-only files by path, so the total does not depend on the order of the plugins. +- It orders files, skipped files, declaration-only files, and `languages` deterministically by path or language name, so the total does not depend on the order of the plugins. diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index aeabbecc..2b58449f 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -24,7 +24,8 @@ mod bindings { pub use bindings::exports::codeint::plugin::language; pub use language::{ - DeclaredDep, DepKind, FileModel, Manifest, ReferenceRange, SourceSet, Token, TokenKind, + DeclaredDep, DepKind, FileModel, FunctionCoverage, HazardLine, Manifest, ReferenceRange, + SourceSet, Token, TokenKind, }; pub use metric::{ ExternalFinding, ExternalMetricMeasurement, Metric, MetricPlugin, MetricPluginError, @@ -146,6 +147,14 @@ pub struct ManifestUsedDep { pub name: String, } +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LanguageFacts { + pub language: String, + pub has_coverage: bool, + pub has_hazard_rules: bool, + pub has_imports: bool, +} + #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct CodeModel { pub files: Vec, @@ -156,6 +165,7 @@ pub struct CodeModel { pub declared_dependencies: Vec, pub dependency_manifests: Vec, pub manifest_used_dependencies: Vec, + pub languages: Vec, } #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -169,6 +179,7 @@ pub struct SourceSets { impl CodeModel { pub fn merge(models: impl IntoIterator) -> CodeModel { let mut merged = CodeModel::default(); + let mut languages: BTreeMap = BTreeMap::new(); for model in models { merged.files.extend(model.files); merged.skipped.extend(model.skipped); @@ -184,6 +195,16 @@ impl CodeModel { merged .manifest_used_dependencies .extend(model.manifest_used_dependencies); + for facts in model.languages { + languages + .entry(facts.language.clone()) + .and_modify(|existing| { + existing.has_coverage |= facts.has_coverage; + existing.has_hazard_rules |= facts.has_hazard_rules; + existing.has_imports |= facts.has_imports; + }) + .or_insert(facts); + } } merged .files @@ -196,6 +217,7 @@ impl CodeModel { merged.dependency_manifests.dedup(); merged.manifest_used_dependencies.sort(); merged.manifest_used_dependencies.dedup(); + merged.languages = languages.into_values().collect(); merged } @@ -213,6 +235,7 @@ impl CodeModel { &mut source_sets.vendored, ] { source_set.workspace = self.workspace.clone(); + source_set.languages = self.languages.clone(); } for file in self.files { source_sets.get_mut(file.model.source_set).files.push(file); @@ -357,6 +380,23 @@ pub enum LanguagePluginError { call: &'static str, reason: String, }, + #[error( + "Language plugin {plugin:?} returned Hazard line {line} in {path}, which is outside the file's {line_count} lines" + )] + HazardLineOutOfRange { + plugin: String, + path: RepoPath, + line: u32, + line_count: usize, + }, + #[error( + "Language plugin {plugin:?} returned a Hazard line with unlisted rule {rule:?} in {path}" + )] + UnlistedHazardRule { + plugin: String, + path: RepoPath, + rule: String, + }, } pub fn validate_declared_dependencies( @@ -410,7 +450,7 @@ pub trait LanguagePlugin: Sync { repository_paths: &[RepoPath], manifests: Vec, requests: Vec, - ) -> Vec; + ) -> Result, LanguagePluginError>; fn declared_dependencies( &self, @@ -424,6 +464,12 @@ pub trait LanguagePlugin: Sync { ) -> Result, LanguagePluginError>; fn reference_ranges(&self) -> Result; + + fn has_hazard_rules(&self) -> bool; + + fn hazard_rules(&self) -> Vec; + + fn has_imports(&self) -> bool; } impl LanguagePlugin for Plugin { @@ -454,8 +500,12 @@ impl LanguagePlugin for Plugin { repository_paths: &[RepoPath], manifests: Vec, requests: Vec, - ) -> Vec { - Plugin::resolve_imports(owned_paths(repository_paths), manifests, requests) + ) -> Result, LanguagePluginError> { + Ok(Plugin::resolve_imports( + owned_paths(repository_paths), + manifests, + requests, + )) } fn declared_dependencies( @@ -479,6 +529,18 @@ impl LanguagePlugin for Plugin { fn reference_ranges(&self) -> Result { ReferenceRanges::new(Plugin::reference_ranges()) } + + fn has_hazard_rules(&self) -> bool { + Plugin::has_hazard_rules() + } + + fn hazard_rules(&self) -> Vec { + Plugin::hazard_rules() + } + + fn has_imports(&self) -> bool { + Plugin::has_imports() + } } fn owned_paths(repository_paths: &[RepoPath]) -> Vec { diff --git a/crates/model/src/metric.rs b/crates/model/src/metric.rs index ace21ecf..af9d8d75 100644 --- a/crates/model/src/metric.rs +++ b/crates/model/src/metric.rs @@ -52,16 +52,8 @@ pub struct ExternalMetricMeasurement { #[derive(Debug, thiserror::Error)] pub enum MetricPluginError { - #[error("Metric plugin {plugin:?} failed during measure: {reason}")] - Call { plugin: String, reason: String }, - #[error("Metric plugin {plugin:?} exceeded its memory cap of {memory_mb} MiB")] - MemoryLimitExceeded { plugin: String, memory_mb: u64 }, - #[error("Metric plugin {plugin:?} exceeded its time limit of {timeout_ms} ms")] - TimeLimitExceeded { plugin: String, timeout_ms: u64 }, - #[error( - "Metric plugin {plugin:?} returned an invalid ratio {ratio}; it must be finite and between 0 and 1" - )] - InvalidRatio { plugin: String, ratio: f64 }, + #[error("Metric plugin {plugin:?} returned a Finding with an empty id")] + EmptyFindingId { plugin: String }, #[error( "Metric plugin {plugin:?} returned an invalid {field} {value}; it must be finite and non-negative" )] @@ -70,12 +62,20 @@ pub enum MetricPluginError { field: &'static str, value: f64, }, - #[error("Metric plugin {plugin:?} returned a Finding with an empty id")] - EmptyFindingId { plugin: String }, - #[error("Metric plugin {plugin:?} returned a Finding with an invalid path {path:?}")] - InvalidFindingPath { plugin: String, path: String }, #[error("Metric plugin {plugin:?} returned a Finding with line 0; lines start at 1")] InvalidFindingLine { plugin: String }, + #[error("Metric plugin {plugin:?} failed during measure: {reason}")] + Call { plugin: String, reason: String }, + #[error("Metric plugin {plugin:?} returned a Finding with an invalid path {path:?}")] + InvalidFindingPath { plugin: String, path: String }, + #[error("Metric plugin {plugin:?} exceeded its memory cap of {memory_mb} MiB")] + MemoryLimitExceeded { plugin: String, memory_mb: u64 }, + #[error("Metric plugin {plugin:?} exceeded its time limit of {timeout_ms} ms")] + TimeLimitExceeded { plugin: String, timeout_ms: u64 }, + #[error( + "Metric plugin {plugin:?} returned an invalid ratio {ratio}; it must be finite and between 0 and 1" + )] + InvalidRatio { plugin: String, ratio: f64 }, } pub trait MetricPlugin: Sync { diff --git a/crates/model/src/runtime_imports.rs b/crates/model/src/runtime_imports.rs index ea4b640c..84ce0891 100644 --- a/crates/model/src/runtime_imports.rs +++ b/crates/model/src/runtime_imports.rs @@ -1,13 +1,13 @@ use std::collections::HashSet; -use crate::{LanguagePlugin, Manifest, RepoPath, SourceFile, language}; +use crate::{LanguagePlugin, LanguagePluginError, Manifest, RepoPath, SourceFile, language}; #[cfg(test)] mod tests; #[derive(Clone, Debug, PartialEq, Eq)] pub enum ImportResolution { - Resolved(RepoPath), + Resolved(Vec), External(String), Builtin, Unresolved { reason: String }, @@ -24,6 +24,11 @@ pub struct RuntimeImport { pub enum ResolveError { #[error("the Language plugin answered {answered} of {asked} import requests")] WrongCount { asked: usize, answered: usize }, + #[error("the Language plugin resolved {specifier:?} in {importer} to an empty list of files")] + EmptyResolution { + importer: RepoPath, + specifier: String, + }, #[error( "the Language plugin resolved {specifier:?} in {importer} to {target:?}, which is not a file of the repository" )] @@ -34,12 +39,17 @@ pub enum ResolveError { }, #[error("the Language plugin asked to read {path:?}, which is not a file of the repository")] UnknownManifest { path: String }, + #[error(transparent)] + Plugin(#[from] LanguagePluginError), } pub fn choose_manifests( plugin: &dyn LanguagePlugin, repository_paths: &[RepoPath], ) -> Result, ResolveError> { + if !plugin.has_imports() { + return Ok(Vec::new()); + } let known_paths: HashSet<&str> = repository_paths.iter().map(RepoPath::as_str).collect(); plugin .manifest_paths(repository_paths) @@ -60,6 +70,9 @@ pub fn resolve_runtime_imports( manifests: Vec, importers: &[&SourceFile], ) -> Result, ResolveError> { + if !plugin.has_imports() { + return Ok(Vec::new()); + } let pending: Vec<(&RepoPath, &String)> = importers .iter() .flat_map(|file| { @@ -79,7 +92,7 @@ pub fn resolve_runtime_imports( specifier: (*specifier).clone(), }) .collect(); - let resolutions = plugin.resolve_imports(repository_paths, manifests, requests); + let resolutions = plugin.resolve_imports(repository_paths, manifests, requests)?; if resolutions.len() != pending.len() { return Err(ResolveError::WrongCount { asked: pending.len(), @@ -91,21 +104,7 @@ pub fn resolve_runtime_imports( .into_iter() .zip(resolutions) .map(|((importer, specifier), resolution)| { - let resolution = match resolution { - language::Resolution::Resolved(target) if known_paths.contains(target.as_str()) => { - ImportResolution::Resolved(RepoPath(target)) - } - language::Resolution::Resolved(target) => { - return Err(ResolveError::UnknownTarget { - importer: importer.clone(), - specifier: specifier.clone(), - target, - }); - } - language::Resolution::External(package) => ImportResolution::External(package), - language::Resolution::Builtin => ImportResolution::Builtin, - language::Resolution::Unresolved(reason) => ImportResolution::Unresolved { reason }, - }; + let resolution = validate_resolution(importer, specifier, resolution, &known_paths)?; Ok(RuntimeImport { importer: importer.clone(), specifier: specifier.clone(), @@ -114,3 +113,49 @@ pub fn resolve_runtime_imports( }) .collect() } + +fn validate_resolution( + importer: &RepoPath, + specifier: &str, + resolution: language::Resolution, + known_paths: &HashSet<&str>, +) -> Result { + match resolution { + language::Resolution::Resolved(targets) => { + validate_resolved_targets(importer, specifier, targets, known_paths) + .map(ImportResolution::Resolved) + } + language::Resolution::External(package) => Ok(ImportResolution::External(package)), + language::Resolution::Builtin => Ok(ImportResolution::Builtin), + language::Resolution::Unresolved(reason) => Ok(ImportResolution::Unresolved { reason }), + } +} + +fn validate_resolved_targets( + importer: &RepoPath, + specifier: &str, + targets: Vec, + known_paths: &HashSet<&str>, +) -> Result, ResolveError> { + if targets.is_empty() { + return Err(ResolveError::EmptyResolution { + importer: importer.clone(), + specifier: specifier.to_owned(), + }); + } + let mut validated = Vec::with_capacity(targets.len()); + let mut seen_targets = HashSet::with_capacity(targets.len()); + for target in targets { + if !known_paths.contains(target.as_str()) { + return Err(ResolveError::UnknownTarget { + importer: importer.clone(), + specifier: specifier.to_owned(), + target, + }); + } + if seen_targets.insert(target.clone()) { + validated.push(RepoPath(target)); + } + } + Ok(validated) +} diff --git a/crates/model/src/runtime_imports/tests.rs b/crates/model/src/runtime_imports/tests.rs index c8fcb3fe..01749499 100644 --- a/crates/model/src/runtime_imports/tests.rs +++ b/crates/model/src/runtime_imports/tests.rs @@ -8,7 +8,18 @@ use super::{ ImportResolution, ResolveError, RuntimeImport, choose_manifests, resolve_runtime_imports, }; -struct Answering(Vec); +enum StubAnswer { + Resolutions(Vec), + MemoryLimit { plugin: String, memory_mb: u64 }, +} + +struct Answering(StubAnswer); + +impl Answering { + fn of(resolutions: Vec) -> Answering { + Answering(StubAnswer::Resolutions(resolutions)) + } +} impl LanguagePlugin for Answering { fn declared_dependencies( @@ -50,13 +61,33 @@ impl LanguagePlugin for Answering { _repository_paths: &[RepoPath], _manifests: Vec, _requests: Vec, - ) -> Vec { - self.0.clone() + ) -> Result, LanguagePluginError> { + match &self.0 { + StubAnswer::Resolutions(resolutions) => Ok(resolutions.clone()), + StubAnswer::MemoryLimit { plugin, memory_mb } => { + Err(LanguagePluginError::MemoryLimitExceeded { + plugin: plugin.clone(), + memory_mb: *memory_mb, + }) + } + } } fn reference_ranges(&self) -> Result { ReferenceRanges::new(Vec::new()) } + + fn has_hazard_rules(&self) -> bool { + false + } + + fn hazard_rules(&self) -> Vec { + Vec::new() + } + + fn has_imports(&self) -> bool { + true + } } fn path(text: &str) -> RepoPath { @@ -72,25 +103,27 @@ fn importer(name: &str, specifiers: &[&str]) -> SourceFile { functions: Vec::new(), tokens: Vec::new(), flagged_lines: Vec::new(), + hazard_lines: Vec::new(), runtime_imports: specifiers.iter().map(|text| (*text).to_owned()).collect(), + program_start: false, }, } } #[test] fn each_runtime_import_keeps_its_importer_specifier_and_resolution() { - let plugin = Answering(vec![ - Resolution::Resolved("b.ts".to_owned()), + let plugin = Answering::of(vec![ + Resolution::Resolved(vec!["b.ts".to_owned(), "c.ts".to_owned()]), Resolution::External("react".to_owned()), Resolution::Builtin, Resolution::Unresolved("gone".to_owned()), ]); - let a = importer("a.ts", &["./b", "react", "node:fs"]); + let a = importer("a.ts", &["./pkg", "react", "node:fs"]); let b = importer("b.ts", &["./gone"]); let imports = resolve_runtime_imports( &plugin, - &[path("a.ts"), path("b.ts")], + &[path("a.ts"), path("b.ts"), path("c.ts")], Vec::new(), &[&a, &b], ) @@ -101,8 +134,8 @@ fn each_runtime_import_keeps_its_importer_specifier_and_resolution() { [ RuntimeImport { importer: path("a.ts"), - specifier: "./b".to_owned(), - resolution: ImportResolution::Resolved(path("b.ts")), + specifier: "./pkg".to_owned(), + resolution: ImportResolution::Resolved(vec![path("b.ts"), path("c.ts")]), }, RuntimeImport { importer: path("a.ts"), @@ -127,7 +160,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("react".to_owned())]); + let plugin = Answering::of(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]); @@ -144,9 +177,29 @@ fn a_plugin_that_answers_the_wrong_number_of_requests_is_an_error() { ); } +#[test] +fn a_plugin_that_resolves_to_an_empty_list_is_an_error() { + let plugin = Answering::of(vec![Resolution::Resolved(Vec::new())]); + let a = importer("a.ts", &["./empty"]); + + let result = resolve_runtime_imports(&plugin, &[path("a.ts")], Vec::new(), &[&a]); + + assert!( + matches!( + &result, + Err(ResolveError::EmptyResolution { importer, specifier }) + if importer.as_str() == "a.ts" && specifier == "./empty" + ), + "unexpected result: {result:?}" + ); +} + #[test] fn a_plugin_that_resolves_to_a_file_outside_the_snapshot_is_an_error() { - let plugin = Answering(vec![Resolution::Resolved("../etc/passwd".to_owned())]); + let plugin = Answering::of(vec![Resolution::Resolved(vec![ + "a.ts".to_owned(), + "../etc/passwd".to_owned(), + ])]); let a = importer("a.ts", &["./b"]); let result = resolve_runtime_imports(&plugin, &[path("a.ts")], Vec::new(), &[&a]); @@ -159,7 +212,7 @@ fn a_plugin_that_resolves_to_a_file_outside_the_snapshot_is_an_error() { #[test] fn the_manifests_a_plugin_chooses_must_be_files_of_the_snapshot() { - let plugin = Answering(Vec::new()); + let plugin = Answering::of(Vec::new()); let chosen = choose_manifests(&plugin, &[path("a.ts"), path("package.json")]); let missing = choose_manifests(&plugin, &[path("a.ts")]); @@ -173,3 +226,126 @@ fn the_manifests_a_plugin_chooses_must_be_files_of_the_snapshot() { "unexpected result: {missing:?}" ); } + +#[test] +fn no_imports_plugin_is_never_asked_for_manifests_or_import_resolution() { + struct NoImportsPlugin; + + impl LanguagePlugin for NoImportsPlugin { + fn extensions(&self) -> Vec { + vec!["noimp".to_owned()] + } + + fn lower(&self, _path: &RepoPath, _text: &str) -> Result { + Err(LowerError::TooLarge) + } + + fn manifest_paths(&self, _repository_paths: &[RepoPath]) -> Vec { + panic!("manifest_paths must not be called when has_imports is false"); + } + + fn workspace_packages( + &self, + _manifests: Vec, + ) -> Result, WorkspaceError> { + panic!("workspace_packages must not be called when has_imports is false"); + } + + fn resolve_imports( + &self, + _repository_paths: &[RepoPath], + _manifests: Vec, + _requests: Vec, + ) -> Result, LanguagePluginError> { + panic!("resolve_imports must not be called when has_imports is false"); + } + + fn declared_dependencies( + &self, + _manifests: Vec, + ) -> Result, LanguagePluginError> { + panic!("declared_dependencies must not be called when has_imports is false"); + } + + fn entry_points( + &self, + _repository_paths: &[RepoPath], + _manifests: Vec, + ) -> Result, LanguagePluginError> { + panic!("entry_points must not be called when has_imports is false"); + } + + fn reference_ranges(&self) -> Result { + ReferenceRanges::new(Vec::new()) + } + + fn has_hazard_rules(&self) -> bool { + false + } + + fn hazard_rules(&self) -> Vec { + Vec::new() + } + + fn has_imports(&self) -> bool { + false + } + } + + let plugin = NoImportsPlugin; + let file = importer("a.noimp", &["./ignored"]); + + let manifests = + choose_manifests(&plugin, &[path("a.noimp")]).expect("choose_manifests skips no-imports"); + assert!(manifests.is_empty()); + + let resolved = resolve_runtime_imports(&plugin, &[path("a.noimp")], Vec::new(), &[&file]) + .expect("resolve_runtime_imports skips no-imports"); + assert!(resolved.is_empty()); +} + +#[test] +fn resolve_runtime_imports_deduplicates_targets_preserving_first_seen_order() { + let plugin = Answering::of(vec![Resolution::Resolved(vec![ + "src/b.fld".to_owned(), + "src/b.fld".to_owned(), + "src/a.fld".to_owned(), + "src/b.fld".to_owned(), + ])]); + let repo = [path("src/main.fld"), path("src/a.fld"), path("src/b.fld")]; + let file = importer("src/main.fld", &["pkg"]); + + let resolved = resolve_runtime_imports(&plugin, &repo, Vec::new(), &[&file]) + .expect("deduplicated multi-file resolution"); + + assert_eq!( + resolved, + vec![RuntimeImport { + importer: path("src/main.fld"), + specifier: "pkg".to_owned(), + resolution: ImportResolution::Resolved(vec![path("src/b.fld"), path("src/a.fld")]), + }] + ); +} + +#[test] +fn resolve_runtime_imports_propagates_plugin_memory_limit_errors() { + let plugin = Answering(StubAnswer::MemoryLimit { + plugin: "folder-import-lang".to_owned(), + memory_mb: 1, + }); + let file = importer("src/main.fld", &["pkg"]); + let error = resolve_runtime_imports(&plugin, &[path("src/main.fld")], Vec::new(), &[&file]) + .expect_err("memory limit error must propagate instead of becoming WrongCount"); + + assert!( + matches!( + error, + ResolveError::Plugin(LanguagePluginError::MemoryLimitExceeded { + ref plugin, + memory_mb: 1, + }) if plugin == "folder-import-lang" + ), + "unexpected error: {error:?}" + ); +} diff --git a/crates/model/src/scan.rs b/crates/model/src/scan.rs index c35ac275..89159d00 100644 --- a/crates/model/src/scan.rs +++ b/crates/model/src/scan.rs @@ -203,6 +203,7 @@ pub fn score_function_spans( source_lines: code_lines.range(start_line..=end_line).count() as u32, name: None, cognitive_complexity: 0, + coverage: None, } }) .collect(); @@ -303,7 +304,7 @@ pub fn resolve_relative_file( if joined == importer { Resolution::External(String::new()) } else { - Resolution::Resolved(joined) + Resolution::Resolved(vec![joined]) } } else { Resolution::Unresolved(format!("no file of the repository matches {rel_uri:?}")) diff --git a/crates/model/src/tests.rs b/crates/model/src/tests.rs index 8ffb0729..324d84d7 100644 --- a/crates/model/src/tests.rs +++ b/crates/model/src/tests.rs @@ -3,9 +3,10 @@ use super::language::{ Resolution, SourceSet, WorkspaceError, }; use super::{ - CodeModel, ImportResolution, InvalidReferenceRange, LanguagePlugin, LanguagePluginError, - ManifestUsedDep, Package, ReferenceRanges, RepoPath, RuntimeImport, SourceFile, Workspace, - token_text_hash, validate_declared_dependencies, validate_entry_points, + CodeModel, FunctionCoverage, ImportResolution, InvalidReferenceRange, LanguageFacts, + LanguagePlugin, LanguagePluginError, ManifestUsedDep, Package, ReferenceRanges, RepoPath, + RuntimeImport, SourceFile, Workspace, token_text_hash, validate_declared_dependencies, + validate_entry_points, }; fn path(text: &str) -> RepoPath { @@ -61,7 +62,9 @@ impl Guest for MeasuredLanguage { functions: Vec::new(), tokens: Vec::new(), flagged_lines: Vec::new(), + hazard_lines: Vec::new(), runtime_imports: Vec::new(), + program_start: false, }) } @@ -96,6 +99,18 @@ impl Guest for MeasuredLanguage { fn reference_ranges() -> Vec { vec![range("erosion", 0.12, 0.56, "Measured panel, Table 1")] } + + fn has_hazard_rules() -> bool { + false + } + + fn hazard_rules() -> Vec { + Vec::new() + } + + fn has_imports() -> bool { + true + } } fn range(metric: &str, low: f64, high: f64, source: &str) -> ReferenceRange { @@ -201,7 +216,9 @@ fn file_in(path: &str, source_set: SourceSet) -> SourceFile { functions: Vec::new(), tokens: Vec::new(), flagged_lines: Vec::new(), + hazard_lines: Vec::new(), runtime_imports: Vec::new(), + program_start: false, }, } } @@ -210,7 +227,7 @@ fn import_of(importer: &str, target: &str) -> RuntimeImport { RuntimeImport { importer: RepoPath::new(importer).expect("a valid path"), specifier: format!("./{target}"), - resolution: ImportResolution::Resolved(RepoPath::new(target).expect("a valid path")), + resolution: ImportResolution::Resolved(vec![RepoPath::new(target).expect("a valid path")]), } } @@ -374,3 +391,185 @@ fn code_model_merge_sorts_and_deduplicates_manifest_used_dependencies() { ] ); } + +#[test] +fn function_coverage_distinguishes_absent_from_zero_executed_lines() { + let absent = super::language::Function { + line: 1, + end_line: 5, + decision_points: 1, + source_lines: 5, + name: Some("uncovered".to_owned()), + cognitive_complexity: 1, + coverage: None, + }; + let zero_executed = super::language::Function { + line: 1, + end_line: 5, + decision_points: 1, + source_lines: 5, + name: Some("uncovered".to_owned()), + cognitive_complexity: 1, + coverage: Some(FunctionCoverage { + listed_lines: 5, + executed_lines: 0, + }), + }; + + assert_ne!(absent, zero_executed); + assert_eq!(absent.coverage, None); + assert_eq!( + zero_executed.coverage, + Some(FunctionCoverage { + listed_lines: 5, + executed_lines: 0, + }) + ); +} + +#[test] +fn code_model_merge_sorts_languages_and_combines_language_facts() { + let first = CodeModel { + languages: vec![ + LanguageFacts { + language: "typescript-javascript".to_owned(), + has_coverage: true, + has_hazard_rules: false, + has_imports: true, + }, + LanguageFacts { + language: "rust".to_owned(), + has_coverage: false, + has_hazard_rules: true, + has_imports: false, + }, + ], + ..CodeModel::default() + }; + let second = CodeModel { + languages: vec![ + LanguageFacts { + language: "python".to_owned(), + has_coverage: false, + has_hazard_rules: false, + has_imports: false, + }, + LanguageFacts { + language: "rust".to_owned(), + has_coverage: true, + has_hazard_rules: false, + has_imports: true, + }, + LanguageFacts { + language: "typescript-javascript".to_owned(), + has_coverage: false, + has_hazard_rules: true, + has_imports: false, + }, + ], + ..CodeModel::default() + }; + + let merged = CodeModel::merge([first, second]); + + assert_eq!( + merged.languages, + vec![ + LanguageFacts { + language: "python".to_owned(), + has_coverage: false, + has_hazard_rules: false, + has_imports: false, + }, + LanguageFacts { + language: "rust".to_owned(), + has_coverage: true, + has_hazard_rules: true, + has_imports: true, + }, + LanguageFacts { + language: "typescript-javascript".to_owned(), + has_coverage: true, + has_hazard_rules: true, + has_imports: true, + }, + ] + ); +} + +#[test] +fn into_source_sets_preserves_language_facts_in_every_source_set() { + let expected = vec![ + LanguageFacts { + language: "rust".to_owned(), + has_coverage: true, + has_hazard_rules: false, + has_imports: true, + }, + LanguageFacts { + language: "sql".to_owned(), + has_coverage: false, + has_hazard_rules: true, + has_imports: false, + }, + ]; + let model = CodeModel { + files: vec![file_in("src/main.rs", SourceSet::Production)], + languages: expected.clone(), + ..CodeModel::default() + }; + + let source_sets = model.into_source_sets(); + + for source_set in [ + SourceSet::Production, + SourceSet::Test, + SourceSet::Generated, + SourceSet::Vendored, + ] { + assert_eq!(source_sets.get(source_set).languages, expected); + } +} + +#[test] +fn language_plugin_trait_forwards_hazard_rules_and_has_imports_exports() { + let plugin: &dyn LanguagePlugin = &MeasuredLanguage; + + assert!(!plugin.has_hazard_rules()); + assert!(plugin.hazard_rules().is_empty()); + assert!(plugin.has_imports()); +} + +#[test] +fn hazard_line_out_of_range_error_names_plugin_file_and_line() { + let error = LanguagePluginError::HazardLineOutOfRange { + plugin: "hazard-lang".to_owned(), + path: path("queries/bad.haz"), + line: 5, + line_count: 3, + }; + let message = error.to_string(); + + assert!(message.contains("hazard-lang"), "message: {message}"); + assert!(message.contains("queries/bad.haz"), "message: {message}"); + assert!(message.contains("line 5"), "message: {message}"); + assert!(message.contains("3 lines"), "message: {message}"); +} + +#[test] +fn unlisted_hazard_rule_error_names_plugin_file_and_rule() { + let error = LanguagePluginError::UnlistedHazardRule { + plugin: "custom-sql".to_owned(), + path: path("queries/users.sql"), + rule: "unlisted-rule".to_owned(), + }; + + let message = error.to_string(); + + assert!( + message.contains("custom-sql") + && message.contains("queries/users.sql") + && message.contains("unlisted-rule"), + "unexpected error message: {message}" + ); +} diff --git a/crates/plugin-host/HOW-TO.md b/crates/plugin-host/HOW-TO.md index 7f89ea94..4bb93fe4 100644 --- a/crates/plugin-host/HOW-TO.md +++ b/crates/plugin-host/HOW-TO.md @@ -15,7 +15,8 @@ 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` validates its exported WIT interface version against `codeint:plugin@0.3.0` before instantiation; an incompatible version (such as `codeint:plugin@0.2.0`) fails with `PluginHostError::IncompatibleContractVersion`. +- `verify_plugin_component` compiles component bytes and checks the exported WIT contract version and zero-capability sandbox requirements without instantiating or running untrusted guest code. - 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 3d9895ab..45759c28 100644 --- a/crates/plugin-host/src/lib.rs +++ b/crates/plugin-host/src/lib.rs @@ -20,6 +20,8 @@ pub use sha256::{format_hex as sha256_hex, sha256}; pub use wasm::WasmLanguagePlugin; pub use wasm_metric::WasmMetricPlugin; +pub const PLUGIN_INTERFACE_VERSION: &str = "0.3.0"; + #[derive(Debug, thiserror::Error)] pub enum PluginHostError { #[error("cannot read Plugin {name:?} at {}", path.display())] @@ -109,6 +111,18 @@ pub enum PluginHostError { }, } +pub fn verify_plugin_component( + name: &str, + path: &Path, + kind: PluginKind, + bytes: &[u8], +) -> Result<(), PluginHostError> { + match kind { + PluginKind::Language => wasm::verify_language_component(name, path, bytes), + PluginKind::Metric => wasm_metric::verify_metric_component(name, path, bytes), + } +} + pub fn load_language_plugin( repository_root: &Path, declaration: &PluginDeclaration, @@ -274,7 +288,7 @@ impl LanguagePlugin for WasmLanguagePlugin { repository_paths: &[RepoPath], manifests: Vec, requests: Vec, - ) -> Vec { + ) -> Result, LanguagePluginError> { self.resolve_imports_impl(repository_paths, manifests, requests) } @@ -296,6 +310,18 @@ impl LanguagePlugin for WasmLanguagePlugin { fn reference_ranges(&self) -> Result { self.reference_ranges_impl() } + + fn has_hazard_rules(&self) -> bool { + self.has_hazard_rules_impl() + } + + fn hazard_rules(&self) -> Vec { + self.hazard_rules_impl() + } + + fn has_imports(&self) -> bool { + self.has_imports_impl() + } } impl MetricPlugin for WasmMetricPlugin { diff --git a/crates/plugin-host/src/wasm.rs b/crates/plugin-host/src/wasm.rs index 0e75a6d3..84f0f733 100644 --- a/crates/plugin-host/src/wasm.rs +++ b/crates/plugin-host/src/wasm.rs @@ -33,17 +33,17 @@ pub(crate) struct ContractSpec { const LANGUAGE_CONTRACT: ContractSpec = ContractSpec { interface_prefix: "codeint:plugin/language@", - expected_interface: "codeint:plugin/language@0.2.0", + expected_interface: "codeint:plugin/language@0.3.0", }; pub(crate) fn check_contract_version( name: &str, path: &Path, engine: &Engine, - instance_pre: &wasmtime::component::InstancePre, + component: &Component, spec: ContractSpec, ) -> Result<(), PluginHostError> { - let component_type = instance_pre.component().component_type(); + let component_type = component.component_type(); let mut incompatible: Option = None; for (export_name, _) in component_type.exports(engine) { if export_name == spec.expected_interface { @@ -141,15 +141,18 @@ impl InstancePool { pub struct WasmLanguagePlugin { name: String, extensions: Vec, + has_hazard_rules: bool, + hazard_rules: Vec, + has_imports: bool, instances: InstancePool, bindings::LanguagePlugin>, } -pub(crate) fn compile_sandboxed_component( +fn compile_component( name: &str, path: &Path, bytes: &[u8], -) -> Result<(Engine, wasmtime::component::InstancePre), PluginHostError> { +) -> Result<(Engine, Component), PluginHostError> { let mut config = Config::new(); config.wasm_component_model(true); config.epoch_interruption(true); @@ -164,6 +167,20 @@ pub(crate) fn compile_sandboxed_component( path: path.to_path_buf(), reason: error.to_string(), })?; + Ok((engine, component)) +} + +pub(crate) fn prepare_sandboxed_component
(
+    name: &str,
+    path: &Path,
+    bytes: &[u8],
+    spec: ContractSpec,
+    bind: impl FnOnce(
+        wasmtime::component::InstancePre,
+    ) -> Result,
+) -> Result<(Engine, Pre), PluginHostError> {
+    let (engine, component) = compile_component(name, path, bytes)?;
+    check_contract_version(name, path, &engine, &component, spec)?;
     let linker: Linker = Linker::new(&engine);
     let instance_pre =
         linker
@@ -173,7 +190,27 @@ pub(crate) fn compile_sandboxed_component(
                 path: path.to_path_buf(),
                 reason: error.to_string(),
             })?;
-    Ok((engine, instance_pre))
+    let pre = bind(instance_pre).map_err(|error| PluginHostError::Instantiate {
+        name: name.to_owned(),
+        path: path.to_path_buf(),
+        reason: error.to_string(),
+    })?;
+    Ok((engine, pre))
+}
+
+pub(crate) fn verify_language_component(
+    name: &str,
+    path: &Path,
+    bytes: &[u8],
+) -> Result<(), PluginHostError> {
+    prepare_sandboxed_component(
+        name,
+        path,
+        bytes,
+        LANGUAGE_CONTRACT,
+        bindings::LanguagePluginPre::new,
+    )?;
+    Ok(())
 }
 
 pub(crate) struct InstantiatedComponent {
@@ -195,14 +232,8 @@ pub(crate) fn instantiate_sandboxed_component(
     ) -> 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 (engine, pre) = prepare_sandboxed_component(name, path, bytes, spec, bind)?;
     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))?;
@@ -248,9 +279,59 @@ impl WasmLanguagePlugin {
             })?;
         let (ext_count, ext_bytes) = extensions.lifted_budget();
         enforce_lifted_budget(&name, limits, ext_count, ext_bytes)?;
+        arm_call_deadline(&mut component.store, limits);
+        let has_hazard_rules = component
+            .bindings
+            .codeint_plugin_language()
+            .call_has_hazard_rules(&mut component.store)
+            .map_err(|error| {
+                map_host_trap(
+                    &name,
+                    path,
+                    Some("has-hazard-rules"),
+                    limits,
+                    &component.store,
+                    error,
+                )
+            })?;
+        arm_call_deadline(&mut component.store, limits);
+        let hazard_rules = component
+            .bindings
+            .codeint_plugin_language()
+            .call_hazard_rules(&mut component.store)
+            .map_err(|error| {
+                map_host_trap(
+                    &name,
+                    path,
+                    Some("hazard-rules"),
+                    limits,
+                    &component.store,
+                    error,
+                )
+            })?;
+        let (rule_count, rule_bytes) = hazard_rules.lifted_budget();
+        enforce_lifted_budget(&name, limits, rule_count, rule_bytes)?;
+        arm_call_deadline(&mut component.store, limits);
+        let has_imports = component
+            .bindings
+            .codeint_plugin_language()
+            .call_has_imports(&mut component.store)
+            .map_err(|error| {
+                map_host_trap(
+                    &name,
+                    path,
+                    Some("has-imports"),
+                    limits,
+                    &component.store,
+                    error,
+                )
+            })?;
         Ok(WasmLanguagePlugin {
             name,
             extensions,
+            has_hazard_rules,
+            hazard_rules,
+            has_imports,
             instances: InstancePool::from_component(component, limits),
         })
     }
@@ -299,6 +380,18 @@ impl WasmLanguagePlugin {
         self.extensions.clone()
     }
 
+    pub(crate) fn has_hazard_rules_impl(&self) -> bool {
+        self.has_hazard_rules
+    }
+
+    pub(crate) fn hazard_rules_impl(&self) -> Vec {
+        self.hazard_rules.clone()
+    }
+
+    pub(crate) fn has_imports_impl(&self) -> bool {
+        self.has_imports
+    }
+
     pub(crate) fn lower_impl(&self, path: &RepoPath, text: &str) -> Result {
         let lowered = self
             .with_checked_instance("lower", |api, store| {
@@ -360,7 +453,7 @@ impl WasmLanguagePlugin {
         repository_paths: &[RepoPath],
         manifests: Vec,
         requests: Vec,
-    ) -> Vec {
+    ) -> Result, LanguagePluginError> {
         let paths = owned_paths(repository_paths);
         let host_manifests = to_guest_manifests(manifests);
         let host_requests: Vec = requests
@@ -370,11 +463,12 @@ impl WasmLanguagePlugin {
                 specifier: request.specifier,
             })
             .collect();
-        self.with_checked_instance("resolve-imports", |api, store| {
-            api.call_resolve_imports(store, &paths, &host_manifests, &host_requests)
-        })
-        .map(|resolutions| resolutions.into_iter().map(convert_resolution).collect())
-        .unwrap_or_default()
+        let resolutions = self
+            .with_checked_instance("resolve-imports", |api, store| {
+                api.call_resolve_imports(store, &paths, &host_manifests, &host_requests)
+            })
+            .map_err(map_language_plugin_error)?;
+        Ok(resolutions.into_iter().map(convert_resolution).collect())
     }
 
     pub(crate) fn declared_dependencies_impl(
@@ -451,12 +545,21 @@ impl LiftedSize for Vec {
 
 impl LiftedSize for Vec {
     fn lifted_budget(&self) -> (usize, usize) {
-        slice_budget(self, |resolution| match resolution {
-            guest::Resolution::Resolved(text)
-            | guest::Resolution::External(text)
-            | guest::Resolution::Unresolved(text) => text.len(),
-            guest::Resolution::Builtin => 0,
-        })
+        let base_bytes = self.len().saturating_mul(size_of::());
+        self.iter()
+            .fold((self.len(), base_bytes), |(count, bytes), resolution| {
+                let (extra_count, extra_bytes) = match resolution {
+                    guest::Resolution::Resolved(targets) => targets.lifted_budget(),
+                    guest::Resolution::External(text) | guest::Resolution::Unresolved(text) => {
+                        (0, text.len())
+                    }
+                    guest::Resolution::Builtin => (0, 0),
+                };
+                (
+                    count.saturating_add(extra_count),
+                    bytes.saturating_add(extra_bytes),
+                )
+            })
     }
 }
 
@@ -487,15 +590,19 @@ impl LiftedSize for Result {
                 let (token_count, token_bytes) = slice_budget(&model.tokens, |_| 0);
                 let (flag_count, flag_bytes) =
                     slice_budget(&model.flagged_lines, |flagged| flagged.rule.len());
+                let (hazard_count, hazard_bytes) =
+                    slice_budget(&model.hazard_lines, |hazard| hazard.rule.len());
                 let (import_count, import_bytes) = model.runtime_imports.lifted_budget();
                 (
                     fn_count
                         .saturating_add(token_count)
                         .saturating_add(flag_count)
+                        .saturating_add(hazard_count)
                         .saturating_add(import_count),
                     fn_bytes
                         .saturating_add(token_bytes)
                         .saturating_add(flag_bytes)
+                        .saturating_add(hazard_bytes)
                         .saturating_add(import_bytes),
                 )
             }
@@ -566,6 +673,12 @@ fn convert_file_model(model: guest::FileModel) -> FileModel {
                 source_lines: function.source_lines,
                 name: function.name,
                 cognitive_complexity: function.cognitive_complexity,
+                coverage: function
+                    .coverage
+                    .map(|coverage| language::FunctionCoverage {
+                        listed_lines: coverage.listed_lines,
+                        executed_lines: coverage.executed_lines,
+                    }),
             })
             .collect(),
         tokens: model
@@ -585,7 +698,16 @@ fn convert_file_model(model: guest::FileModel) -> FileModel {
                 rule: flagged.rule,
             })
             .collect(),
+        hazard_lines: model
+            .hazard_lines
+            .into_iter()
+            .map(|hazard| language::HazardLine {
+                line: hazard.line,
+                rule: hazard.rule,
+            })
+            .collect(),
         runtime_imports: model.runtime_imports,
+        program_start: model.program_start,
     }
 }
 
@@ -618,7 +740,7 @@ 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::Resolved(paths) => language::Resolution::Resolved(paths),
         guest::Resolution::External(package) => language::Resolution::External(package),
         guest::Resolution::Builtin => language::Resolution::Builtin,
         guest::Resolution::Unresolved(reason) => language::Resolution::Unresolved(reason),
diff --git a/crates/plugin-host/src/wasm_metric.rs b/crates/plugin-host/src/wasm_metric.rs
index 78e346d5..d42f4243 100644
--- a/crates/plugin-host/src/wasm_metric.rs
+++ b/crates/plugin-host/src/wasm_metric.rs
@@ -9,13 +9,31 @@ use wasmtime::Store;
 
 use crate::PluginHostError;
 use crate::limits::{LimitTrap, PluginStoreState, arm_call_deadline, classify_trap};
-use crate::wasm::{ContractSpec, InstancePool, instantiate_sandboxed_component, map_host_trap};
+use crate::wasm::{
+    ContractSpec, InstancePool, instantiate_sandboxed_component, map_host_trap,
+    prepare_sandboxed_component,
+};
 
 const METRIC_CONTRACT: ContractSpec = ContractSpec {
     interface_prefix: "codeint:plugin/metric@",
-    expected_interface: "codeint:plugin/metric@0.2.0",
+    expected_interface: "codeint:plugin/metric@0.3.0",
 };
 
+pub(crate) fn verify_metric_component(
+    name: &str,
+    path: &Path,
+    bytes: &[u8],
+) -> Result<(), PluginHostError> {
+    prepare_sandboxed_component(
+        name,
+        path,
+        bytes,
+        METRIC_CONTRACT,
+        bindings::MetricPluginPre::new,
+    )?;
+    Ok(())
+}
+
 mod bindings {
     wasmtime::component::bindgen!({
         world: "metric-plugin",
@@ -215,9 +233,9 @@ fn to_guest_code_model(model: &CodeModel) -> guest_metric::CodeModel {
                 importer: import.importer.as_str().to_owned(),
                 specifier: import.specifier.clone(),
                 resolution: match &import.resolution {
-                    ImportResolution::Resolved(path) => {
-                        guest_language::Resolution::Resolved(path.as_str().to_owned())
-                    }
+                    ImportResolution::Resolved(paths) => guest_language::Resolution::Resolved(
+                        paths.iter().map(|path| path.as_str().to_owned()).collect(),
+                    ),
                     ImportResolution::External(package) => {
                         guest_language::Resolution::External(package.clone())
                     }
@@ -233,6 +251,16 @@ fn to_guest_code_model(model: &CodeModel) -> guest_metric::CodeModel {
             .member_roots()
             .map(|root| root.as_str().to_owned())
             .collect(),
+        languages: model
+            .languages
+            .iter()
+            .map(|facts| guest_metric::LanguageFacts {
+                language: facts.language.clone(),
+                has_coverage: facts.has_coverage,
+                has_hazard_rules: facts.has_hazard_rules,
+                has_imports: facts.has_imports,
+            })
+            .collect(),
     }
 }
 
@@ -255,6 +283,12 @@ fn to_guest_file_model(model: &FileModel) -> guest_language::FileModel {
                 source_lines: function.source_lines,
                 name: function.name.clone(),
                 cognitive_complexity: function.cognitive_complexity,
+                coverage: function.coverage.as_ref().map(|coverage| {
+                    guest_language::FunctionCoverage {
+                        listed_lines: coverage.listed_lines,
+                        executed_lines: coverage.executed_lines,
+                    }
+                }),
             })
             .collect(),
         tokens: model
@@ -279,7 +313,16 @@ fn to_guest_file_model(model: &FileModel) -> guest_language::FileModel {
                 rule: flagged.rule.clone(),
             })
             .collect(),
+        hazard_lines: model
+            .hazard_lines
+            .iter()
+            .map(|hazard| guest_language::HazardLine {
+                line: hazard.line,
+                rule: hazard.rule.clone(),
+            })
+            .collect(),
         runtime_imports: model.runtime_imports.clone(),
+        program_start: model.program_start,
     }
 }
 
diff --git a/crates/plugin-host/tests/common/mod.rs b/crates/plugin-host/tests/common/mod.rs
index f22d3cfc..6cdb0122 100644
--- a/crates/plugin-host/tests/common/mod.rs
+++ b/crates/plugin-host/tests/common/mod.rs
@@ -6,6 +6,7 @@ use codeint_config::{PluginDeclaration, PluginKind, PluginSource, Sha256Digest};
 use codeint_plugin_host::{sha256, sha256_hex};
 
 static SAMPLE_WASM: OnceLock = OnceLock::new();
+static SANDBOX_PROBES_DIR: OnceLock = OnceLock::new();
 
 pub(crate) fn build_fixture_workspace(
     manifest_relative: &str,
@@ -53,6 +54,18 @@ pub(crate) fn sample_plugin_wasm() -> &'static Path {
     })
 }
 
+pub(crate) fn sandbox_probe_wasm(file_name: &str) -> PathBuf {
+    SANDBOX_PROBES_DIR
+        .get_or_init(|| {
+            build_fixture_workspace(
+                "tests/fixtures/sandbox-probes/Cargo.toml",
+                "wasm-fixtures",
+                true,
+            )
+        })
+        .join(file_name)
+}
+
 pub(crate) fn declaration_for(name: &str, path: &Path) -> PluginDeclaration {
     declaration_with_kind(name, PluginKind::Language, path)
 }
diff --git a/crates/plugin-host/tests/conformance.rs b/crates/plugin-host/tests/conformance.rs
index 8ed5a115..06331fed 100644
--- a/crates/plugin-host/tests/conformance.rs
+++ b/crates/plugin-host/tests/conformance.rs
@@ -9,10 +9,22 @@ use codeint_lang_python::Python;
 use codeint_lang_rust::Rust;
 use codeint_lang_ts::TypeScriptAndJavaScript;
 use codeint_model::language::{ImportRequest, Resolution};
-use codeint_model::{LanguagePlugin, LowerError, Manifest, RepoPath, SourceSet, WorkspaceError};
+use codeint_model::{
+    HazardLine, LanguagePlugin, LowerError, Manifest, RepoPath, SourceSet, WorkspaceError,
+};
 use codeint_plugin_host::load_language_plugin;
 
-use common::{declaration_for, sample_plugin_wasm};
+use common::{declaration_for, sample_plugin_wasm, sandbox_probe_wasm};
+
+struct ImportConformanceFixture<'a> {
+    repository_paths: &'a [&'a str],
+    expected_manifest_path: &'a str,
+    valid_manifests: &'a [(&'a str, &'a str)],
+    expected_workspace_package: &'a str,
+    invalid_manifest_text: &'a str,
+    import_requests: &'a [(&'a str, &'a str)],
+    expected_resolved_targets: &'a [&'a str],
+}
 
 struct ConformanceFixture<'a> {
     name: &'a str,
@@ -26,18 +38,190 @@ struct ConformanceFixture<'a> {
     unparsable_path: &'a str,
     unparsable_source: &'a str,
     unsupported_path: &'a str,
-    repository_paths: &'a [&'a str],
-    expected_manifest_path: &'a str,
-    valid_manifests: &'a [(&'a str, &'a str)],
-    expected_workspace_package: &'a str,
-    invalid_manifest_text: &'a str,
-    import_requests: &'a [(&'a str, &'a str)],
-    expected_resolved_target: &'a str,
+    imports: Option>,
+}
+
+fn assert_valid_hazard_lines(
+    label: &str,
+    file_kind: &str,
+    source: &str,
+    hazard_lines: &[HazardLine],
+    has_hazard_rules: bool,
+    hazard_rules: &[String],
+) {
+    if !has_hazard_rules {
+        assert!(
+            hazard_lines.is_empty(),
+            "{label}: {file_kind} returned hazard_lines when has_hazard_rules is false: {hazard_lines:?}"
+        );
+    }
+    let source_line_count = source.lines().count();
+    for hazard in hazard_lines {
+        assert!(
+            hazard.line >= 1 && (hazard.line as usize) <= source_line_count,
+            "{label}: {file_kind} hazard line {} is outside 1..={source_line_count}",
+            hazard.line
+        );
+        assert!(
+            hazard_rules.iter().any(|rule| rule == &hazard.rule),
+            "{label}: {file_kind} hazard rule {:?} is not listed in hazard_rules ({hazard_rules:?})",
+            hazard.rule
+        );
+    }
+}
+
+fn assert_import_conformance(
+    plugin: &dyn LanguagePlugin,
+    label: &str,
+    imports: &ImportConformanceFixture<'_>,
+) {
+    let repo_paths: Vec = imports
+        .repository_paths
+        .iter()
+        .map(|path| RepoPath::new(*path).unwrap())
+        .collect();
+    let manifest_paths = plugin.manifest_paths(&repo_paths);
+    assert!(
+        manifest_paths.contains(&imports.expected_manifest_path.to_owned()),
+        "{label}: expected manifest {} in {manifest_paths:?}",
+        imports.expected_manifest_path
+    );
+    for chosen in &manifest_paths {
+        assert!(
+            imports.repository_paths.contains(&chosen.as_str()),
+            "{label}: manifest_paths returned {chosen:?} outside repository_paths"
+        );
+    }
+
+    let valid_manifest: Vec = imports
+        .valid_manifests
+        .iter()
+        .map(|(path, text)| Manifest {
+            path: (*path).to_owned(),
+            text: (*text).to_owned(),
+        })
+        .collect();
+    let packages = plugin
+        .workspace_packages(valid_manifest.clone())
+        .unwrap_or_else(|error| panic!("{label}: workspace_packages failed: {error}"));
+    assert_eq!(
+        packages,
+        vec![RepoPath::new(imports.expected_workspace_package).unwrap()],
+        "{label}: workspace_packages"
+    );
+
+    let invalid_manifest = vec![Manifest {
+        path: imports.expected_manifest_path.to_owned(),
+        text: imports.invalid_manifest_text.to_owned(),
+    }];
+    let bad_workspace = plugin.workspace_packages(invalid_manifest);
+    assert!(
+        matches!(bad_workspace, Err(WorkspaceError::Manifest { .. })),
+        "{label}: expected WorkspaceError::Manifest, got {bad_workspace:?}"
+    );
+
+    let requests: Vec = imports
+        .import_requests
+        .iter()
+        .map(|(importer, specifier)| ImportRequest {
+            importer: (*importer).to_owned(),
+            specifier: (*specifier).to_owned(),
+        })
+        .collect();
+    let resolutions = plugin
+        .resolve_imports(&repo_paths, valid_manifest.clone(), requests)
+        .unwrap_or_else(|error| panic!("{label}: resolve_imports failed: {error}"));
+    assert_eq!(
+        resolutions.len(),
+        imports.import_requests.len(),
+        "{label}: resolve_imports length must match requests"
+    );
+    for resolution in &resolutions {
+        if let Resolution::Resolved(targets) = resolution {
+            assert!(
+                !targets.is_empty(),
+                "{label}: Resolution::Resolved must contain at least one repository file"
+            );
+            for target in targets {
+                assert!(
+                    imports.repository_paths.contains(&target.as_str()),
+                    "{label}: resolve_imports returned {target:?} outside repository_paths"
+                );
+            }
+        }
+    }
+    assert_eq!(
+        resolutions[0],
+        Resolution::Resolved(
+            imports
+                .expected_resolved_targets
+                .iter()
+                .map(|target| (*target).to_owned())
+                .collect()
+        ),
+        "{label}: first import resolves"
+    );
+    assert!(
+        matches!(
+            resolutions[1],
+            Resolution::External(_) | Resolution::Builtin
+        ),
+        "{label}: second import is external or builtin, got {:?}",
+        resolutions[1]
+    );
+    assert!(
+        matches!(resolutions[2], Resolution::Unresolved(_)),
+        "{label}: third import is unresolved, got {:?}",
+        resolutions[2]
+    );
+
+    let _deps = plugin
+        .declared_dependencies(valid_manifest.clone())
+        .unwrap_or_else(|error| panic!("{label}: declared_dependencies failed: {error}"));
+    let entry_points = plugin
+        .entry_points(&repo_paths, valid_manifest)
+        .unwrap_or_else(|error| panic!("{label}: entry_points failed: {error}"));
+    for entry in &entry_points {
+        assert!(
+            imports.repository_paths.contains(&entry.as_str()),
+            "{label}: entry_points returned {entry:?} outside repository_paths"
+        );
+    }
 }
 
 fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceFixture<'_>) {
     let label = fixture.name;
+    let has_imports = plugin.has_imports();
+    assert_eq!(
+        fixture.imports.is_some(),
+        has_imports,
+        "{label}: fixture.imports presence must match plugin.has_imports() ({has_imports})"
+    );
+    assert_extensions_and_hazard_rules(plugin, label);
+    let has_hazard_rules = plugin.has_hazard_rules();
+    let hazard_rules = plugin.hazard_rules();
+    assert_edge_case_lowers(plugin, fixture, has_hazard_rules, &hazard_rules);
+    let prod = assert_production_and_crlf_lower(
+        plugin,
+        fixture,
+        has_imports,
+        has_hazard_rules,
+        &hazard_rules,
+    );
+    assert_test_lower(
+        plugin,
+        fixture,
+        has_imports,
+        has_hazard_rules,
+        &hazard_rules,
+    );
+    if let Some(imports) = &fixture.imports {
+        assert_import_conformance(plugin, label, imports);
+    }
+    assert_reference_ranges_and_concurrency(plugin, fixture, &prod);
+}
 
+fn assert_extensions_and_hazard_rules(plugin: &dyn LanguagePlugin, label: &str) {
     let extensions = plugin.extensions();
     assert!(
         !extensions.is_empty(),
@@ -49,7 +233,34 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF
             "{label}: invalid extension {extension:?}"
         );
     }
+    let has_hazard_rules = plugin.has_hazard_rules();
+    let hazard_rules = plugin.hazard_rules();
+    if has_hazard_rules {
+        assert!(
+            !hazard_rules.is_empty(),
+            "{label}: has_hazard_rules is true, so hazard_rules must not be empty"
+        );
+    } else {
+        assert!(
+            hazard_rules.is_empty(),
+            "{label}: has_hazard_rules is false, so hazard_rules must be empty"
+        );
+    }
+    for rule in &hazard_rules {
+        assert!(
+            !rule.is_empty(),
+            "{label}: hazard_rules must not contain empty rule names"
+        );
+    }
+}
 
+fn assert_edge_case_lowers(
+    plugin: &dyn LanguagePlugin,
+    fixture: &ConformanceFixture<'_>,
+    has_hazard_rules: bool,
+    hazard_rules: &[String],
+) {
+    let label = fixture.name;
     let unsupported = plugin.lower(
         &RepoPath::new(fixture.unsupported_path).unwrap(),
         "plain text\n",
@@ -58,7 +269,6 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF
         matches!(unsupported, Err(LowerError::UnsupportedFile { .. })),
         "{label}: expected UnsupportedFile, got {unsupported:?}"
     );
-
     let empty = plugin
         .lower(&RepoPath::new(fixture.empty_path).unwrap(), "")
         .unwrap_or_else(|error| panic!("{label}: empty file failed to lower: {error}"));
@@ -69,11 +279,19 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF
         empty.flagged_lines.is_empty(),
         "{label}: empty flagged_lines"
     );
+    assert!(empty.hazard_lines.is_empty(), "{label}: empty hazard_lines");
     assert!(
         empty.runtime_imports.is_empty(),
         "{label}: empty runtime_imports"
     );
-
+    assert_valid_hazard_lines(
+        label,
+        "empty",
+        "",
+        &empty.hazard_lines,
+        has_hazard_rules,
+        hazard_rules,
+    );
     if let Some((decl_path, decl_source)) = fixture.declaration_only {
         let decl = plugin.lower(&RepoPath::new(decl_path).unwrap(), decl_source);
         assert!(
@@ -81,7 +299,6 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF
             "{label}: expected DeclarationOnly, got {decl:?}"
         );
     }
-
     let unparsable = plugin.lower(
         &RepoPath::new(fixture.unparsable_path).unwrap(),
         fixture.unparsable_source,
@@ -90,7 +307,16 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF
         matches!(&unparsable, Err(LowerError::Unparsable { message }) if !message.is_empty()),
         "{label}: expected Unparsable with message, got {unparsable:?}"
     );
+}
 
+fn assert_production_and_crlf_lower(
+    plugin: &dyn LanguagePlugin,
+    fixture: &ConformanceFixture<'_>,
+    has_imports: bool,
+    has_hazard_rules: bool,
+    hazard_rules: &[String],
+) -> codeint_model::FileModel {
+    let label = fixture.name;
     let prod_path = RepoPath::new(fixture.production_path).unwrap();
     let prod = plugin
         .lower(&prod_path, fixture.production_source)
@@ -103,10 +329,50 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF
     assert!(prod.source_lines > 0, "{label}: production source_lines");
     assert!(!prod.functions.is_empty(), "{label}: production functions");
     assert!(!prod.tokens.is_empty(), "{label}: production tokens");
-    assert!(
-        !prod.runtime_imports.is_empty(),
-        "{label}: production runtime_imports"
+    if has_imports {
+        assert!(
+            !prod.runtime_imports.is_empty(),
+            "{label}: production runtime_imports"
+        );
+    } else {
+        assert!(
+            prod.runtime_imports.is_empty(),
+            "{label}: production runtime_imports must be empty when has_imports is false"
+        );
+    }
+    assert_file_model_ordering_and_spans(label, &prod);
+    assert_valid_hazard_lines(
+        label,
+        "production",
+        fixture.production_source,
+        &prod.hazard_lines,
+        has_hazard_rules,
+        hazard_rules,
+    );
+    let crlf = plugin
+        .lower(&prod_path, fixture.production_source_crlf)
+        .unwrap_or_else(|error| panic!("{label}: CRLF file failed to lower: {error}"));
+    assert_eq!(
+        crlf.source_lines, prod.source_lines,
+        "{label}: CRLF source_lines"
+    );
+    assert_eq!(crlf.functions, prod.functions, "{label}: CRLF functions");
+    assert_eq!(
+        crlf.hazard_lines, prod.hazard_lines,
+        "{label}: CRLF hazard_lines"
+    );
+    assert_valid_hazard_lines(
+        label,
+        "production CRLF",
+        fixture.production_source_crlf,
+        &crlf.hazard_lines,
+        has_hazard_rules,
+        hazard_rules,
     );
+    prod
+}
+
+fn assert_file_model_ordering_and_spans(label: &str, prod: &codeint_model::FileModel) {
     for pair in prod.functions.windows(2) {
         assert!(
             pair[0].line <= pair[1].line,
@@ -118,6 +384,10 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF
             function.line >= 1 && function.line <= function.end_line,
             "{label}: invalid function span {function:?}"
         );
+        assert_eq!(
+            function.coverage, None,
+            "{label}: Language plugin must leave function coverage absent"
+        );
     }
     for pair in prod.tokens.windows(2) {
         assert!(pair[0].line <= pair[1].line, "{label}: tokens out of order");
@@ -128,16 +398,16 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF
             "{label}: invalid flagged line"
         );
     }
+}
 
-    let crlf = plugin
-        .lower(&prod_path, fixture.production_source_crlf)
-        .unwrap_or_else(|error| panic!("{label}: CRLF file failed to lower: {error}"));
-    assert_eq!(
-        crlf.source_lines, prod.source_lines,
-        "{label}: CRLF source_lines"
-    );
-    assert_eq!(crlf.functions, prod.functions, "{label}: CRLF functions");
-
+fn assert_test_lower(
+    plugin: &dyn LanguagePlugin,
+    fixture: &ConformanceFixture<'_>,
+    has_imports: bool,
+    has_hazard_rules: bool,
+    hazard_rules: &[String],
+) {
+    let label = fixture.name;
     let test_model = plugin
         .lower(
             &RepoPath::new(fixture.test_path).unwrap(),
@@ -149,98 +419,34 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF
         SourceSet::Test,
         "{label}: test source_set"
     );
-
-    let repo_paths: Vec = fixture
-        .repository_paths
-        .iter()
-        .map(|path| RepoPath::new(*path).unwrap())
-        .collect();
-    let manifest_paths = plugin.manifest_paths(&repo_paths);
-    assert!(
-        manifest_paths.contains(&fixture.expected_manifest_path.to_owned()),
-        "{label}: expected manifest {} in {manifest_paths:?}",
-        fixture.expected_manifest_path
-    );
-    for chosen in &manifest_paths {
-        assert!(
-            fixture.repository_paths.contains(&chosen.as_str()),
-            "{label}: manifest_paths returned {chosen:?} outside repository_paths"
+    for function in &test_model.functions {
+        assert_eq!(
+            function.coverage, None,
+            "{label}: Language plugin must leave test function coverage absent"
         );
     }
-
-    let valid_manifest: Vec = fixture
-        .valid_manifests
-        .iter()
-        .map(|(path, text)| Manifest {
-            path: (*path).to_owned(),
-            text: (*text).to_owned(),
-        })
-        .collect();
-    let packages = plugin
-        .workspace_packages(valid_manifest.clone())
-        .unwrap_or_else(|error| panic!("{label}: workspace_packages failed: {error}"));
-    assert_eq!(
-        packages,
-        vec![RepoPath::new(fixture.expected_workspace_package).unwrap()],
-        "{label}: workspace_packages"
-    );
-
-    let invalid_manifest = vec![Manifest {
-        path: fixture.expected_manifest_path.to_owned(),
-        text: fixture.invalid_manifest_text.to_owned(),
-    }];
-    let bad_workspace = plugin.workspace_packages(invalid_manifest);
-    assert!(
-        matches!(bad_workspace, Err(WorkspaceError::Manifest { .. })),
-        "{label}: expected WorkspaceError::Manifest, got {bad_workspace:?}"
-    );
-
-    let requests: Vec = fixture
-        .import_requests
-        .iter()
-        .map(|(importer, specifier)| ImportRequest {
-            importer: (*importer).to_owned(),
-            specifier: (*specifier).to_owned(),
-        })
-        .collect();
-    let resolutions = plugin.resolve_imports(&repo_paths, valid_manifest.clone(), requests);
-    assert_eq!(
-        resolutions.len(),
-        fixture.import_requests.len(),
-        "{label}: resolve_imports length must match requests"
-    );
-    assert_eq!(
-        resolutions[0],
-        Resolution::Resolved(fixture.expected_resolved_target.to_owned()),
-        "{label}: first import resolves"
-    );
-    assert!(
-        matches!(
-            resolutions[1],
-            Resolution::External(_) | Resolution::Builtin
-        ),
-        "{label}: second import is external or builtin, got {:?}",
-        resolutions[1]
-    );
-    assert!(
-        matches!(resolutions[2], Resolution::Unresolved(_)),
-        "{label}: third import is unresolved, got {:?}",
-        resolutions[2]
+    assert_valid_hazard_lines(
+        label,
+        "test",
+        fixture.test_source,
+        &test_model.hazard_lines,
+        has_hazard_rules,
+        hazard_rules,
     );
-
-    let _deps = plugin
-        .declared_dependencies(valid_manifest.clone())
-        .unwrap_or_else(|error| panic!("{label}: declared_dependencies failed: {error}"));
-    let entry_points = plugin
-        .entry_points(&repo_paths, valid_manifest)
-        .unwrap_or_else(|error| panic!("{label}: entry_points failed: {error}"));
-    for entry in &entry_points {
+    if !has_imports {
         assert!(
-            fixture.repository_paths.contains(&entry.as_str()),
-            "{label}: entry_points returned {entry:?} outside repository_paths"
+            test_model.runtime_imports.is_empty(),
+            "{label}: test runtime_imports must be empty when has_imports is false"
         );
     }
+}
 
+fn assert_reference_ranges_and_concurrency(
+    plugin: &dyn LanguagePlugin,
+    fixture: &ConformanceFixture<'_>,
+    prod: &codeint_model::FileModel,
+) {
+    let label = fixture.name;
     let ranges = plugin
         .reference_ranges()
         .unwrap_or_else(|error| panic!("{label}: reference_ranges failed: {error}"));
@@ -248,7 +454,7 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF
         ranges.for_metric("erosion").is_some(),
         "{label}: expected erosion reference range"
     );
-
+    let prod_path = RepoPath::new(fixture.production_path).unwrap();
     std::thread::scope(|scope| {
         let handles: Vec<_> = (0..4)
             .map(|_| {
@@ -261,7 +467,7 @@ fn assert_seam_2_conformance(plugin: &dyn LanguagePlugin, fixture: &ConformanceF
             .collect();
         for handle in handles {
             assert_eq!(
-                handle.join().unwrap(),
+                &handle.join().unwrap(),
                 prod,
                 "{label}: concurrent lower mismatch"
             );
@@ -286,25 +492,27 @@ fn built_in_typescript_javascript_plugin_passes_seam_2_conformance() {
         unparsable_path: "packages/app/src/broken.ts",
         unparsable_source: "export const = ;\n",
         unsupported_path: "scripts/tool.unknown",
-        repository_paths: &[
-            "package.json",
-            "packages/app/package.json",
-            "packages/app/src/main.ts",
-            "packages/app/src/helper.ts",
-        ],
-        expected_manifest_path: "package.json",
-        valid_manifests: &[
-            ("package.json", r#"{"workspaces": ["packages/app"]}"#),
-            ("packages/app/package.json", r#"{"name": "@sample/app"}"#),
-        ],
-        expected_workspace_package: "packages/app",
-        invalid_manifest_text: "{not json",
-        import_requests: &[
-            ("packages/app/src/main.ts", "./helper"),
-            ("packages/app/src/main.ts", "node:path"),
-            ("packages/app/src/main.ts", "./missing"),
-        ],
-        expected_resolved_target: "packages/app/src/helper.ts",
+        imports: Some(ImportConformanceFixture {
+            repository_paths: &[
+                "package.json",
+                "packages/app/package.json",
+                "packages/app/src/main.ts",
+                "packages/app/src/helper.ts",
+            ],
+            expected_manifest_path: "package.json",
+            valid_manifests: &[
+                ("package.json", r#"{"workspaces": ["packages/app"]}"#),
+                ("packages/app/package.json", r#"{"name": "@sample/app"}"#),
+            ],
+            expected_workspace_package: "packages/app",
+            invalid_manifest_text: "{not json",
+            import_requests: &[
+                ("packages/app/src/main.ts", "./helper"),
+                ("packages/app/src/main.ts", "node:path"),
+                ("packages/app/src/main.ts", "./missing"),
+            ],
+            expected_resolved_targets: &["packages/app/src/helper.ts"],
+        }),
     };
 
     assert_seam_2_conformance(&TypeScriptAndJavaScript, &fixture);
@@ -329,21 +537,23 @@ fn sample_external_wasm_plugin_passes_seam_2_conformance() {
         unparsable_path: "packages/app/src/broken.mini",
         unparsable_source: "SYNTAX_ERROR\n",
         unsupported_path: "scripts/tool.unknown",
-        repository_paths: &[
-            "mini.workspace",
-            "packages/app/src/main.mini",
-            "packages/app/src/helper.mini",
-        ],
-        expected_manifest_path: "mini.workspace",
-        valid_manifests: &[("mini.workspace", "packages/app\n")],
-        expected_workspace_package: "packages/app",
-        invalid_manifest_text: "INVALID: bad workspace entry\n",
-        import_requests: &[
-            ("packages/app/src/main.mini", "./helper"),
-            ("packages/app/src/main.mini", "external-lib"),
-            ("packages/app/src/main.mini", "./missing"),
-        ],
-        expected_resolved_target: "packages/app/src/helper.mini",
+        imports: Some(ImportConformanceFixture {
+            repository_paths: &[
+                "mini.workspace",
+                "packages/app/src/main.mini",
+                "packages/app/src/helper.mini",
+            ],
+            expected_manifest_path: "mini.workspace",
+            valid_manifests: &[("mini.workspace", "packages/app\n")],
+            expected_workspace_package: "packages/app",
+            invalid_manifest_text: "INVALID: bad workspace entry\n",
+            import_requests: &[
+                ("packages/app/src/main.mini", "./helper"),
+                ("packages/app/src/main.mini", "external-lib"),
+                ("packages/app/src/main.mini", "./missing"),
+            ],
+            expected_resolved_targets: &["packages/app/src/helper.mini"],
+        }),
     };
 
     assert_seam_2_conformance(&plugin, &fixture);
@@ -427,13 +637,15 @@ fn run_simple_conformance(
             unparsable_path: files.5,
             unparsable_source: files.6,
             unsupported_path: "scripts/tool.unknown",
-            repository_paths: workspace.3,
-            expected_manifest_path: workspace.0,
-            valid_manifests: workspace.4,
-            expected_workspace_package: workspace.1,
-            invalid_manifest_text: workspace.2,
-            import_requests: workspace.5,
-            expected_resolved_target: files.1,
+            imports: Some(ImportConformanceFixture {
+                repository_paths: workspace.3,
+                expected_manifest_path: workspace.0,
+                valid_manifests: workspace.4,
+                expected_workspace_package: workspace.1,
+                invalid_manifest_text: workspace.2,
+                import_requests: workspace.5,
+                expected_resolved_targets: &[files.1],
+            }),
         },
     );
 }
@@ -475,13 +687,15 @@ fn built_in_php_plugin_passes_seam_2_conformance() {
         unparsable_path: "packages/app/src/Broken.php",
         unparsable_source: " codeint_plugin_host::WasmLanguagePlugin {
+    let declaration = declaration_for(name, wasm_path);
+    load_language_plugin(Path::new("."), &declaration, &PluginHostConfig::default())
+        .unwrap_or_else(|error| panic!("{name} external wasm plugin failed to load: {error}"))
+}
+
+fn assert_sandbox_probe_conformance(
+    name: &str,
+    wasm_file: &str,
+    prefix: &str,
+    extension: &str,
+    production_source: &str,
+    imports: Option>,
+) {
+    let wasm_path = sandbox_probe_wasm(wasm_file);
+    let plugin = load_external_plugin(name, &wasm_path);
+    let production_source_crlf = production_source.replace('\n', "\r\n");
+    let production_path = format!("{prefix}/main.{extension}");
+    let test_path = format!("{prefix}/main_test.{extension}");
+    let empty_path = format!("{prefix}/empty.{extension}");
+    let unparsable_path = format!("{prefix}/broken.{extension}");
+    assert_seam_2_conformance(
+        &plugin,
+        &ConformanceFixture {
+            name,
+            production_path: &production_path,
+            production_source,
+            production_source_crlf: &production_source_crlf,
+            test_path: &test_path,
+            test_source: "fn check()\n",
+            empty_path: &empty_path,
+            declaration_only: None,
+            unparsable_path: &unparsable_path,
+            unparsable_source: "SYNTAX_ERROR\n",
+            unsupported_path: "scripts/tool.unknown",
+            imports,
+        },
+    );
+}
+
+#[test]
+fn folder_import_external_wasm_plugin_passes_seam_2_conformance() {
+    let alpha = "packages/app/util/alpha.fld";
+    let beta = "packages/app/util/beta.fld";
+    let repo_paths = ["fld.workspace", "packages/app/main.fld", alpha, beta];
+    let resolved_targets = [alpha, beta];
+    assert_sandbox_probe_conformance(
+        "folder-import",
+        "folder_import_language_plugin.wasm",
+        "packages/app",
+        "fld",
+        "use packages/app/util\n\n# comment\nfn run()\n",
+        Some(ImportConformanceFixture {
+            repository_paths: &repo_paths,
+            expected_manifest_path: "fld.workspace",
+            valid_manifests: &[(
+                "fld.workspace",
+                "packages/app\nentry:packages/app/main.fld\n",
+            )],
+            expected_workspace_package: "packages/app",
+            invalid_manifest_text: "INVALID: bad workspace entry\n",
+            import_requests: &[
+                ("packages/app/main.fld", "packages/app/util"),
+                ("packages/app/main.fld", "ext:external-lib"),
+                ("packages/app/main.fld", "packages/app/missing"),
+            ],
+            expected_resolved_targets: &resolved_targets,
+        }),
+    );
+}
+
+#[test]
+fn no_imports_external_wasm_plugin_passes_seam_2_conformance() {
+    assert_sandbox_probe_conformance(
+        "no-imports",
+        "no_imports_language_plugin.wasm",
+        "queries",
+        "noimp",
+        "# comment\nfn run()\nselect_rows\n",
+        None,
+    );
+}
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 aedf9bda..81cd614d 100644
--- a/crates/plugin-host/tests/fixtures/sample-plugin/src/lib.rs
+++ b/crates/plugin-host/tests/fixtures/sample-plugin/src/lib.rs
@@ -334,6 +334,7 @@ fn push_function_header(
         source_lines: 0,
         name: name.clone(),
         cognitive_complexity: 0,
+        coverage: None,
     });
     stack.push(OpenFunction {
         slot,
@@ -390,11 +391,97 @@ fn update_function_stack(
             source_lines: finished.source_lines,
             name: finished.name,
             cognitive_complexity: finished.cognitive_complexity,
+            coverage: None,
         };
     }
     Ok(())
 }
 
+struct LowerState {
+    source_lines: u32,
+    functions: Vec,
+    stack: Vec,
+    tokens: Vec,
+    flagged_lines: Vec,
+    runtime_imports: Vec,
+}
+
+impl LowerState {
+    fn new() -> Self {
+        Self {
+            source_lines: 0,
+            functions: Vec::new(),
+            stack: Vec::new(),
+            tokens: Vec::new(),
+            flagged_lines: Vec::new(),
+            runtime_imports: Vec::new(),
+        }
+    }
+
+    fn lower_line(&mut self, line_number: u32, raw_line: &str) -> Result<(), LowerError> {
+        let code = strip_comment(raw_line);
+        let trimmed = code.trim();
+        if trimmed.is_empty() {
+            return Ok(());
+        }
+        if trimmed.contains("SYNTAX_ERROR") {
+            return Err(LowerError::Unparsable(format!(
+                "syntax error at line {line_number}"
+            )));
+        }
+        self.source_lines = self
+            .source_lines
+            .checked_add(1)
+            .ok_or(LowerError::TooLarge)?;
+        let is_import = if let Some(specifier) = extract_import_specifier(trimmed) {
+            self.runtime_imports.push(specifier);
+            true
+        } else {
+            false
+        };
+        if trimmed == "pass;" {
+            self.flagged_lines.push(FlaggedLine {
+                line: line_number,
+                rule: "redundant-pass".to_string(),
+            });
+        }
+        tokenize_line(code, line_number, is_import, &mut self.tokens);
+        push_function_header(trimmed, line_number, &mut self.functions, &mut self.stack);
+        update_function_stack(
+            code,
+            trimmed,
+            line_number,
+            &mut self.functions,
+            &mut self.stack,
+        )
+    }
+}
+
+fn resolve_single_import(repository_paths: &[String], request: ImportRequest) -> Resolution {
+    if request.specifier.starts_with("std:") {
+        return Resolution::Builtin;
+    }
+    let Some(relative) = request.specifier.strip_prefix("./") else {
+        return Resolution::External(request.specifier);
+    };
+    let candidate = match request.importer.rsplit_once('/') {
+        Some((dir, _)) => format!("{dir}/{relative}"),
+        None => relative.to_string(),
+    };
+    let with_ext = if candidate.ends_with(".mini") {
+        candidate.clone()
+    } else {
+        format!("{candidate}.mini")
+    };
+    if repository_paths.iter().any(|path| path == &candidate) {
+        Resolution::Resolved(vec![candidate])
+    } else if repository_paths.iter().any(|path| path == &with_ext) {
+        Resolution::Resolved(vec![with_ext])
+    } else {
+        Resolution::Unresolved(format!("cannot find {with_ext}"))
+    }
+}
+
 impl Guest for SampleMiniPlugin {
     fn extensions() -> Vec {
         vec!["mini".to_string()]
@@ -410,60 +497,25 @@ impl Guest for SampleMiniPlugin {
         if file_name.ends_with(".d.mini") {
             return Err(LowerError::DeclarationOnly);
         }
-
-        let mut source_lines: u32 = 0;
-        let mut functions: Vec = Vec::new();
-        let mut stack: Vec = Vec::new();
-        let mut tokens: Vec = Vec::new();
-        let mut flagged_lines: Vec = Vec::new();
-        let mut runtime_imports: Vec = Vec::new();
-
+        let mut state = LowerState::new();
         for (zero_based, raw_line) in text.lines().enumerate() {
             let line_number = u32::try_from(zero_based + 1).map_err(|_| LowerError::TooLarge)?;
-            let code = strip_comment(raw_line);
-            let trimmed = code.trim();
-            if trimmed.is_empty() {
-                continue;
-            }
-            if trimmed.contains("SYNTAX_ERROR") {
-                return Err(LowerError::Unparsable(format!(
-                    "syntax error at line {line_number}"
-                )));
-            }
-            source_lines = source_lines.checked_add(1).ok_or(LowerError::TooLarge)?;
-
-            let is_import = if let Some(specifier) = extract_import_specifier(trimmed) {
-                runtime_imports.push(specifier);
-                true
-            } else {
-                false
-            };
-
-            if trimmed == "pass;" {
-                flagged_lines.push(FlaggedLine {
-                    line: line_number,
-                    rule: "redundant-pass".to_string(),
-                });
-            }
-
-            tokenize_line(code, line_number, is_import, &mut tokens);
-            push_function_header(trimmed, line_number, &mut functions, &mut stack);
-            update_function_stack(code, trimmed, line_number, &mut functions, &mut stack)?;
+            state.lower_line(line_number, raw_line)?;
         }
-
-        if !stack.is_empty() {
+        if !state.stack.is_empty() {
             return Err(LowerError::Unparsable(
                 "unclosed function block".to_string(),
             ));
         }
-
         Ok(FileModel {
             source_set: source_set_of(&path),
-            source_lines,
-            functions,
-            tokens,
-            flagged_lines,
-            runtime_imports,
+            source_lines: state.source_lines,
+            functions: state.functions,
+            tokens: state.tokens,
+            flagged_lines: state.flagged_lines,
+            hazard_lines: Vec::new(),
+            runtime_imports: state.runtime_imports,
+            program_start: false,
         })
     }
 
@@ -505,36 +557,7 @@ impl Guest for SampleMiniPlugin {
     ) -> Vec {
         requests
             .into_iter()
-            .map(|request| {
-                if request.specifier.starts_with("std:") {
-                    return Resolution::Builtin;
-                }
-                if !request.specifier.starts_with("./") {
-                    return Resolution::External(request.specifier);
-                }
-                let relative = request.specifier.trim_start_matches("./");
-                let folder = match request.importer.rsplit_once('/') {
-                    Some((dir, _)) => dir,
-                    None => "",
-                };
-                let candidate = if folder.is_empty() {
-                    relative.to_string()
-                } else {
-                    format!("{folder}/{relative}")
-                };
-                let with_ext = if candidate.ends_with(".mini") {
-                    candidate.clone()
-                } else {
-                    format!("{candidate}.mini")
-                };
-                if repository_paths.iter().any(|path| path == &candidate) {
-                    Resolution::Resolved(candidate)
-                } else if repository_paths.iter().any(|path| path == &with_ext) {
-                    Resolution::Resolved(with_ext)
-                } else {
-                    Resolution::Unresolved(format!("cannot find {with_ext}"))
-                }
-            })
+            .map(|request| resolve_single_import(&repository_paths, request))
             .collect()
     }
 
@@ -595,4 +618,16 @@ impl Guest for SampleMiniPlugin {
             source: "sample mini language fixture".to_string(),
         }]
     }
+
+    fn has_hazard_rules() -> bool {
+        false
+    }
+
+    fn hazard_rules() -> Vec {
+        Vec::new()
+    }
+
+    fn has_imports() -> bool {
+        true
+    }
 }
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.lock b/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.lock
index cbdc5643..c3e0f2a8 100644
--- a/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.lock
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.lock
@@ -22,6 +22,14 @@ dependencies = [
  "wit-bindgen",
 ]
 
+[[package]]
+name = "coverage-reader-metric-plugin"
+version = "0.1.0"
+dependencies = [
+ "probe-runtime",
+ "wit-bindgen",
+]
+
 [[package]]
 name = "dual-version-language-plugin"
 version = "0.1.0"
@@ -44,6 +52,14 @@ dependencies = [
  "wit-bindgen",
 ]
 
+[[package]]
+name = "folder-import-language-plugin"
+version = "0.1.0"
+dependencies = [
+ "probe-runtime",
+ "wit-bindgen",
+]
+
 [[package]]
 name = "foldhash"
 version = "0.2.0"
@@ -59,6 +75,22 @@ dependencies = [
  "foldhash",
 ]
 
+[[package]]
+name = "hazard-facts-metric-plugin"
+version = "0.1.0"
+dependencies = [
+ "probe-runtime",
+ "wit-bindgen",
+]
+
+[[package]]
+name = "hazard-rules-language-plugin"
+version = "0.1.0"
+dependencies = [
+ "probe-runtime",
+ "wit-bindgen",
+]
+
 [[package]]
 name = "heck"
 version = "0.5.0"
@@ -71,6 +103,22 @@ version = "2.3.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
 
+[[package]]
+name = "import-capability-metric-plugin"
+version = "0.1.0"
+dependencies = [
+ "probe-runtime",
+ "wit-bindgen",
+]
+
+[[package]]
+name = "imports-reader-metric-plugin"
+version = "0.1.0"
+dependencies = [
+ "probe-runtime",
+ "wit-bindgen",
+]
+
 [[package]]
 name = "indexmap"
 version = "2.14.2"
@@ -111,6 +159,22 @@ dependencies = [
  "wit-bindgen",
 ]
 
+[[package]]
+name = "legacy-v0-2-0-language-plugin"
+version = "0.1.0"
+dependencies = [
+ "probe-runtime",
+ "wit-bindgen",
+]
+
+[[package]]
+name = "legacy-v0-2-0-metric-plugin"
+version = "0.1.0"
+dependencies = [
+ "probe-runtime",
+ "wit-bindgen",
+]
+
 [[package]]
 name = "log"
 version = "0.4.35"
@@ -147,6 +211,14 @@ dependencies = [
  "wit-bindgen",
 ]
 
+[[package]]
+name = "no-imports-language-plugin"
+version = "0.1.0"
+dependencies = [
+ "probe-runtime",
+ "wit-bindgen",
+]
+
 [[package]]
 name = "prettyplease"
 version = "0.3.0"
@@ -170,6 +242,22 @@ dependencies = [
  "unicode-ident",
 ]
 
+[[package]]
+name = "program-start-language-plugin"
+version = "0.1.0"
+dependencies = [
+ "probe-runtime",
+ "wit-bindgen",
+]
+
+[[package]]
+name = "program-start-metric-plugin"
+version = "0.1.0"
+dependencies = [
+ "probe-runtime",
+ "wit-bindgen",
+]
+
 [[package]]
 name = "quote"
 version = "1.0.47"
@@ -252,6 +340,14 @@ version = "1.0.27"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
 
+[[package]]
+name = "unlisted-hazard-rule-language-plugin"
+version = "0.1.0"
+dependencies = [
+ "probe-runtime",
+ "wit-bindgen",
+]
+
 [[package]]
 name = "wasm-encoder"
 version = "0.262.0"
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml
index 663993ab..200c033f 100644
--- a/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/Cargo.toml
@@ -10,7 +10,19 @@ members = [
     "loop-metric",
     "legacy-v0-1-0-language",
     "legacy-v0-1-0-metric",
+    "legacy-v0-2-0-language",
+    "legacy-v0-2-0-metric",
     "dual-version-language",
+    "coverage-reader-metric",
+    "program-start-language",
+    "program-start-metric",
+    "hazard-rules-language",
+    "hazard-facts-metric",
+    "folder-import-language",
+    "imports-reader-metric",
+    "unlisted-hazard-rule-language",
+    "no-imports-language",
+    "import-capability-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 d8d1c1bc..1e92f7c5 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
@@ -76,4 +76,16 @@ impl Guest for ClockReaderPlugin {
     fn reference_ranges() -> Vec {
         Vec::new()
     }
+
+    fn has_hazard_rules() -> bool {
+        false
+    }
+
+    fn hazard_rules() -> Vec {
+        Vec::new()
+    }
+
+    fn has_imports() -> bool {
+        true
+    }
 }
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/coverage-reader-metric/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/coverage-reader-metric/Cargo.toml
new file mode 100644
index 00000000..67bbf32e
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/coverage-reader-metric/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "coverage-reader-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/coverage-reader-metric/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/coverage-reader-metric/src/lib.rs
new file mode 100644
index 00000000..70b027bc
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/coverage-reader-metric/src/lib.rs
@@ -0,0 +1,105 @@
+#![no_std]
+
+extern crate alloc;
+extern crate probe_runtime;
+
+use alloc::format;
+use alloc::string::{String, ToString};
+use alloc::vec::Vec;
+
+wit_bindgen::generate!({
+    world: "metric-plugin",
+    path: "../../../../../../wit",
+});
+
+use self::codeint::plugin::language::Function;
+use exports::codeint::plugin::metric::{CodeModel, Finding, Guest, Measurement};
+
+struct CoverageReaderMetricPlugin;
+
+export!(CoverageReaderMetricPlugin);
+
+fn finding_for_function(
+    file_path: &str,
+    function: &Function,
+    total_listed: &mut u64,
+    total_unexecuted: &mut u64,
+) -> Finding {
+    let label = function.name.as_deref().unwrap_or("anonymous");
+    let (id, message) = match &function.coverage {
+        None => (format!("absent:{label}"), "absent".to_string()),
+        Some(coverage) => {
+            let unexecuted = coverage
+                .listed_lines
+                .saturating_sub(coverage.executed_lines);
+            *total_listed += u64::from(coverage.listed_lines);
+            *total_unexecuted += u64::from(unexecuted);
+            let prefix = if coverage.executed_lines == 0 {
+                "zero"
+            } else {
+                "covered"
+            };
+            (
+                format!("{prefix}:{label}"),
+                format!(
+                    "listed={} executed={}",
+                    coverage.listed_lines, coverage.executed_lines
+                ),
+            )
+        }
+    };
+    Finding {
+        id,
+        path: file_path.to_string(),
+        line: function.line,
+        end_line: Some(function.end_line),
+        message,
+    }
+}
+
+impl Guest for CoverageReaderMetricPlugin {
+    fn key() -> String {
+        "coverage_reader".to_string()
+    }
+
+    fn name() -> String {
+        "Coverage reader".to_string()
+    }
+
+    fn description() -> String {
+        "Test Metric plugin that reads per-function and per-language coverage facts".to_string()
+    }
+
+    fn measure(model: CodeModel) -> Measurement {
+        let mut total_listed: u64 = 0;
+        let mut total_unexecuted: u64 = 0;
+        let mut findings = Vec::new();
+        for file in &model.files {
+            for function in &file.model.functions {
+                findings.push(finding_for_function(
+                    &file.path,
+                    function,
+                    &mut total_listed,
+                    &mut total_unexecuted,
+                ));
+            }
+        }
+        let (_, language_findings) = probe_runtime::language_fact_findings!(
+            &model.languages,
+            "language",
+            "has_coverage",
+            "covered",
+            "absent",
+            |facts: &self::exports::codeint::plugin::metric::LanguageFacts| facts.has_coverage
+        );
+        findings.extend(language_findings);
+        let numerator = total_unexecuted as f64;
+        let denominator = total_listed as f64;
+        Measurement {
+            ratio: probe_runtime::ratio(numerator, denominator),
+            numerator,
+            denominator,
+            findings,
+        }
+    }
+}
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/dual-version-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/dual-version-language/src/lib.rs
index bfcf5cfc..9e2e72f8 100644
--- a/crates/plugin-host/tests/fixtures/sandbox-probes/dual-version-language/src/lib.rs
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/dual-version-language/src/lib.rs
@@ -10,20 +10,22 @@ use alloc::vec::Vec;
 wit_bindgen::generate!({
     world: "dual-language-plugin",
     inline: "
-        package codeint:dual@0.2.0;
+        package codeint:dual@0.3.0;
 
         world dual-language-plugin {
-            export codeint:plugin/language@0.1.0;
             export codeint:plugin/language@0.2.0;
+            export codeint:plugin/language@0.3.0;
         }
 
-        package codeint:plugin@0.1.0 {
+        package codeint:plugin@0.2.0 {
             interface language {
                 record function {
                     line: u32,
                     end-line: u32,
                     decision-points: u32,
                     source-lines: u32,
+                    name: option,
+                    cognitive-complexity: u32,
                 }
 
                 enum token-kind {
@@ -67,10 +69,23 @@ wit_bindgen::generate!({
 
                 variant resolution {
                     resolved(string),
-                    external,
+                    external(string),
+                    builtin,
                     unresolved(string),
                 }
 
+                enum dep-kind {
+                    runtime,
+                    dev,
+                    optional,
+                }
+
+                record declared-dep {
+                    package-root: string,
+                    name: string,
+                    kind: dep-kind,
+                }
+
                 variant lower-error {
                     unparsable(string),
                     unsupported-file(string),
@@ -100,12 +115,19 @@ wit_bindgen::generate!({
                 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;
+                declared-dependencies: func(manifests: list) -> list;
+                entry-points: func(repository-paths: list, manifests: list) -> list;
                 reference-ranges: func() -> list;
             }
         }
 
-        package codeint:plugin@0.2.0 {
+        package codeint:plugin@0.3.0 {
             interface language {
+                record function-coverage {
+                    listed-lines: u32,
+                    executed-lines: u32,
+                }
+
                 record function {
                     line: u32,
                     end-line: u32,
@@ -113,6 +135,7 @@ wit_bindgen::generate!({
                     source-lines: u32,
                     name: option,
                     cognitive-complexity: u32,
+                    coverage: option,
                 }
 
                 enum token-kind {
@@ -140,13 +163,20 @@ wit_bindgen::generate!({
                     rule: string,
                 }
 
+                record hazard-line {
+                    line: u32,
+                    rule: string,
+                }
+
                 record file-model {
                     source-set: source-set,
                     source-lines: u32,
                     functions: list,
                     tokens: list,
                     flagged-lines: list,
+                    hazard-lines: list,
                     runtime-imports: list,
+                    program-start: bool,
                 }
 
                 record import-request {
@@ -155,7 +185,7 @@ wit_bindgen::generate!({
                 }
 
                 variant resolution {
-                    resolved(string),
+                    resolved(list),
                     external(string),
                     builtin,
                     unresolved(string),
@@ -205,6 +235,9 @@ wit_bindgen::generate!({
                 declared-dependencies: func(manifests: list) -> list;
                 entry-points: func(repository-paths: list, manifests: list) -> list;
                 reference-ranges: func() -> list;
+                has-hazard-rules: func() -> bool;
+                hazard-rules: func() -> list;
+                has-imports: func() -> bool;
             }
         }
     ",
@@ -215,7 +248,7 @@ struct DualVersionLanguagePlugin;
 export!(DualVersionLanguagePlugin);
 
 macro_rules! impl_common_guest {
-    ($pkg:ident) => {
+    ($pkg:ident $(, hazard_lines: $hazard_lines:expr, program_start: $program_start:expr)?) => {
         fn extensions() -> Vec {
             vec!["dual".to_string()]
         }
@@ -233,7 +266,9 @@ macro_rules! impl_common_guest {
                 functions: vec![],
                 tokens: vec![],
                 flagged_lines: vec![],
+                $(hazard_lines: $hazard_lines,)?
                 runtime_imports: vec![],
+                $(program_start: $program_start,)?
             })
         }
 
@@ -255,33 +290,45 @@ macro_rules! impl_common_guest {
             vec![]
         }
 
+        fn declared_dependencies(
+            _manifests: Vec,
+        ) -> Vec {
+            vec![exports::codeint::$pkg::language::DeclaredDep {
+                package_root: String::new(),
+                name: "dual-dep".to_string(),
+                kind: exports::codeint::$pkg::language::DepKind::Runtime,
+            }]
+        }
+
+        fn entry_points(
+            repository_paths: Vec,
+            _manifests: Vec,
+        ) -> Vec {
+            repository_paths.into_iter().take(1).collect()
+        }
+
         fn reference_ranges() -> Vec {
             vec![]
         }
     };
 }
 
-impl exports::codeint::plugin0_1_0::language::Guest for DualVersionLanguagePlugin {
-    impl_common_guest!(plugin0_1_0);
-}
-
 impl exports::codeint::plugin0_2_0::language::Guest for DualVersionLanguagePlugin {
     impl_common_guest!(plugin0_2_0);
+}
+
+impl exports::codeint::plugin0_3_0::language::Guest for DualVersionLanguagePlugin {
+    impl_common_guest!(plugin0_3_0, hazard_lines: vec![], program_start: false);
+
+    fn has_hazard_rules() -> bool {
+        false
+    }
 
-    fn declared_dependencies(
-        _manifests: Vec,
-    ) -> Vec {
-        vec![exports::codeint::plugin0_2_0::language::DeclaredDep {
-            package_root: String::new(),
-            name: "dual-dep".to_string(),
-            kind: exports::codeint::plugin0_2_0::language::DepKind::Runtime,
-        }]
+    fn hazard_rules() -> Vec {
+        vec![]
     }
 
-    fn entry_points(
-        repository_paths: Vec,
-        _manifests: Vec,
-    ) -> Vec {
-        repository_paths.into_iter().take(1).collect()
+    fn has_imports() -> bool {
+        true
     }
 }
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 ab20732e..78e2016c 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
@@ -70,4 +70,16 @@ impl Guest for FileReaderPlugin {
     fn reference_ranges() -> Vec {
         Vec::new()
     }
+
+    fn has_hazard_rules() -> bool {
+        false
+    }
+
+    fn hazard_rules() -> Vec {
+        Vec::new()
+    }
+
+    fn has_imports() -> bool {
+        true
+    }
 }
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/folder-import-language/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/folder-import-language/Cargo.toml
new file mode 100644
index 00000000..649bc0ee
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/folder-import-language/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "folder-import-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/folder-import-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/folder-import-language/src/lib.rs
new file mode 100644
index 00000000..519a8bf0
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/folder-import-language/src/lib.rs
@@ -0,0 +1,190 @@
+#![no_std]
+
+extern crate alloc;
+extern crate probe_runtime;
+
+use alloc::format;
+use alloc::string::{String, ToString};
+use alloc::vec;
+use alloc::vec::Vec;
+
+wit_bindgen::generate!({
+    world: "language-plugin",
+    path: "../../../../../../wit",
+});
+
+use exports::codeint::plugin::language::{
+    DeclaredDep, FileModel, Function, Guest, ImportRequest, LowerError, Manifest, ReferenceRange,
+    Resolution, SourceSet, Token, TokenKind, WorkspaceError,
+};
+
+struct FolderImportLanguagePlugin;
+
+export!(FolderImportLanguagePlugin);
+
+struct LowerAccumulator {
+    source_lines: u32,
+    functions: Vec,
+    tokens: Vec,
+    runtime_imports: Vec,
+    program_start: bool,
+}
+
+impl LowerAccumulator {
+    fn new() -> Self {
+        Self {
+            source_lines: 0,
+            functions: Vec::new(),
+            tokens: Vec::new(),
+            runtime_imports: Vec::new(),
+            program_start: false,
+        }
+    }
+
+    fn process_line(&mut self, line_no: u32, raw_line: &str) -> Result<(), LowerError> {
+        let trimmed = raw_line.trim();
+        if trimmed.is_empty() || trimmed.starts_with('#') {
+            return Ok(());
+        }
+        if trimmed == "SYNTAX_ERROR" {
+            return Err(LowerError::Unparsable("syntax error".to_string()));
+        }
+        self.source_lines += 1;
+        if trimmed == "program main" {
+            self.program_start = true;
+        }
+        let kind = if let Some(specifier) = trimmed.strip_prefix("use ") {
+            let spec = specifier.trim();
+            if !spec.is_empty() {
+                self.runtime_imports.push(spec.to_string());
+            }
+            TokenKind::ImportOrExport
+        } else {
+            TokenKind::Other
+        };
+        if let Some(rest) = trimmed.strip_prefix("fn ") {
+            self.functions.push(Function {
+                line: line_no,
+                end_line: line_no,
+                decision_points: 0,
+                source_lines: 1,
+                name: probe_runtime::parse_fn_name(rest),
+                cognitive_complexity: 0,
+                coverage: None,
+            });
+        }
+        for word in trimmed.split_whitespace() {
+            self.tokens.push(Token {
+                kind,
+                text_hash: probe_runtime::fnv1a_64(word),
+                line: line_no,
+            });
+        }
+        Ok(())
+    }
+}
+
+fn resolve_folder_import(repository_paths: &[String], request: ImportRequest) -> Resolution {
+    if request.specifier == "empty" {
+        return Resolution::Resolved(Vec::new());
+    }
+    if request.specifier == "partial-missing" {
+        let mut targets = Vec::new();
+        if let Some(first) = repository_paths.first() {
+            targets.push(first.clone());
+        }
+        targets.push("missing/does_not_exist.fld".to_string());
+        return Resolution::Resolved(targets);
+    }
+    if request.specifier.starts_with("std:") {
+        return Resolution::Builtin;
+    }
+    if let Some(pkg) = request.specifier.strip_prefix("ext:") {
+        return Resolution::External(pkg.to_string());
+    }
+    let prefix = format!("{}/", request.specifier);
+    let mut targets: Vec = repository_paths
+        .iter()
+        .filter(|path| {
+            path.as_str() != request.importer.as_str()
+                && path.ends_with(".fld")
+                && path
+                    .strip_prefix(&prefix)
+                    .is_some_and(|rest| !rest.contains('/'))
+        })
+        .cloned()
+        .collect();
+    targets.sort();
+    if targets.is_empty() {
+        Resolution::Unresolved(format!("no folder matches {:?}", request.specifier))
+    } else {
+        Resolution::Resolved(targets)
+    }
+}
+
+impl Guest for FolderImportLanguagePlugin {
+    fn extensions() -> Vec {
+        vec!["fld".to_string()]
+    }
+
+    fn lower(path: String, text: String) -> Result {
+        if !path.ends_with(".fld") {
+            return Err(LowerError::UnsupportedFile("unsupported".to_string()));
+        }
+        let source_set = if path.ends_with("_test.fld") {
+            SourceSet::Test
+        } else {
+            SourceSet::Production
+        };
+        let mut acc = LowerAccumulator::new();
+        for (index, raw_line) in text.lines().enumerate() {
+            acc.process_line((index + 1) as u32, raw_line)?;
+        }
+        Ok(probe_runtime::blank_file_model!(
+            source_set,
+            acc.source_lines,
+            functions: acc.functions,
+            tokens: acc.tokens,
+            runtime_imports: acc.runtime_imports,
+            program_start: acc.program_start,
+        ))
+    }
+
+    fn manifest_paths(repository_paths: Vec) -> Vec {
+        repository_paths
+            .into_iter()
+            .filter(|path| path == "fld.workspace" || path.ends_with("/fld.workspace"))
+            .collect()
+    }
+
+    fn workspace_packages(manifests: Vec) -> Result, WorkspaceError> {
+        let pairs: Vec<(&str, &str)> = manifests
+            .iter()
+            .map(|m| (m.path.as_str(), m.text.as_str()))
+            .collect();
+        probe_runtime::parse_workspace_manifest_lines(&pairs, "entry:")
+            .map_err(|(path, message)| WorkspaceError { path, message })
+    }
+
+    fn resolve_imports(
+        repository_paths: Vec,
+        _manifests: Vec,
+        requests: Vec,
+    ) -> Vec {
+        requests
+            .into_iter()
+            .map(|request| resolve_folder_import(&repository_paths, request))
+            .collect()
+    }
+
+    fn declared_dependencies(_manifests: Vec) -> Vec {
+        Vec::new()
+    }
+
+    fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec {
+        let texts: Vec<&str> = manifests.iter().map(|m| m.text.as_str()).collect();
+        probe_runtime::extract_manifest_entries(&repository_paths, &texts)
+    }
+
+    probe_runtime::fixture_erosion_ranges!("folder import language fixture", true);
+}
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/hazard-facts-metric/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/hazard-facts-metric/Cargo.toml
new file mode 100644
index 00000000..d10f7d37
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/hazard-facts-metric/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "hazard-facts-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/hazard-facts-metric/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/hazard-facts-metric/src/lib.rs
new file mode 100644
index 00000000..0ceb8ed0
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/hazard-facts-metric/src/lib.rs
@@ -0,0 +1,63 @@
+#![no_std]
+
+extern crate alloc;
+extern crate probe_runtime;
+
+use alloc::format;
+use alloc::string::{String, ToString};
+use alloc::vec::Vec;
+
+wit_bindgen::generate!({
+    world: "metric-plugin",
+    path: "../../../../../../wit",
+});
+
+use exports::codeint::plugin::metric::{CodeModel, Finding, Guest, Measurement};
+
+struct HazardFactsMetricPlugin;
+
+export!(HazardFactsMetricPlugin);
+
+impl Guest for HazardFactsMetricPlugin {
+    fn key() -> String {
+        "hazard_facts".to_string()
+    }
+
+    fn name() -> String {
+        "Hazard facts".to_string()
+    }
+
+    fn description() -> String {
+        "Test Metric plugin that reads per-language hazard rule capability".to_string()
+    }
+
+    fn measure(model: CodeModel) -> Measurement {
+        let (enabled, mut findings) = probe_runtime::language_fact_findings!(
+            &model.languages,
+            "hazard-rules",
+            "has_hazard_rules",
+            "enabled",
+            "absent",
+            |facts: &self::exports::codeint::plugin::metric::LanguageFacts| facts.has_hazard_rules
+        );
+        for file in &model.files {
+            for hazard in &file.model.hazard_lines {
+                findings.push(Finding {
+                    id: format!("hazard:{}:{}:{}", file.path, hazard.line, hazard.rule),
+                    path: file.path.clone(),
+                    line: hazard.line,
+                    end_line: None,
+                    message: format!("hazard rule={}", hazard.rule),
+                });
+            }
+        }
+        let numerator = enabled as f64;
+        let denominator = model.languages.len() as f64;
+        Measurement {
+            ratio: probe_runtime::ratio(numerator, denominator),
+            numerator,
+            denominator,
+            findings,
+        }
+    }
+}
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/hazard-rules-language/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/hazard-rules-language/Cargo.toml
new file mode 100644
index 00000000..97612d50
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/hazard-rules-language/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "hazard-rules-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/hazard-rules-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/hazard-rules-language/src/lib.rs
new file mode 100644
index 00000000..b0cdff44
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/hazard-rules-language/src/lib.rs
@@ -0,0 +1,86 @@
+#![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",
+    path: "../../../../../../wit",
+});
+
+use exports::codeint::plugin::language::{
+    DeclaredDep, FileModel, Guest, HazardLine, ImportRequest, LowerError, Manifest, ReferenceRange,
+    Resolution, SourceSet, WorkspaceError,
+};
+
+struct HazardRulesLanguagePlugin;
+
+export!(HazardRulesLanguagePlugin);
+
+impl Guest for HazardRulesLanguagePlugin {
+    fn extensions() -> Vec {
+        vec!["haz".to_string()]
+    }
+
+    fn lower(path: String, text: String) -> Result {
+        if !path.ends_with(".haz") {
+            return Err(LowerError::UnsupportedFile("unsupported".to_string()));
+        }
+        let line_count = text.lines().count() as u32;
+        let source_lines = probe_runtime::count_non_empty_lines(&text);
+        let mut hazard_lines = Vec::new();
+        for (index, line) in text.lines().enumerate() {
+            let line_number = (index + 1) as u32;
+            if line.contains("DELETE FROM") && !line.contains("WHERE") {
+                hazard_lines.push(HazardLine {
+                    line: line_number,
+                    rule: "delete-without-where".to_string(),
+                });
+            }
+            if line.contains("LIKE '%") {
+                hazard_lines.push(HazardLine {
+                    line: line_number,
+                    rule: "leading-wildcard-like".to_string(),
+                });
+            }
+            if line.contains("HAZARD_BEYOND_EOF") {
+                hazard_lines.push(HazardLine {
+                    line: line_count + 1,
+                    rule: "delete-without-where".to_string(),
+                });
+            }
+            if line.contains("HAZARD_LINE_ZERO") {
+                hazard_lines.push(HazardLine {
+                    line: 0,
+                    rule: "delete-without-where".to_string(),
+                });
+            }
+        }
+        Ok(probe_runtime::blank_file_model!(
+            SourceSet::Production,
+            source_lines,
+            hazard_lines: hazard_lines,
+        ))
+    }
+
+    probe_runtime::empty_language_metadata_stubs!();
+
+    fn has_hazard_rules() -> bool {
+        true
+    }
+
+    fn hazard_rules() -> Vec {
+        vec![
+            "delete-without-where".to_string(),
+            "leading-wildcard-like".to_string(),
+        ]
+    }
+
+    fn has_imports() -> bool {
+        true
+    }
+}
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/import-capability-metric/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/import-capability-metric/Cargo.toml
new file mode 100644
index 00000000..d7bdcde7
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/import-capability-metric/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "import-capability-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/import-capability-metric/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/import-capability-metric/src/lib.rs
new file mode 100644
index 00000000..170d2fde
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/import-capability-metric/src/lib.rs
@@ -0,0 +1,52 @@
+#![no_std]
+
+extern crate alloc;
+extern crate probe_runtime;
+
+use alloc::format;
+use alloc::string::{String, ToString};
+use alloc::vec::Vec;
+
+wit_bindgen::generate!({
+    world: "metric-plugin",
+    path: "../../../../../../wit",
+});
+
+use exports::codeint::plugin::metric::{CodeModel, Finding, Guest, Measurement};
+
+struct ImportCapabilityMetricPlugin;
+
+export!(ImportCapabilityMetricPlugin);
+
+impl Guest for ImportCapabilityMetricPlugin {
+    fn key() -> String {
+        "import_capability".to_string()
+    }
+
+    fn name() -> String {
+        "Import capability".to_string()
+    }
+
+    fn description() -> String {
+        "Test Metric plugin that reads per-language import capability".to_string()
+    }
+
+    fn measure(model: CodeModel) -> Measurement {
+        let (with_imports, findings) = probe_runtime::language_fact_findings!(
+            &model.languages,
+            "imports",
+            "has_imports",
+            "imports",
+            "no-imports",
+            |facts: &self::exports::codeint::plugin::metric::LanguageFacts| facts.has_imports
+        );
+        let numerator = with_imports as f64;
+        let denominator = model.languages.len() as f64;
+        Measurement {
+            ratio: probe_runtime::ratio(numerator, denominator),
+            numerator,
+            denominator,
+            findings,
+        }
+    }
+}
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/imports-reader-metric/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/imports-reader-metric/Cargo.toml
new file mode 100644
index 00000000..0015c617
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/imports-reader-metric/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "imports-reader-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/imports-reader-metric/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/imports-reader-metric/src/lib.rs
new file mode 100644
index 00000000..8b3cda79
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/imports-reader-metric/src/lib.rs
@@ -0,0 +1,74 @@
+#![no_std]
+
+extern crate alloc;
+extern crate probe_runtime;
+
+use alloc::format;
+use alloc::string::{String, ToString};
+use alloc::vec::Vec;
+
+wit_bindgen::generate!({
+    world: "metric-plugin",
+    path: "../../../../../../wit",
+});
+
+use self::codeint::plugin::language::Resolution;
+use exports::codeint::plugin::metric::{CodeModel, Finding, Guest, Measurement};
+
+struct ImportsReaderMetricPlugin;
+
+export!(ImportsReaderMetricPlugin);
+
+impl Guest for ImportsReaderMetricPlugin {
+    fn key() -> String {
+        "resolved_links".to_string()
+    }
+
+    fn name() -> String {
+        "Resolved links".to_string()
+    }
+
+    fn description() -> String {
+        "Test Metric plugin that reads multi-file resolved runtime imports".to_string()
+    }
+
+    fn measure(model: CodeModel) -> Measurement {
+        let mut findings = Vec::new();
+        let mut resolved_imports: u64 = 0;
+        let mut multi_target_imports: u64 = 0;
+
+        for import in &model.runtime_imports {
+            if let Resolution::Resolved(targets) = &import.resolution {
+                resolved_imports += 1;
+                if targets.len() > 1 {
+                    multi_target_imports += 1;
+                }
+                findings.push(Finding {
+                    id: format!(
+                        "{}:{}:{}",
+                        import.importer,
+                        import.specifier,
+                        targets.join(",")
+                    ),
+                    path: import.importer.clone(),
+                    line: 1,
+                    end_line: None,
+                    message: format!("{} -> [{}]", import.specifier, targets.join(", ")),
+                });
+            }
+        }
+
+        let ratio = if resolved_imports == 0 {
+            0.0
+        } else {
+            multi_target_imports as f64 / resolved_imports as f64
+        };
+
+        Measurement {
+            ratio,
+            numerator: multi_target_imports as f64,
+            denominator: resolved_imports as f64,
+            findings,
+        }
+    }
+}
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-2-0-language/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-2-0-language/Cargo.toml
new file mode 100644
index 00000000..ad7ca94d
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-2-0-language/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "legacy-v0-2-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-2-0-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-2-0-language/src/lib.rs
new file mode 100644
index 00000000..0768b5d1
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-2-0-language/src/lib.rs
@@ -0,0 +1,149 @@
+#![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.2.0;
+
+        interface language {
+            record function {
+                line: u32,
+                end-line: u32,
+                decision-points: u32,
+                source-lines: u32,
+                name: option,
+                cognitive-complexity: 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(string),
+                builtin,
+                unresolved(string),
+            }
+
+            enum dep-kind {
+                runtime,
+                dev,
+                optional,
+            }
+
+            record declared-dep {
+                package-root: string,
+                name: string,
+                kind: dep-kind,
+            }
+
+            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;
+            declared-dependencies: func(manifests: list) -> list;
+            entry-points: func(repository-paths: list, manifests: list) -> list;
+            reference-ranges: func() -> list;
+        }
+
+        world language-plugin {
+            export language;
+        }
+    ",
+});
+
+use exports::codeint::plugin::language::{
+    DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution,
+    SourceSet, WorkspaceError,
+};
+
+struct LegacyV020LanguagePlugin;
+
+export!(LegacyV020LanguagePlugin);
+
+impl Guest for LegacyV020LanguagePlugin {
+    fn extensions() -> Vec {
+        vec!["legacy02".to_string()]
+    }
+
+    fn lower(_path: String, _text: String) -> Result {
+        Ok(FileModel {
+            runtime_imports: Vec::new(),
+            flagged_lines: Vec::new(),
+            tokens: Vec::new(),
+            functions: Vec::new(),
+            source_lines: 0,
+            source_set: SourceSet::Production,
+        })
+    }
+
+    probe_runtime::empty_language_metadata_stubs!();
+}
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-2-0-metric/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-2-0-metric/Cargo.toml
new file mode 100644
index 00000000..5f2518d1
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-2-0-metric/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "legacy-v0-2-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-2-0-metric/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-2-0-metric/src/lib.rs
new file mode 100644
index 00000000..9036fd58
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/legacy-v0-2-0-metric/src/lib.rs
@@ -0,0 +1,141 @@
+#![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.2.0;
+
+        interface language {
+            record function {
+                line: u32,
+                end-line: u32,
+                decision-points: u32,
+                source-lines: u32,
+                name: option,
+                cognitive-complexity: 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(string),
+                builtin,
+                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 LegacyV020MetricPlugin;
+
+export!(LegacyV020MetricPlugin);
+
+impl Guest for LegacyV020MetricPlugin {
+    fn key() -> String {
+        "legacy_v0_2_0_metric".to_string()
+    }
+
+    fn name() -> String {
+        "Legacy 0.2.0 metric".to_string()
+    }
+
+    fn description() -> String {
+        "Test Metric plugin targeting codeint:plugin@0.2.0".to_string()
+    }
+
+    fn measure(_model: CodeModel) -> Measurement {
+        let zero = 0.0;
+        Measurement {
+            findings: Vec::new(),
+            denominator: zero,
+            numerator: zero,
+            ratio: zero,
+        }
+    }
+}
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 389b4733..f7f611e1 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
@@ -45,14 +45,10 @@ impl Guest for LoopLanguagePlugin {
                 core::hint::spin_loop();
             }
         }
-        Ok(FileModel {
-            source_set: SourceSet::Production,
-            source_lines: text.lines().count() as u32,
-            functions: Vec::new(),
-            tokens: Vec::new(),
-            flagged_lines: Vec::new(),
-            runtime_imports: Vec::new(),
-        })
+        Ok(probe_runtime::blank_file_model!(
+            SourceSet::Production,
+            text.lines().count() as u32,
+        ))
     }
 
     fn manifest_paths(_repository_paths: Vec) -> Vec {
@@ -88,4 +84,16 @@ impl Guest for LoopLanguagePlugin {
     fn reference_ranges() -> Vec {
         Vec::new()
     }
+
+    fn has_hazard_rules() -> bool {
+        false
+    }
+
+    fn hazard_rules() -> Vec {
+        Vec::new()
+    }
+
+    fn has_imports() -> bool {
+        true
+    }
 }
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 43ab264b..3f4fd56a 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
@@ -77,14 +77,10 @@ impl Guest for MemoryHogLanguagePlugin {
             buf.resize(2 * 1024 * 1024, 1u8);
             core::hint::black_box(&buf);
         }
-        Ok(FileModel {
-            source_set: SourceSet::Production,
-            source_lines: text.lines().count() as u32,
-            functions: Vec::new(),
-            tokens: Vec::new(),
-            flagged_lines: Vec::new(),
-            runtime_imports: Vec::new(),
-        })
+        Ok(probe_runtime::blank_file_model!(
+            SourceSet::Production,
+            text.lines().count() as u32,
+        ))
     }
 
     fn manifest_paths(_paths: Vec) -> Vec {
@@ -153,4 +149,16 @@ impl Guest for MemoryHogLanguagePlugin {
     fn reference_ranges() -> Vec {
         vec![]
     }
+
+    fn has_hazard_rules() -> bool {
+        false
+    }
+
+    fn hazard_rules() -> Vec {
+        vec![]
+    }
+
+    fn has_imports() -> bool {
+        true
+    }
 }
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/no-imports-language/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/no-imports-language/Cargo.toml
new file mode 100644
index 00000000..332adbe3
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/no-imports-language/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "no-imports-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/no-imports-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/no-imports-language/src/lib.rs
new file mode 100644
index 00000000..678295f9
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/no-imports-language/src/lib.rs
@@ -0,0 +1,93 @@
+#![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",
+    path: "../../../../../../wit",
+});
+
+use exports::codeint::plugin::language::{
+    DeclaredDep, FileModel, Function, Guest, ImportRequest, LowerError, Manifest, ReferenceRange,
+    Resolution, SourceSet, Token, TokenKind, WorkspaceError,
+};
+
+struct NoImportsLanguagePlugin;
+
+export!(NoImportsLanguagePlugin);
+
+fn parse_noimp_line(
+    line_number: u32,
+    trimmed: &str,
+    functions: &mut Vec,
+    tokens: &mut Vec,
+) {
+    if let Some(rest) = trimmed.strip_prefix("fn ") {
+        functions.push(Function {
+            line: line_number,
+            end_line: line_number,
+            decision_points: 0,
+            source_lines: 1,
+            name: probe_runtime::parse_fn_name(rest),
+            cognitive_complexity: 0,
+            coverage: None,
+        });
+    }
+    for word in trimmed.split_whitespace() {
+        let kind = if word == "fn" {
+            TokenKind::Other
+        } else {
+            TokenKind::Identifier
+        };
+        tokens.push(Token {
+            kind,
+            text_hash: probe_runtime::fnv1a_64(word),
+            line: line_number,
+        });
+    }
+}
+
+impl Guest for NoImportsLanguagePlugin {
+    fn extensions() -> Vec {
+        vec!["noimp".to_string()]
+    }
+
+    fn lower(path: String, text: String) -> Result {
+        if !path.ends_with(".noimp") {
+            return Err(LowerError::UnsupportedFile("unsupported".to_string()));
+        }
+        if text.contains("SYNTAX_ERROR") {
+            return Err(LowerError::Unparsable("syntax error".to_string()));
+        }
+        let source_set = if path.ends_with("_test.noimp") || path.ends_with(".test.noimp") {
+            SourceSet::Test
+        } else {
+            SourceSet::Production
+        };
+        let mut source_lines: u32 = 0;
+        let mut functions = Vec::new();
+        let mut tokens = Vec::new();
+        for (index, raw_line) in text.lines().enumerate() {
+            let trimmed = raw_line.trim();
+            if trimmed.is_empty() || trimmed.starts_with('#') {
+                continue;
+            }
+            source_lines += 1;
+            parse_noimp_line((index + 1) as u32, trimmed, &mut functions, &mut tokens);
+        }
+        Ok(probe_runtime::blank_file_model!(
+            source_set,
+            source_lines,
+            functions: functions,
+            tokens: tokens,
+        ))
+    }
+
+    probe_runtime::panic_no_imports_stubs!();
+    probe_runtime::fixture_erosion_ranges!("no-imports language fixture", false);
+}
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/probe-runtime/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/probe-runtime/src/lib.rs
index 08b6f03d..89a490cc 100644
--- a/crates/plugin-host/tests/fixtures/sandbox-probes/probe-runtime/src/lib.rs
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/probe-runtime/src/lib.rs
@@ -145,3 +145,222 @@ pub unsafe extern "C" fn memset(dest: *mut u8, value: i32, count: usize) -> *mut
     }
     dest
 }
+
+pub fn fnv1a_64(text: &str) -> u64 {
+    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
+    for byte in text.as_bytes() {
+        hash ^= u64::from(*byte);
+        hash = hash.wrapping_mul(0x0100_0000_01b3);
+    }
+    hash
+}
+
+pub fn ratio(numerator: f64, denominator: f64) -> f64 {
+    if denominator == 0.0 {
+        0.0
+    } else {
+        numerator / denominator
+    }
+}
+
+pub fn count_non_empty_lines(text: &str) -> u32 {
+    text.lines().filter(|line| !line.trim().is_empty()).count() as u32
+}
+
+pub fn parse_fn_name(rest: &str) -> Option {
+    rest.split(|ch: char| ch == '(' || ch.is_whitespace())
+        .next()
+        .filter(|name| !name.is_empty())
+        .map(alloc::string::ToString::to_string)
+}
+
+pub fn extract_manifest_entries(
+    repository_paths: &[alloc::string::String],
+    manifest_texts: &[&str],
+) -> alloc::vec::Vec {
+    let mut entries = alloc::vec::Vec::new();
+    for text in manifest_texts {
+        for line in 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(alloc::string::ToString::to_string(candidate));
+                }
+            }
+        }
+    }
+    entries
+}
+
+#[macro_export]
+macro_rules! empty_language_metadata_stubs {
+    () => {
+        fn manifest_paths(
+            _repository_paths: ::alloc::vec::Vec<::alloc::string::String>,
+        ) -> ::alloc::vec::Vec<::alloc::string::String> {
+            ::alloc::vec::Vec::new()
+        }
+
+        fn workspace_packages(
+            _manifests: ::alloc::vec::Vec,
+        ) -> ::core::result::Result<::alloc::vec::Vec<::alloc::string::String>, WorkspaceError> {
+            ::core::result::Result::Ok(::alloc::vec::Vec::new())
+        }
+
+        fn resolve_imports(
+            _repository_paths: ::alloc::vec::Vec<::alloc::string::String>,
+            _manifests: ::alloc::vec::Vec,
+            _requests: ::alloc::vec::Vec,
+        ) -> ::alloc::vec::Vec {
+            ::alloc::vec::Vec::new()
+        }
+
+        fn declared_dependencies(
+            _manifests: ::alloc::vec::Vec,
+        ) -> ::alloc::vec::Vec {
+            ::alloc::vec::Vec::new()
+        }
+
+        fn entry_points(
+            _repository_paths: ::alloc::vec::Vec<::alloc::string::String>,
+            _manifests: ::alloc::vec::Vec,
+        ) -> ::alloc::vec::Vec<::alloc::string::String> {
+            ::alloc::vec::Vec::new()
+        }
+
+        fn reference_ranges() -> ::alloc::vec::Vec {
+            ::alloc::vec::Vec::new()
+        }
+    };
+}
+
+#[macro_export]
+macro_rules! panic_no_imports_stubs {
+    () => {
+        fn manifest_paths(
+            _repository_paths: ::alloc::vec::Vec<::alloc::string::String>,
+        ) -> ::alloc::vec::Vec<::alloc::string::String> {
+            panic!("manifest-paths must not be called when has-imports is false");
+        }
+
+        fn workspace_packages(
+            _manifests: ::alloc::vec::Vec,
+        ) -> ::core::result::Result<::alloc::vec::Vec<::alloc::string::String>, WorkspaceError> {
+            panic!("workspace-packages must not be called when has-imports is false");
+        }
+
+        fn resolve_imports(
+            _repository_paths: ::alloc::vec::Vec<::alloc::string::String>,
+            _manifests: ::alloc::vec::Vec,
+            _requests: ::alloc::vec::Vec,
+        ) -> ::alloc::vec::Vec {
+            panic!("resolve-imports must not be called when has-imports is false");
+        }
+
+        fn declared_dependencies(
+            _manifests: ::alloc::vec::Vec,
+        ) -> ::alloc::vec::Vec {
+            panic!("declared-dependencies must not be called when has-imports is false");
+        }
+
+        fn entry_points(
+            _repository_paths: ::alloc::vec::Vec<::alloc::string::String>,
+            _manifests: ::alloc::vec::Vec,
+        ) -> ::alloc::vec::Vec<::alloc::string::String> {
+            panic!("entry-points must not be called when has-imports is false");
+        }
+    };
+}
+
+#[macro_export]
+macro_rules! language_fact_findings {
+    ($languages:expr, $prefix:expr, $flag_name:expr, $on_label:expr, $off_label:expr, $extract:expr) => {{
+        let mut enabled: usize = 0;
+        let mut findings = ::alloc::vec::Vec::new();
+        for facts in $languages {
+            let active = ($extract)(facts);
+            let status = if active {
+                enabled += 1;
+                $on_label
+            } else {
+                $off_label
+            };
+            findings.push(Finding {
+                id: ::alloc::format!("{}:{}:{status}", $prefix, facts.language),
+                path: ::alloc::format!("languages/{}", facts.language),
+                line: 1,
+                end_line: None,
+                message: ::alloc::format!("language={} {}={active}", facts.language, $flag_name),
+            });
+        }
+        (enabled, findings)
+    }};
+}
+
+#[macro_export]
+macro_rules! blank_file_model {
+    ($source_set:expr, $source_lines:expr $(, $field:ident : $val:expr)* $(,)?) => {{
+        let mut model = FileModel {
+            source_set: $source_set,
+            source_lines: $source_lines,
+            functions: ::alloc::vec::Vec::new(),
+            tokens: ::alloc::vec::Vec::new(),
+            flagged_lines: ::alloc::vec::Vec::new(),
+            hazard_lines: ::alloc::vec::Vec::new(),
+            runtime_imports: ::alloc::vec::Vec::new(),
+            program_start: false,
+        };
+        $(model.$field = $val;)*
+        model
+    }};
+}
+
+#[macro_export]
+macro_rules! fixture_erosion_ranges {
+    ($source:expr, $has_imports:expr) => {
+        fn reference_ranges() -> ::alloc::vec::Vec {
+            ::alloc::vec![ReferenceRange {
+                metric: ::alloc::string::ToString::to_string("erosion"),
+                low: 0.0,
+                high: 0.2,
+                source: ::alloc::string::ToString::to_string($source),
+            }]
+        }
+
+        fn has_hazard_rules() -> bool {
+            false
+        }
+
+        fn hazard_rules() -> ::alloc::vec::Vec<::alloc::string::String> {
+            ::alloc::vec::Vec::new()
+        }
+
+        fn has_imports() -> bool {
+            $has_imports
+        }
+    };
+}
+
+pub fn parse_workspace_manifest_lines(
+    manifests: &[(&str, &str)],
+    skip_prefix: &str,
+) -> Result, (alloc::string::String, alloc::string::String)>
+{
+    let mut packages = alloc::vec::Vec::new();
+    for &(path, text) in manifests {
+        for line in text.lines() {
+            let trimmed = line.trim();
+            if trimmed.is_empty() || trimmed.starts_with(skip_prefix) {
+                continue;
+            }
+            if let Some(problem) = trimmed.strip_prefix("INVALID:") {
+                return Err((
+                    alloc::string::ToString::to_string(path),
+                    alloc::string::ToString::to_string(problem.trim()),
+                ));
+            }
+            packages.push(alloc::string::ToString::to_string(trimmed));
+        }
+    }
+    Ok(packages)
+}
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/program-start-language/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/program-start-language/Cargo.toml
new file mode 100644
index 00000000..51fa703d
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/program-start-language/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "program-start-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/program-start-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/program-start-language/src/lib.rs
new file mode 100644
index 00000000..0ba42483
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/program-start-language/src/lib.rs
@@ -0,0 +1,115 @@
+#![no_std]
+
+extern crate alloc;
+extern crate probe_runtime;
+
+use alloc::format;
+use alloc::string::{String, ToString};
+use alloc::vec;
+use alloc::vec::Vec;
+
+wit_bindgen::generate!({
+    world: "language-plugin",
+    path: "../../../../../../wit",
+});
+
+use exports::codeint::plugin::language::{
+    DeclaredDep, FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution,
+    SourceSet, WorkspaceError,
+};
+
+struct ProgramStartLanguagePlugin;
+
+export!(ProgramStartLanguagePlugin);
+
+impl Guest for ProgramStartLanguagePlugin {
+    fn extensions() -> Vec {
+        vec!["prog".to_string()]
+    }
+
+    fn lower(path: String, text: String) -> Result {
+        if !path.ends_with(".prog") {
+            return Err(LowerError::UnsupportedFile("unsupported".to_string()));
+        }
+        let source_set = if path.ends_with("_test.prog") || path.ends_with(".test.prog") {
+            SourceSet::Test
+        } else {
+            SourceSet::Production
+        };
+        let source_lines = probe_runtime::count_non_empty_lines(&text);
+        let program_start = text.lines().any(|line| line.trim() == "program main");
+        let runtime_imports = text
+            .lines()
+            .filter_map(|line| line.trim().strip_prefix("use "))
+            .map(|spec| spec.trim().to_string())
+            .filter(|spec| !spec.is_empty())
+            .collect();
+        Ok(probe_runtime::blank_file_model!(
+            source_set,
+            source_lines,
+            runtime_imports: runtime_imports,
+            program_start: program_start,
+        ))
+    }
+
+    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 {
+        requests
+            .into_iter()
+            .map(|request| {
+                let target = match request.specifier.strip_prefix("./") {
+                    Some(relative) => match request.importer.rsplit_once('/') {
+                        Some((dir, _)) => format!("{dir}/{relative}"),
+                        None => relative.to_string(),
+                    },
+                    None => request.specifier,
+                };
+                let candidates = if target.ends_with(".prog") {
+                    vec![target.clone()]
+                } else {
+                    vec![target.clone(), format!("{target}.prog")]
+                };
+                candidates
+                    .into_iter()
+                    .find(|candidate| repository_paths.iter().any(|path| path == candidate))
+                    .map(|found| Resolution::Resolved(vec![found]))
+                    .unwrap_or_else(|| Resolution::Unresolved(format!("missing {target}")))
+            })
+            .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::new()
+    }
+
+    fn has_hazard_rules() -> bool {
+        false
+    }
+
+    fn hazard_rules() -> Vec {
+        Vec::new()
+    }
+
+    fn has_imports() -> bool {
+        true
+    }
+}
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/program-start-metric/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/program-start-metric/Cargo.toml
new file mode 100644
index 00000000..8a93ff79
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/program-start-metric/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "program-start-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/program-start-metric/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/program-start-metric/src/lib.rs
new file mode 100644
index 00000000..ddb3b09e
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/program-start-metric/src/lib.rs
@@ -0,0 +1,61 @@
+#![no_std]
+
+extern crate alloc;
+extern crate probe_runtime;
+
+use alloc::format;
+use alloc::string::{String, ToString};
+use alloc::vec::Vec;
+
+wit_bindgen::generate!({
+    world: "metric-plugin",
+    path: "../../../../../../wit",
+});
+
+use exports::codeint::plugin::metric::{CodeModel, Finding, Guest, Measurement};
+
+struct ProgramStartMetricPlugin;
+
+export!(ProgramStartMetricPlugin);
+
+impl Guest for ProgramStartMetricPlugin {
+    fn key() -> String {
+        "program_starts".to_string()
+    }
+
+    fn name() -> String {
+        "Program starts".to_string()
+    }
+
+    fn description() -> String {
+        "Test Metric plugin that reads program-start marks".to_string()
+    }
+
+    fn measure(model: CodeModel) -> Measurement {
+        let mut findings = Vec::new();
+        for file in &model.files {
+            if file.model.program_start {
+                findings.push(Finding {
+                    id: format!("program-start:{}", file.path),
+                    path: file.path.clone(),
+                    line: 1,
+                    end_line: None,
+                    message: "program start".to_string(),
+                });
+            }
+        }
+        let numerator = findings.len() as f64;
+        let denominator = model.files.len() as f64;
+        let ratio = if model.files.is_empty() {
+            0.0
+        } else {
+            numerator / denominator
+        };
+        Measurement {
+            ratio,
+            numerator,
+            denominator,
+            findings,
+        }
+    }
+}
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 e783d683..17ad4ef1 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
@@ -112,4 +112,16 @@ impl Guest for SocketOpenerPlugin {
     fn reference_ranges() -> Vec {
         Vec::new()
     }
+
+    fn has_hazard_rules() -> bool {
+        false
+    }
+
+    fn hazard_rules() -> Vec {
+        Vec::new()
+    }
+
+    fn has_imports() -> bool {
+        true
+    }
 }
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/unlisted-hazard-rule-language/Cargo.toml b/crates/plugin-host/tests/fixtures/sandbox-probes/unlisted-hazard-rule-language/Cargo.toml
new file mode 100644
index 00000000..04fa5103
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/unlisted-hazard-rule-language/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "unlisted-hazard-rule-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/unlisted-hazard-rule-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/unlisted-hazard-rule-language/src/lib.rs
new file mode 100644
index 00000000..a0de2f46
--- /dev/null
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/unlisted-hazard-rule-language/src/lib.rs
@@ -0,0 +1,70 @@
+#![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",
+    path: "../../../../../../wit",
+});
+
+use exports::codeint::plugin::language::{
+    DeclaredDep, FileModel, Guest, HazardLine, ImportRequest, LowerError, Manifest, ReferenceRange,
+    Resolution, SourceSet, WorkspaceError,
+};
+
+struct UnlistedHazardRuleLanguagePlugin;
+
+export!(UnlistedHazardRuleLanguagePlugin);
+
+impl Guest for UnlistedHazardRuleLanguagePlugin {
+    fn extensions() -> Vec {
+        vec!["uhr".to_string()]
+    }
+
+    fn lower(path: String, text: String) -> Result {
+        if !path.ends_with(".uhr") {
+            return Err(LowerError::UnsupportedFile("unsupported".to_string()));
+        }
+        let source_lines = probe_runtime::count_non_empty_lines(&text);
+        let mut hazard_lines = Vec::new();
+        for (index, line) in text.lines().enumerate() {
+            let line_number = (index + 1) as u32;
+            if line.contains("ALLOWED_HAZARD") {
+                hazard_lines.push(HazardLine {
+                    line: line_number,
+                    rule: "allowed-rule".to_string(),
+                });
+            }
+            if line.contains("UNLISTED_HAZARD") {
+                hazard_lines.push(HazardLine {
+                    line: line_number,
+                    rule: "unlisted-secret-rule".to_string(),
+                });
+            }
+        }
+        Ok(probe_runtime::blank_file_model!(
+            SourceSet::Production,
+            source_lines,
+            hazard_lines: hazard_lines,
+        ))
+    }
+
+    probe_runtime::empty_language_metadata_stubs!();
+
+    fn has_hazard_rules() -> bool {
+        true
+    }
+
+    fn hazard_rules() -> Vec {
+        vec!["allowed-rule".to_string()]
+    }
+
+    fn has_imports() -> bool {
+        true
+    }
+}
diff --git a/crates/plugin-host/tests/load.rs b/crates/plugin-host/tests/load.rs
index 16361588..2cdf2ff0 100644
--- a/crates/plugin-host/tests/load.rs
+++ b/crates/plugin-host/tests/load.rs
@@ -6,20 +6,27 @@ use std::sync::OnceLock;
 use codeint_config::{
     PluginDeclaration, PluginHostConfig, PluginKind, PluginLimits, PluginSource, Sha256Digest,
 };
-use codeint_model::language::{DeclaredDep, DepKind, Function, ImportRequest, Resolution};
+use codeint_model::language::{
+    DeclaredDep, DepKind, Function, FunctionCoverage, ImportRequest, Resolution,
+};
 use codeint_model::{
-    CodeModel, FileModel, LanguagePlugin, LanguagePluginError, LowerError, Manifest, MetricPlugin,
-    MetricPluginError, RepoPath, SourceFile, SourceSet, Token, TokenKind, token_text_hash,
+    CodeModel, FileModel, HazardLine, ImportResolution, LanguageFacts, LanguagePlugin,
+    LanguagePluginError, LowerError, Manifest, MetricPlugin, MetricPluginError, RepoPath,
+    ResolveError, SourceFile, SourceSet, Token, TokenKind, resolve_runtime_imports,
+    token_text_hash,
 };
 use codeint_plugin_host::{
-    PluginHostError, WasmLanguagePlugin, load_language_plugin, load_language_plugin_with_limits,
-    load_language_plugins, load_metric_plugin, load_metric_plugin_with_limits, load_metric_plugins,
+    PLUGIN_INTERFACE_VERSION, PluginHostError, WasmLanguagePlugin, load_language_plugin,
+    load_language_plugin_with_limits, load_language_plugins, load_metric_plugin,
+    load_metric_plugin_with_limits, load_metric_plugins, verify_plugin_component,
 };
 
-use common::{build_fixture_workspace, declaration_for, declaration_with_kind, sample_plugin_wasm};
+use common::{
+    build_fixture_workspace, declaration_for, declaration_with_kind, sample_plugin_wasm,
+    sandbox_probe_wasm,
+};
 
 static SAMPLE_METRIC_WASM: OnceLock = OnceLock::new();
-static SANDBOX_PROBES_DIR: OnceLock = OnceLock::new();
 
 fn sample_metric_plugin_wasm() -> &'static Path {
     SAMPLE_METRIC_WASM.get_or_init(|| {
@@ -32,18 +39,6 @@ fn sample_metric_plugin_wasm() -> &'static Path {
     })
 }
 
-fn sandbox_probe_wasm(file_name: &str) -> PathBuf {
-    SANDBOX_PROBES_DIR
-        .get_or_init(|| {
-            build_fixture_workspace(
-                "tests/fixtures/sandbox-probes/Cargo.toml",
-                "wasm-fixtures",
-                true,
-            )
-        })
-        .join(file_name)
-}
-
 fn assert_sandbox_blocks(plugin_name: &str, wasm_file: &str, denied_interface: &str) {
     let wasm_path = sandbox_probe_wasm(wasm_file);
     let declaration = declaration_for(plugin_name, &wasm_path);
@@ -116,28 +111,30 @@ fn loads_sample_external_plugin_with_zero_capabilities_and_valid_hash() {
         .expect("workspace packages");
     assert_eq!(packages, vec![RepoPath::new("packages/core").unwrap()]);
 
-    let resolutions = plugin.resolve_imports(
-        &repo_paths,
-        Vec::new(),
-        vec![
-            ImportRequest {
-                importer: "src/app.mini".to_owned(),
-                specifier: "./util".to_owned(),
-            },
-            ImportRequest {
-                importer: "src/app.mini".to_owned(),
-                specifier: "external-pkg".to_owned(),
-            },
-            ImportRequest {
-                importer: "src/app.mini".to_owned(),
-                specifier: "std:io".to_owned(),
-            },
-        ],
-    );
+    let resolutions = plugin
+        .resolve_imports(
+            &repo_paths,
+            Vec::new(),
+            vec![
+                ImportRequest {
+                    importer: "src/app.mini".to_owned(),
+                    specifier: "./util".to_owned(),
+                },
+                ImportRequest {
+                    importer: "src/app.mini".to_owned(),
+                    specifier: "external-pkg".to_owned(),
+                },
+                ImportRequest {
+                    importer: "src/app.mini".to_owned(),
+                    specifier: "std:io".to_owned(),
+                },
+            ],
+        )
+        .expect("resolve imports");
     assert_eq!(
         resolutions,
         vec![
-            Resolution::Resolved("src/util.mini".to_owned()),
+            Resolution::Resolved(vec!["src/util.mini".to_owned()]),
             Resolution::External("external-pkg".to_owned()),
             Resolution::Builtin,
         ]
@@ -214,6 +211,7 @@ fn loads_sample_external_metric_plugin_with_zero_capabilities_and_measures_code_
                         source_lines: 3,
                         name: Some("brief".to_owned()),
                         cognitive_complexity: 0,
+                        coverage: None,
                     },
                     Function {
                         line: 5,
@@ -222,6 +220,7 @@ fn loads_sample_external_metric_plugin_with_zero_capabilities_and_measures_code_
                         source_lines: 14,
                         name: Some("verbose".to_owned()),
                         cognitive_complexity: 1,
+                        coverage: None,
                     },
                 ],
                 tokens: vec![Token {
@@ -230,7 +229,9 @@ fn loads_sample_external_metric_plugin_with_zero_capabilities_and_measures_code_
                     line: 6,
                 }],
                 flagged_lines: Vec::new(),
+                hazard_lines: Vec::new(),
                 runtime_imports: Vec::new(),
+                program_start: false,
             },
         }],
         ..CodeModel::default()
@@ -477,7 +478,9 @@ fn metric_plugin_that_loops_forever_or_exceeds_memory_cap_returns_limit_error()
                 functions: Vec::new(),
                 tokens: Vec::new(),
                 flagged_lines: Vec::new(),
+                hazard_lines: Vec::new(),
                 runtime_imports: Vec::new(),
+                program_start: false,
             },
         }],
         ..CodeModel::default()
@@ -572,11 +575,12 @@ fn built_in_and_sample_plugins_fit_comfortably_within_default_limits() {
 }
 
 #[test]
-fn verifies_0_2_0_contract_fields_and_methods_across_wasm_boundary() {
+fn verifies_0_3_0_contract_fields_and_methods_across_wasm_boundary() {
+    assert_eq!(PLUGIN_INTERFACE_VERSION, "0.3.0");
     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");
+        .expect("0.3.0 sample plugin loads");
 
     let lowered = plugin
         .lower(
@@ -588,8 +592,12 @@ fn verifies_0_2_0_contract_fields_and_methods_across_wasm_boundary() {
     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[0].coverage, None);
     assert_eq!(lowered.functions[1].name, None);
     assert_eq!(lowered.functions[1].cognitive_complexity, 0);
+    assert_eq!(lowered.functions[1].coverage, None);
+    assert!(lowered.hazard_lines.is_empty());
+    assert!(!lowered.program_start);
 
     let repo_paths = vec![
         RepoPath::new("mini.workspace").expect("valid repo path"),
@@ -630,30 +638,32 @@ fn verifies_0_2_0_contract_fields_and_methods_across_wasm_boundary() {
         vec![RepoPath::new("src/main.mini").expect("valid repo path")]
     );
     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(),
-                },
-            ],
-        ),
+        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(),
+                    },
+                ],
+            )
+            .expect("resolve imports"),
         vec![
-            Resolution::Resolved("src/util.mini".to_owned()),
+            Resolution::Resolved(vec!["src/util.mini".to_owned()]),
             Resolution::External("serde".to_owned()),
             Resolution::Builtin,
             Resolution::Unresolved("cannot find src/missing.mini".to_owned()),
@@ -698,12 +708,12 @@ fn rejects_v0_1_0_language_plugin_with_actionable_version_mismatch_error() {
 
     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");
+        .expect("0.1.0 Language plugin must be rejected by 0.3.0 host");
 
     assert_incompatible_contract_error(
         error,
         "legacy-lang",
-        "codeint:plugin/language@0.2.0",
+        "codeint:plugin/language@0.3.0",
         "codeint:plugin/language@0.1.0",
     );
 }
@@ -715,16 +725,93 @@ fn rejects_v0_1_0_metric_plugin_with_actionable_version_mismatch_error() {
 
     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");
+        .expect("0.1.0 Metric plugin must be rejected by 0.3.0 host");
 
     assert_incompatible_contract_error(
         error,
         "legacy-metric",
-        "codeint:plugin/metric@0.2.0",
+        "codeint:plugin/metric@0.3.0",
         "codeint:plugin/metric@0.1.0",
     );
 }
 
+#[test]
+fn rejects_v0_2_0_language_and_metric_plugins_with_actionable_version_mismatch_error() {
+    let lang_path = sandbox_probe_wasm("legacy_v0_2_0_language_plugin.wasm");
+    let lang_decl = declaration_for("legacy-v02-lang", &lang_path);
+    let lang_err = load_language_plugin(Path::new("."), &lang_decl, &PluginHostConfig::default())
+        .err()
+        .expect("0.2.0 Language plugin must be rejected by 0.3.0 host");
+    assert_incompatible_contract_error(
+        lang_err,
+        "legacy-v02-lang",
+        "codeint:plugin/language@0.3.0",
+        "codeint:plugin/language@0.2.0",
+    );
+
+    let metric_path = sandbox_probe_wasm("legacy_v0_2_0_metric_plugin.wasm");
+    let metric_decl = declaration_with_kind("legacy-v02-metric", PluginKind::Metric, &metric_path);
+    let metric_err = load_metric_plugin(Path::new("."), &metric_decl, &PluginHostConfig::default())
+        .err()
+        .expect("0.2.0 Metric plugin must be rejected by 0.3.0 host");
+    assert_incompatible_contract_error(
+        metric_err,
+        "legacy-v02-metric",
+        "codeint:plugin/metric@0.3.0",
+        "codeint:plugin/metric@0.2.0",
+    );
+
+    let sample_lang_bytes = std::fs::read(sample_plugin_wasm()).expect("read sample language wasm");
+    assert!(
+        verify_plugin_component(
+            "sample-mini",
+            sample_plugin_wasm(),
+            PluginKind::Language,
+            &sample_lang_bytes,
+        )
+        .is_ok()
+    );
+    let sample_metric_bytes =
+        std::fs::read(sample_metric_plugin_wasm()).expect("read sample metric wasm");
+    assert!(
+        verify_plugin_component(
+            "sample-metric",
+            sample_metric_plugin_wasm(),
+            PluginKind::Metric,
+            &sample_metric_bytes,
+        )
+        .is_ok()
+    );
+    let legacy_lang_bytes = std::fs::read(&lang_path).expect("read legacy 0.2.0 language wasm");
+    let verify_lang_err = verify_plugin_component(
+        "legacy-v02-lang",
+        &lang_path,
+        PluginKind::Language,
+        &legacy_lang_bytes,
+    )
+    .expect_err("0.2.0 language component must fail contract verification");
+    assert_incompatible_contract_error(
+        verify_lang_err,
+        "legacy-v02-lang",
+        "codeint:plugin/language@0.3.0",
+        "codeint:plugin/language@0.2.0",
+    );
+    let legacy_metric_bytes = std::fs::read(&metric_path).expect("read legacy 0.2.0 metric wasm");
+    let verify_metric_err = verify_plugin_component(
+        "legacy-v02-metric",
+        &metric_path,
+        PluginKind::Metric,
+        &legacy_metric_bytes,
+    )
+    .expect_err("0.2.0 metric component must fail contract verification");
+    assert_incompatible_contract_error(
+        verify_metric_err,
+        "legacy-v02-metric",
+        "codeint:plugin/metric@0.3.0",
+        "codeint:plugin/metric@0.2.0",
+    );
+}
+
 fn trigger_manifest(directive: &str) -> Vec {
     vec![Manifest {
         path: "trigger.manifest".to_owned(),
@@ -918,7 +1005,7 @@ fn rejects_invalid_entry_points_and_declared_dependencies_from_wasm_plugin() {
 }
 
 #[test]
-fn loads_dual_version_language_plugin_exporting_0_1_0_and_0_2_0() {
+fn loads_dual_version_language_plugin_exporting_0_2_0_and_0_3_0() {
     let plugin = load_probe(
         "dual-lang",
         "dual_version_language_plugin.wasm",
@@ -943,3 +1030,743 @@ fn loads_dual_version_language_plugin_exporting_0_1_0_and_0_2_0() {
         }]
     );
 }
+
+fn coverage_model_with(functions: Vec) -> CodeModel {
+    CodeModel {
+        files: vec![SourceFile {
+            path: RepoPath::new("src/work.ts").expect("valid repo path"),
+            model: FileModel {
+                source_set: SourceSet::Production,
+                source_lines: 30,
+                functions,
+                tokens: Vec::new(),
+                flagged_lines: Vec::new(),
+                hazard_lines: Vec::new(),
+                runtime_imports: Vec::new(),
+                program_start: false,
+            },
+        }],
+        ..CodeModel::default()
+    }
+}
+
+#[test]
+fn metric_plugin_reads_per_function_coverage_and_distinguishes_absent_from_zero_executed() {
+    let wasm_path = sandbox_probe_wasm("coverage_reader_metric_plugin.wasm");
+    let declaration = declaration_with_kind("coverage-reader", PluginKind::Metric, &wasm_path);
+    let plugin = load_metric_plugin(Path::new("."), &declaration, &PluginHostConfig::default())
+        .expect("coverage reader Metric plugin loads");
+
+    assert_eq!(plugin.key(), "coverage_reader");
+
+    let absent_only = coverage_model_with(vec![Function {
+        line: 1,
+        end_line: 6,
+        decision_points: 1,
+        source_lines: 5,
+        name: Some("unreported".to_owned()),
+        cognitive_complexity: 1,
+        coverage: None,
+    }]);
+    let zero_only = coverage_model_with(vec![Function {
+        line: 1,
+        end_line: 6,
+        decision_points: 1,
+        source_lines: 5,
+        name: Some("unexecuted".to_owned()),
+        cognitive_complexity: 1,
+        coverage: Some(FunctionCoverage {
+            listed_lines: 5,
+            executed_lines: 0,
+        }),
+    }]);
+
+    let absent_measured = plugin
+        .measure(&absent_only)
+        .expect("measure absent coverage");
+    let zero_measured = plugin.measure(&zero_only).expect("measure zero executed");
+
+    assert!((absent_measured.ratio - 0.0).abs() < 1e-9);
+    assert!((absent_measured.numerator - 0.0).abs() < 1e-9);
+    assert!((absent_measured.denominator - 0.0).abs() < 1e-9);
+    assert_eq!(absent_measured.findings.len(), 1);
+    assert_eq!(absent_measured.findings[0].id, "absent:unreported");
+    assert_eq!(absent_measured.findings[0].message, "absent");
+
+    assert!((zero_measured.ratio - 1.0).abs() < 1e-9);
+    assert!((zero_measured.numerator - 5.0).abs() < 1e-9);
+    assert!((zero_measured.denominator - 5.0).abs() < 1e-9);
+    assert_eq!(zero_measured.findings.len(), 1);
+    assert_eq!(zero_measured.findings[0].id, "zero:unexecuted");
+    assert_eq!(zero_measured.findings[0].message, "listed=5 executed=0");
+
+    let mixed = coverage_model_with(vec![
+        Function {
+            line: 1,
+            end_line: 6,
+            decision_points: 1,
+            source_lines: 5,
+            name: Some("unreported".to_owned()),
+            cognitive_complexity: 1,
+            coverage: None,
+        },
+        Function {
+            line: 8,
+            end_line: 14,
+            decision_points: 2,
+            source_lines: 5,
+            name: Some("unexecuted".to_owned()),
+            cognitive_complexity: 2,
+            coverage: Some(FunctionCoverage {
+                listed_lines: 5,
+                executed_lines: 0,
+            }),
+        },
+        Function {
+            line: 16,
+            end_line: 22,
+            decision_points: 2,
+            source_lines: 5,
+            name: Some("partial".to_owned()),
+            cognitive_complexity: 2,
+            coverage: Some(FunctionCoverage {
+                listed_lines: 5,
+                executed_lines: 3,
+            }),
+        },
+    ]);
+
+    let mixed_measured = plugin.measure(&mixed).expect("measure mixed coverage");
+    assert!((mixed_measured.ratio - 0.7).abs() < 1e-9);
+    assert!((mixed_measured.numerator - 7.0).abs() < 1e-9);
+    assert!((mixed_measured.denominator - 10.0).abs() < 1e-9);
+    let summary: Vec<(&str, &str)> = mixed_measured
+        .findings
+        .iter()
+        .map(|finding| (finding.id.as_str(), finding.message.as_str()))
+        .collect();
+    assert_eq!(
+        summary,
+        vec![
+            ("absent:unreported", "absent"),
+            ("zero:unexecuted", "listed=5 executed=0"),
+            ("covered:partial", "listed=5 executed=3"),
+        ]
+    );
+}
+
+fn load_probe_language(name: &str, wasm_file: &str) -> codeint_plugin_host::WasmLanguagePlugin {
+    let wasm_path = sandbox_probe_wasm(wasm_file);
+    let declaration = declaration_for(name, &wasm_path);
+    load_language_plugin(Path::new("."), &declaration, &PluginHostConfig::default())
+        .unwrap_or_else(|error| panic!("{name} Language plugin loads: {error}"))
+}
+
+fn load_probe_metric(name: &str, wasm_file: &str) -> codeint_plugin_host::WasmMetricPlugin {
+    let wasm_path = sandbox_probe_wasm(wasm_file);
+    let declaration = declaration_with_kind(name, PluginKind::Metric, &wasm_path);
+    load_metric_plugin(Path::new("."), &declaration, &PluginHostConfig::default())
+        .unwrap_or_else(|error| panic!("{name} Metric plugin loads: {error}"))
+}
+
+fn language_facts(
+    language: &str,
+    has_coverage: bool,
+    has_hazard_rules: bool,
+    has_imports: bool,
+) -> LanguageFacts {
+    LanguageFacts {
+        language: language.to_owned(),
+        has_coverage,
+        has_hazard_rules,
+        has_imports,
+    }
+}
+
+fn model_with_language_facts(facts: LanguageFacts, with_file: bool) -> CodeModel {
+    let base = if with_file {
+        coverage_model_with(Vec::new())
+    } else {
+        CodeModel::default()
+    };
+    CodeModel {
+        languages: vec![facts],
+        ..base
+    }
+}
+
+fn assert_two_language_fact_probe(
+    plugin: &codeint_plugin_host::WasmMetricPlugin,
+    first: (LanguageFacts, bool, f64, (&str, &str)),
+    second: (LanguageFacts, bool, f64, (&str, &str)),
+    expected_merged_ratio: f64,
+    expected_merged: Vec<(&str, &str)>,
+) {
+    let first_model = model_with_language_facts(first.0, first.1);
+    let second_model = model_with_language_facts(second.0, second.1);
+    let first_measured = plugin
+        .measure(&first_model)
+        .expect("measure first language");
+    let second_measured = plugin
+        .measure(&second_model)
+        .expect("measure second language");
+    assert!((first_measured.ratio - first.2).abs() < 1e-9);
+    assert_eq!(summarize_findings(&first_measured), vec![first.3]);
+    assert!((second_measured.ratio - second.2).abs() < 1e-9);
+    assert_eq!(summarize_findings(&second_measured), vec![second.3]);
+
+    let merged = CodeModel::merge([first_model, second_model]);
+    let source_sets = merged.into_source_sets();
+    let multi_measured = plugin
+        .measure(source_sets.get(SourceSet::Production))
+        .expect("measure merged multi-language model");
+    assert!((multi_measured.ratio - expected_merged_ratio).abs() < 1e-9);
+    assert_eq!(summarize_findings(&multi_measured), expected_merged);
+}
+
+#[test]
+fn language_plugin_sets_program_start_mark_and_metric_plugin_reads_it() {
+    let language = load_probe_language(
+        "program-start-language",
+        "program_start_language_plugin.wasm",
+    );
+    let metric = load_probe_metric("program-start-metric", "program_start_metric_plugin.wasm");
+
+    let main_path = RepoPath::new("cmd/app/main.prog").expect("valid repo path");
+    let lib_path = RepoPath::new("internal/util/helper.prog").expect("valid repo path");
+
+    let main_model = language
+        .lower(&main_path, "program main\nrun()\n")
+        .expect("lowers program-start file");
+    let lib_model = language
+        .lower(&lib_path, "library util\nhelper()\n")
+        .expect("lowers library file");
+
+    assert!(main_model.program_start);
+    assert!(!lib_model.program_start);
+
+    let code_model = CodeModel {
+        files: vec![
+            SourceFile {
+                path: main_path.clone(),
+                model: main_model,
+            },
+            SourceFile {
+                path: lib_path,
+                model: lib_model,
+            },
+        ],
+        ..CodeModel::default()
+    };
+
+    let measured = metric
+        .measure(&code_model)
+        .expect("Metric plugin reads program_start from Code model");
+    assert_eq!(metric.key(), "program_starts");
+    assert!((measured.ratio - 0.5).abs() < 1e-9);
+    assert!((measured.numerator - 1.0).abs() < 1e-9);
+    assert!((measured.denominator - 2.0).abs() < 1e-9);
+    assert_eq!(measured.findings.len(), 1);
+    assert_eq!(measured.findings[0].id, "program-start:cmd/app/main.prog");
+    assert_eq!(measured.findings[0].path, main_path);
+    assert_eq!(measured.findings[0].message, "program start");
+}
+
+#[test]
+fn built_in_language_plugins_never_set_program_start() {
+    use codeint_lang_dart::Dart;
+    use codeint_lang_php::Php;
+    use codeint_lang_python::Python;
+    use codeint_lang_rust::Rust;
+    use codeint_lang_ts::TypeScriptAndJavaScript;
+
+    let cases: [(&str, &dyn LanguagePlugin, &str, &str); 5] = [
+        (
+            "typescript-javascript",
+            &TypeScriptAndJavaScript,
+            "src/main.ts",
+            "export function main(): void {\n  console.log('hi');\n}\nmain();\n",
+        ),
+        (
+            "rust",
+            &Rust,
+            "src/main.rs",
+            "fn main() {\n    println!(\"hi\");\n}\n",
+        ),
+        (
+            "php",
+            &Php,
+            "public/index.php",
+            " Vec<(&str, &str)> {
+    measurement
+        .findings
+        .iter()
+        .map(|finding| (finding.id.as_str(), finding.message.as_str()))
+        .collect()
+}
+
+#[test]
+fn metric_plugin_reads_per_language_coverage_statement() {
+    let wasm_path = sandbox_probe_wasm("coverage_reader_metric_plugin.wasm");
+    let declaration = declaration_with_kind("coverage-reader", PluginKind::Metric, &wasm_path);
+    let plugin = load_metric_plugin(Path::new("."), &declaration, &PluginHostConfig::default())
+        .expect("coverage reader Metric plugin loads");
+
+    let absent_language = CodeModel {
+        languages: vec![LanguageFacts {
+            language: "typescript-javascript".to_owned(),
+            has_coverage: false,
+            has_hazard_rules: false,
+            has_imports: true,
+        }],
+        ..coverage_model_with(Vec::new())
+    };
+    let covered_language = CodeModel {
+        languages: vec![LanguageFacts {
+            language: "typescript-javascript".to_owned(),
+            has_coverage: true,
+            has_hazard_rules: false,
+            has_imports: true,
+        }],
+        ..coverage_model_with(Vec::new())
+    };
+
+    let absent_measured = plugin
+        .measure(&absent_language)
+        .expect("measure language without coverage");
+    let covered_measured = plugin
+        .measure(&covered_language)
+        .expect("measure language with coverage");
+
+    assert_eq!(
+        summarize_findings(&absent_measured),
+        vec![(
+            "language:typescript-javascript:absent",
+            "language=typescript-javascript has_coverage=false",
+        )]
+    );
+    assert_eq!(
+        summarize_findings(&covered_measured),
+        vec![(
+            "language:typescript-javascript:covered",
+            "language=typescript-javascript has_coverage=true",
+        )]
+    );
+
+    let rust_covered = CodeModel {
+        files: vec![SourceFile {
+            path: RepoPath::new("src/lib.rs").expect("valid repo path"),
+            model: FileModel {
+                source_set: SourceSet::Production,
+                source_lines: 10,
+                functions: Vec::new(),
+                tokens: Vec::new(),
+                flagged_lines: Vec::new(),
+                hazard_lines: Vec::new(),
+                runtime_imports: Vec::new(),
+                program_start: false,
+            },
+        }],
+        languages: vec![LanguageFacts {
+            language: "rust".to_owned(),
+            has_coverage: true,
+            has_hazard_rules: false,
+            has_imports: true,
+        }],
+        ..CodeModel::default()
+    };
+    let merged = CodeModel::merge([absent_language, rust_covered]);
+    let source_sets = merged.into_source_sets();
+
+    let multi_measured = plugin
+        .measure(source_sets.get(SourceSet::Production))
+        .expect("measure merged multi-language model");
+
+    assert_eq!(
+        summarize_findings(&multi_measured),
+        vec![
+            ("language:rust:covered", "language=rust has_coverage=true"),
+            (
+                "language:typescript-javascript:absent",
+                "language=typescript-javascript has_coverage=false",
+            ),
+        ]
+    );
+}
+
+#[test]
+fn built_in_language_plugins_have_no_hazard_rules() {
+    use codeint_lang_dart::Dart;
+    use codeint_lang_php::Php;
+    use codeint_lang_python::Python;
+    use codeint_lang_rust::Rust;
+    use codeint_lang_ts::TypeScriptAndJavaScript;
+
+    let plugins: [(&str, &dyn LanguagePlugin); 5] = [
+        ("typescript-javascript", &TypeScriptAndJavaScript),
+        ("rust", &Rust),
+        ("php", &Php),
+        ("dart", &Dart),
+        ("python", &Python),
+    ];
+
+    for (name, plugin) in plugins {
+        assert!(
+            !plugin.has_hazard_rules(),
+            "{name} built-in Language plugin must report has_hazard_rules = false"
+        );
+        assert!(
+            plugin.hazard_rules().is_empty(),
+            "{name} built-in Language plugin must list no hazard rules"
+        );
+    }
+}
+
+#[test]
+fn language_plugin_exports_hazard_rules_across_wasm_boundary() {
+    let wasm_path = sandbox_probe_wasm("hazard_rules_language_plugin.wasm");
+    let declaration = declaration_for("hazard-rules-language", &wasm_path);
+    let plugin = load_language_plugin(Path::new("."), &declaration, &PluginHostConfig::default())
+        .expect("hazard-rules Language plugin loads");
+
+    assert!(plugin.has_hazard_rules());
+    assert_eq!(
+        plugin.hazard_rules(),
+        vec![
+            "delete-without-where".to_owned(),
+            "leading-wildcard-like".to_owned(),
+        ]
+    );
+}
+
+#[test]
+fn metric_plugin_reads_per_language_hazard_rules_statement() {
+    let plugin = load_probe_metric("hazard-facts", "hazard_facts_metric_plugin.wasm");
+    assert_eq!(plugin.key(), "hazard_facts");
+    assert_two_language_fact_probe(
+        &plugin,
+        (
+            LanguageFacts {
+                language: "typescript-javascript".to_owned(),
+                has_coverage: false,
+                has_hazard_rules: false,
+                has_imports: true,
+            },
+            true,
+            0.0,
+            (
+                "hazard-rules:typescript-javascript:absent",
+                "language=typescript-javascript has_hazard_rules=false",
+            ),
+        ),
+        (
+            LanguageFacts {
+                language: "sql".to_owned(),
+                has_coverage: false,
+                has_hazard_rules: true,
+                has_imports: false,
+            },
+            false,
+            1.0,
+            (
+                "hazard-rules:sql:enabled",
+                "language=sql has_hazard_rules=true",
+            ),
+        ),
+        0.5,
+        vec![
+            (
+                "hazard-rules:sql:enabled",
+                "language=sql has_hazard_rules=true",
+            ),
+            (
+                "hazard-rules:typescript-javascript:absent",
+                "language=typescript-javascript has_hazard_rules=false",
+            ),
+        ],
+    );
+}
+
+#[test]
+fn language_plugin_resolves_multi_file_imports_and_metric_plugin_reads_them() {
+    let language = load_probe_language("folder-import", "folder_import_language_plugin.wasm");
+    let metric = load_probe_metric("imports-reader", "imports_reader_metric_plugin.wasm");
+
+    let main_path = RepoPath::new("src/main.fld").expect("valid repo path");
+    let alpha_path = RepoPath::new("pkg/util/alpha.fld").expect("valid repo path");
+    let beta_path = RepoPath::new("pkg/util/beta.fld").expect("valid repo path");
+    let repo_paths = vec![main_path.clone(), alpha_path.clone(), beta_path.clone()];
+
+    let main_model = language
+        .lower(&main_path, "use pkg/util\nfn main()\n")
+        .expect("lower main.fld");
+    let main_file = SourceFile {
+        path: main_path.clone(),
+        model: main_model,
+    };
+
+    let resolved = resolve_runtime_imports(&language, &repo_paths, Vec::new(), &[&main_file])
+        .expect("resolve multi-file folder import");
+    assert_eq!(resolved.len(), 1);
+    assert_eq!(
+        resolved[0].resolution,
+        ImportResolution::Resolved(vec![alpha_path.clone(), beta_path.clone()])
+    );
+
+    let code_model = CodeModel {
+        files: vec![main_file],
+        runtime_imports: resolved,
+        ..CodeModel::default()
+    };
+    let measured = metric
+        .measure(&code_model)
+        .expect("Metric plugin reads multi-file resolved import");
+    assert_eq!(metric.key(), "resolved_links");
+    assert!((measured.ratio - 1.0).abs() < 1e-9);
+    assert_eq!(measured.findings.len(), 1);
+    assert_eq!(
+        measured.findings[0].message,
+        "pkg/util -> [pkg/util/alpha.fld, pkg/util/beta.fld]"
+    );
+
+    let empty_model = language
+        .lower(&main_path, "use empty\nfn main()\n")
+        .expect("lower empty-import file");
+    let empty_file = SourceFile {
+        path: main_path.clone(),
+        model: empty_model,
+    };
+    let empty_err = resolve_runtime_imports(&language, &repo_paths, Vec::new(), &[&empty_file])
+        .expect_err("empty resolved list must fail");
+    assert!(
+        matches!(
+            empty_err,
+            ResolveError::EmptyResolution {
+                ref importer,
+                ref specifier,
+            } if importer == &main_path && specifier == "empty"
+        ),
+        "unexpected error: {empty_err:?}"
+    );
+
+    let partial_model = language
+        .lower(&main_path, "use partial-missing\nfn main()\n")
+        .expect("lower partial-missing file");
+    let partial_file = SourceFile {
+        path: main_path,
+        model: partial_model,
+    };
+    let partial_err = resolve_runtime_imports(&language, &repo_paths, Vec::new(), &[&partial_file])
+        .expect_err("unknown target inside multi-file list must fail");
+    assert!(
+        matches!(
+            partial_err,
+            ResolveError::UnknownTarget { ref target, .. }
+                if target == "missing/does_not_exist.fld"
+        ),
+        "unexpected error: {partial_err:?}"
+    );
+}
+
+#[test]
+fn language_plugin_reports_hazard_lines_and_metric_plugin_reads_them() {
+    let language =
+        load_probe_language("hazard-rules-language", "hazard_rules_language_plugin.wasm");
+    let metric = load_probe_metric("hazard-facts", "hazard_facts_metric_plugin.wasm");
+
+    let unsafe_path = RepoPath::new("queries/unsafe.haz").expect("valid repo path");
+    let clean_path = RepoPath::new("queries/clean.haz").expect("valid repo path");
+    let unsafe_source = "SELECT id FROM users;\nDELETE FROM sessions;\nSELECT name FROM users WHERE name LIKE '%admin';\nDELETE FROM audit_logs WHERE id = 1;\n";
+    let clean_source = "SELECT id FROM users WHERE id = 1;\n";
+
+    let unsafe_model = language
+        .lower(&unsafe_path, unsafe_source)
+        .expect("lowers file with hazard lines");
+    let clean_model = language
+        .lower(&clean_path, clean_source)
+        .expect("lowers clean file");
+
+    assert_eq!(
+        unsafe_model.hazard_lines,
+        vec![
+            HazardLine {
+                line: 2,
+                rule: "delete-without-where".to_owned(),
+            },
+            HazardLine {
+                line: 3,
+                rule: "leading-wildcard-like".to_owned(),
+            },
+        ]
+    );
+    let HazardLine { line, rule } = &unsafe_model.hazard_lines[0];
+    assert_eq!(*line, 2);
+    assert_eq!(rule, "delete-without-where");
+    assert!(clean_model.hazard_lines.is_empty());
+
+    let listed_rules = language.hazard_rules();
+    let line_count = unsafe_source.lines().count();
+    for hazard in &unsafe_model.hazard_lines {
+        assert!(hazard.line >= 1 && (hazard.line as usize) <= line_count);
+        assert!(listed_rules.contains(&hazard.rule));
+    }
+
+    let code_model = CodeModel {
+        files: vec![
+            SourceFile {
+                path: clean_path,
+                model: clean_model,
+            },
+            SourceFile {
+                path: unsafe_path.clone(),
+                model: unsafe_model,
+            },
+        ],
+        languages: vec![LanguageFacts {
+            language: "hazard-lang".to_owned(),
+            has_coverage: false,
+            has_hazard_rules: true,
+            has_imports: true,
+        }],
+        ..CodeModel::default()
+    };
+
+    let measured = metric
+        .measure(&code_model)
+        .expect("Metric plugin reads hazard_lines from Code model");
+
+    assert_eq!(
+        summarize_findings(&measured),
+        vec![
+            (
+                "hazard-rules:hazard-lang:enabled",
+                "language=hazard-lang has_hazard_rules=true",
+            ),
+            (
+                "hazard:queries/unsafe.haz:2:delete-without-where",
+                "hazard rule=delete-without-where",
+            ),
+            (
+                "hazard:queries/unsafe.haz:3:leading-wildcard-like",
+                "hazard rule=leading-wildcard-like",
+            ),
+        ]
+    );
+    assert_eq!(measured.findings[1].path, unsafe_path);
+    assert_eq!(measured.findings[1].line, 2);
+    assert_eq!(measured.findings[2].path, unsafe_path);
+    assert_eq!(measured.findings[2].line, 3);
+}
+
+#[test]
+fn built_in_language_plugins_state_they_have_imports() {
+    use codeint_lang_dart::Dart;
+    use codeint_lang_php::Php;
+    use codeint_lang_python::Python;
+    use codeint_lang_rust::Rust;
+    use codeint_lang_ts::TypeScriptAndJavaScript;
+
+    let plugins: [(&str, &dyn LanguagePlugin); 5] = [
+        ("typescript-javascript", &TypeScriptAndJavaScript),
+        ("rust", &Rust),
+        ("php", &Php),
+        ("dart", &Dart),
+        ("python", &Python),
+    ];
+
+    for (name, plugin) in plugins {
+        assert!(
+            plugin.has_imports(),
+            "{name} built-in Language plugin must report has_imports = true"
+        );
+    }
+}
+
+#[test]
+fn language_plugin_exports_has_imports_false_across_wasm_boundary() {
+    let wasm_path = sandbox_probe_wasm("no_imports_language_plugin.wasm");
+    let declaration = declaration_for("no-imports-language", &wasm_path);
+    let plugin = load_language_plugin(Path::new("."), &declaration, &PluginHostConfig::default())
+        .expect("no-imports Language plugin loads");
+
+    assert_eq!(plugin.extensions(), vec!["noimp"]);
+    assert!(!plugin.has_imports());
+    let lowered = plugin
+        .lower(
+            &RepoPath::new("queries/select.noimp").expect("valid repo path"),
+            "fn select_users()\n",
+        )
+        .expect("no-imports Language plugin lowers .noimp file");
+    assert_eq!(lowered.source_lines, 1);
+    assert_eq!(lowered.functions.len(), 1);
+    assert!(lowered.runtime_imports.is_empty());
+}
+
+#[test]
+fn metric_plugin_reads_per_language_has_imports_statement() {
+    let plugin = load_probe_metric("import-capability", "import_capability_metric_plugin.wasm");
+    assert_eq!(plugin.key(), "import_capability");
+    assert_two_language_fact_probe(
+        &plugin,
+        (
+            language_facts("typescript-javascript", false, false, true),
+            true,
+            1.0,
+            (
+                "imports:typescript-javascript:imports",
+                "language=typescript-javascript has_imports=true",
+            ),
+        ),
+        (
+            language_facts("no-imports-lang", false, false, false),
+            false,
+            0.0,
+            (
+                "imports:no-imports-lang:no-imports",
+                "language=no-imports-lang has_imports=false",
+            ),
+        ),
+        0.5,
+        vec![
+            (
+                "imports:no-imports-lang:no-imports",
+                "language=no-imports-lang has_imports=false",
+            ),
+            (
+                "imports:typescript-javascript:imports",
+                "language=typescript-javascript has_imports=true",
+            ),
+        ],
+    );
+}
diff --git a/crates/report/HOW-TO.md b/crates/report/HOW-TO.md
index 6d80a7e1..80fce640 100644
--- a/crates/report/HOW-TO.md
+++ b/crates/report/HOW-TO.md
@@ -11,6 +11,7 @@ let report = Report::summarize(
         plugin: "typescript-javascript".to_owned(),
         model,
         reference_ranges,
+        has_imports: true,
     }],
     submodules,
     FindingsShown::default(),
@@ -28,6 +29,8 @@ if !report.over_budget().is_empty() {
 - `Report::summarize` splits the merged `CodeModel` by Source set, computes all Metrics per Source set, evaluates Dependency hygiene per Language plugin when manifests are present, and checks every `Budget`.
 - Use `Report::summarize_with_options` and `CommitMeasurement::of_languages_with_options` to pass `DependenciesConfig` (including `dependencies.ignore`), `Boundaries`, external Metric plugins, `OwnershipOptions`, and optional precomputed `orphan_files`, `dependency_hygiene`, and `dependency_hygiene_by_language` (used when `--package` evaluates cross-package reachability and workspace hoisting before filtering).
 - When two or more Language plugins measure files, the report adds a `languages` section per plugin and omits Reference ranges on the combined totals.
+- When `MeasuredLanguage::has_imports` is `false`, TOON, JSON, and Markdown reports omit `import_cycles`, `orphan_files`, `boundaries`, and `dependencies` for that language and emit a one-line `import_metrics_note`, and SARIF emits no import Findings for files of that language.
+- Repository totals and Budgets for `import_cycles`, `orphan_files`, `boundaries`, and `dependencies` (including Workspace package `import_cycles`) count only languages with `has_imports: true` on both sides of each ratio, and stay absent when no measured language has imports.
 - `render` formats the report as `Toon`, `Json`, `Sarif`, or `Markdown`.
 - SARIF output emits one result per listed Finding and stores each Finding id in `partialFingerprints.codeintFindingId`.
   When overlapping or transitively related Clone groups form a Clone family across three or more locations, `duplication.clone_families` lists the Clone families worst-first by `duplicated_lines` in JSON, TOON, Markdown, and MCP, and SARIF emits one consolidated result per Clone family instead of duplicate results for its member Clone groups.
diff --git a/crates/report/src/coupling.rs b/crates/report/src/coupling.rs
index 6819ba3e..5ae1724f 100644
--- a/crates/report/src/coupling.rs
+++ b/crates/report/src/coupling.rs
@@ -113,8 +113,10 @@ impl CouplingReport {
 fn direct_import_pairs(model: &CodeModel) -> BTreeSet<(RepoPath, RepoPath)> {
     let mut edges = BTreeSet::new();
     for import in &model.runtime_imports {
-        if let ImportResolution::Resolved(target) = &import.resolution {
-            edges.insert(ordered_pair(&import.importer, target));
+        if let ImportResolution::Resolved(targets) = &import.resolution {
+            for target in targets {
+                edges.insert(ordered_pair(&import.importer, target));
+            }
         }
     }
     edges
diff --git a/crates/report/src/diff.rs b/crates/report/src/diff.rs
index 8ef467a5..d0b37d43 100644
--- a/crates/report/src/diff.rs
+++ b/crates/report/src/diff.rs
@@ -105,7 +105,8 @@ struct SourceSetChanges {
     cognitive_complexity: MetricChanges,
     duplication: DuplicationChanges,
     verbosity: MetricChanges,
-    import_cycles: MetricChanges,
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    import_cycles: Option>,
     #[serde(default, skip_serializing_if = "Option::is_none")]
     boundaries: Option>,
     #[serde(default, skip_serializing_if = "Option::is_none")]
@@ -298,7 +299,10 @@ impl DiffReport {
                                 families.unlisted_clone_family_group_ids.as_slice()
                             }),
                         flagged_lines: &changes.verbosity.new.listed,
-                        import_cycles: &changes.import_cycles.new.listed,
+                        import_cycles: changes
+                            .import_cycles
+                            .as_ref()
+                            .map_or(&[], |cycles| cycles.new.listed.as_slice()),
                         boundaries: changes
                             .boundaries
                             .as_ref()
@@ -536,13 +540,13 @@ fn over_budget(source_sets: &SourceSetChangesSections, budgets: &Budgets) -> Vec
                     Metric::Verbosity.key(),
                     changes.verbosity.head_ratio.0,
                 ),
-                (
-                    source_set,
-                    Metric::ImportCycles.key(),
-                    changes.import_cycles.head_ratio.0,
-                ),
             ]
             .into_iter()
+            .chain(
+                changes.import_cycles.iter().map(move |cycles| {
+                    (source_set, Metric::ImportCycles.key(), cycles.head_ratio.0)
+                }),
+            )
             .chain(
                 changes
                     .boundaries
@@ -586,12 +590,13 @@ impl SourceSetChanges {
                 .regressions(source_set, Metric::Duplication.key(), limits),
             self.verbosity
                 .regressions(source_set, Metric::Verbosity.key(), limits),
-            self.import_cycles
-                .regressions(source_set, Metric::ImportCycles.key(), limits),
         ]
         .into_iter()
         .flatten()
         .collect();
+        if let Some(import_cycles) = &self.import_cycles {
+            found.extend(import_cycles.regressions(source_set, Metric::ImportCycles.key(), limits));
+        }
         if let Some(boundaries) = &self.boundaries {
             found.extend(boundaries.regressions(source_set, "boundaries", limits));
         }
@@ -903,6 +908,15 @@ fn source_set_changes(
             },
         );
     }
+    let import_cycles = match (base.import_cycles, head.import_cycles) {
+        (None, None) => None,
+        (base_cycles, head_cycles) => Some(classify(
+            base_cycles.unwrap_or_default(),
+            head_cycles.unwrap_or_default(),
+            shown,
+            ownership,
+        )),
+    };
     let boundaries = match (base.boundaries, head.boundaries) {
         (None, None) => None,
         (base_boundaries, head_boundaries) => Some(classify(
@@ -957,7 +971,7 @@ fn source_set_changes(
             clone_families,
         },
         verbosity: classify(base.verbosity, head.verbosity, shown, ownership),
-        import_cycles: classify(base.import_cycles, head.import_cycles, shown, ownership),
+        import_cycles,
         boundaries,
         orphan_files,
         external_metrics,
diff --git a/crates/report/src/diff/markdown.rs b/crates/report/src/diff/markdown.rs
index 23649411..ae9b6fe7 100644
--- a/crates/report/src/diff/markdown.rs
+++ b/crates/report/src/diff/markdown.rs
@@ -93,8 +93,10 @@ fn metric_rows(source_set: &str, changes: &SourceSetChanges) -> Vec>
         ),
         metric_row(source_set, "Duplication", &changes.duplication.groups),
         metric_row(source_set, "Verbosity", &changes.verbosity),
-        metric_row(source_set, "Import cycles", &changes.import_cycles),
     ];
+    if let Some(import_cycles) = &changes.import_cycles {
+        rows.push(metric_row(source_set, "Import cycles", import_cycles));
+    }
     if let Some(boundaries) = &changes.boundaries {
         rows.push(metric_row(source_set, "Boundaries", boundaries));
     }
@@ -169,13 +171,15 @@ fn findings_blocks(changes: &SourceSetChanges) -> Vec {
         &FLAGGED_LINE,
         |listed| findings_table(&FLAGGED_LINE_COLUMNS, listed, flagged_line_row),
     );
-    push_changes(
-        &mut blocks,
-        "Import cycles",
-        &changes.import_cycles,
-        &IMPORT_CYCLE,
-        |listed| list(listed.iter().map(import_cycle_item)),
-    );
+    if let Some(import_cycles) = &changes.import_cycles {
+        push_changes(
+            &mut blocks,
+            "Import cycles",
+            import_cycles,
+            &IMPORT_CYCLE,
+            |listed| list(listed.iter().map(import_cycle_item)),
+        );
+    }
     if let Some(boundaries) = &changes.boundaries {
         push_changes(&mut blocks, "Boundaries", boundaries, &FINDING, |listed| {
             findings_table(&BOUNDARY_FINDING_COLUMNS, listed, boundary_finding_row)
diff --git a/crates/report/src/diff/tests.rs b/crates/report/src/diff/tests.rs
index d4cdcebb..37c7307b 100644
--- a/crates/report/src/diff/tests.rs
+++ b/crates/report/src/diff/tests.rs
@@ -45,3 +45,140 @@ fn new_findings_saturates_when_left_out_is_usize_max() {
 
     assert_eq!(changes.new_findings(), usize::MAX);
 }
+
+fn single_file_model(
+    path: &str,
+    language: &str,
+    has_imports: bool,
+    program_start: bool,
+) -> (codeint_model::RepoPath, codeint_model::CodeModel) {
+    use codeint_model::{CodeModel, FileModel, LanguageFacts, RepoPath, SourceFile, SourceSet};
+
+    let repo_path = RepoPath::new(path).expect("path");
+    let model = CodeModel {
+        files: vec![SourceFile {
+            path: repo_path.clone(),
+            model: FileModel {
+                source_set: SourceSet::Production,
+                source_lines: 2,
+                functions: Vec::new(),
+                tokens: Vec::new(),
+                flagged_lines: Vec::new(),
+                hazard_lines: Vec::new(),
+                runtime_imports: Vec::new(),
+                program_start,
+            },
+        }],
+        languages: vec![LanguageFacts {
+            language: language.to_owned(),
+            has_coverage: false,
+            has_hazard_rules: false,
+            has_imports,
+        }],
+        ..CodeModel::default()
+    };
+    (repo_path, model)
+}
+
+#[test]
+fn no_imports_only_models_omit_import_cycles_and_dependencies_in_diff_and_trend() {
+    use codeint_config::{
+        Budgets, CalendarDay, DependenciesConfig, DuplicationConfig, FindingsShown,
+        RegressionLimits, ReportFormat, TrendFormat,
+    };
+    use codeint_model::{CodeModel, DeclaredDep, DepKind, DependencyManifest, RepoPath};
+
+    use crate::{
+        BaseCommit, CommitMeasurement, DiffReport, Head, TraceReport, TrendPoint, TrendReport,
+    };
+
+    let (sql_path, no_imports_model) = single_file_model("queries/users.sql", "sql", false, true);
+    let unmeasured_js_with_manifest = CodeModel {
+        dependency_manifests: vec![DependencyManifest {
+            package_root: String::new(),
+            path: RepoPath::new("package.json").expect("manifest path"),
+        }],
+        declared_dependencies: vec![DeclaredDep {
+            package_root: String::new(),
+            name: "lodash".to_owned(),
+            kind: DepKind::Runtime,
+        }],
+        ..CodeModel::default()
+    };
+
+    let measurement = |models: Vec| {
+        CommitMeasurement::of_languages_with_options(
+            models,
+            &[],
+            None,
+            &DependenciesConfig::default(),
+            DuplicationConfig::default(),
+            None,
+            None,
+        )
+        .expect("commit measurement")
+    };
+    let base_m = measurement(vec![
+        no_imports_model.clone(),
+        unmeasured_js_with_manifest.clone(),
+    ]);
+    let head_m = measurement(vec![
+        no_imports_model.clone(),
+        unmeasured_js_with_manifest.clone(),
+    ]);
+    let budgets = Budgets::default();
+    let diff = DiffReport::compare(
+        BaseCommit {
+            git_ref: "main".to_owned(),
+            merge_base: "abc".to_owned(),
+        },
+        Head::WorkingTree,
+        base_m,
+        head_m,
+        FindingsShown::default(),
+        &budgets,
+        &RegressionLimits::default(),
+    );
+    assert!(diff.failure_messages().is_empty());
+    let diff_json: serde_json::Value =
+        serde_json::from_str(&diff.render(ReportFormat::Json).expect("diff json")).expect("json");
+    assert!(diff_json.get("dependencies").is_none());
+    assert!(
+        diff_json["source_sets"]["production"]
+            .get("import_cycles")
+            .is_none()
+    );
+    let diff_md = diff.render(ReportFormat::Markdown).expect("diff markdown");
+    assert!(!diff_md.contains("Import cycles"));
+
+    let trend = TrendReport::of(vec![TrendPoint {
+        commit: "abc1234".to_owned(),
+        committed_on: CalendarDay::containing(1_700_000_000),
+        measurement: measurement(vec![no_imports_model.clone(), unmeasured_js_with_manifest]),
+    }]);
+    let trend_json: serde_json::Value =
+        serde_json::from_str(&trend.render(TrendFormat::Json).expect("trend json")).expect("json");
+    assert!(
+        trend_json["source_sets"]["production"][0]
+            .get("import_cycles")
+            .is_none()
+    );
+    let trend_md = trend.render(TrendFormat::Markdown).expect("trend markdown");
+    assert!(!trend_md.contains("Import cycles"));
+
+    let traced = TraceReport::trace(&no_imports_model, &sql_path, &sql_path, false, 5)
+        .expect("trace no-imports");
+    assert!(traced.from_entry_point.is_none());
+    assert!(traced.to_entry_point.is_none());
+}
+
+#[test]
+fn trace_omits_program_start_mark_for_non_runtime_tooling_paths() {
+    use crate::TraceReport;
+
+    let (script, model) = single_file_model("scripts/main.prog", "program-start", true, true);
+
+    let traced = TraceReport::trace(&model, &script, &script, false, 5).expect("trace");
+    assert!(traced.from_entry_point.is_none());
+    assert!(traced.to_entry_point.is_none());
+}
diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs
index 071d9b2c..c9560ec1 100644
--- a/crates/report/src/lib.rs
+++ b/crates/report/src/lib.rs
@@ -57,7 +57,7 @@ pub use measurement::CommitMeasurement;
 pub use ownership::OwnershipOptions;
 pub use saved::{SavedReport, SavedReportError};
 pub use schema::{ExitCodeSchema, LanguageSchema, McpToolSchema, MetricSchema, SchemaReport};
-pub use trace::TraceReport;
+pub use trace::{TraceMultiFileImport, TraceReport};
 pub use trend::{TrendPoint, TrendReport};
 
 use dependencies::{ImportedDependencyRow, UnusedDependencyRow};
@@ -69,6 +69,7 @@ const NOT_PUBLISHED_FOR_THIS_LANGUAGE: &str = "no published Reference range for
 const NOT_SHOWN_FOR_SEVERAL_LANGUAGES: &str =
     "not shown, because the measured files are in more than one language";
 const NOT_SHOWN_FOR_NEAR_CLONES: &str = "not shown, because near-clone detection is enabled (Reference ranges are calibrated for exact Clone groups)";
+const NO_IMPORTS_METRIC_NOTE: &str = "This language has no imports, so Import cycles, Orphan files, Import boundaries, and Dependency hygiene are not measured.";
 
 #[derive(Debug, thiserror::Error)]
 pub enum ReportError {
@@ -109,12 +110,15 @@ pub struct MeasuredLanguage {
     pub plugin: String,
     pub model: CodeModel,
     pub reference_ranges: ReferenceRanges,
+    pub has_imports: bool,
 }
 
 #[derive(Debug, Serialize, Deserialize)]
 struct MeasuredSection {
     files: usize,
     source_lines: u64,
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    import_metrics_note: Option,
     source_sets: SourceSetSections,
     #[serde(default, skip_serializing_if = "Option::is_none")]
     dependencies: Option,
@@ -252,7 +256,8 @@ struct SourceSetSection {
     cognitive_complexity: MetricSection,
     duplication: DuplicationSection,
     verbosity: MetricSection,
-    import_cycles: ImportCyclesSection,
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    import_cycles: Option,
     #[serde(default, skip_serializing_if = "Option::is_none")]
     boundaries: Option,
     #[serde(default, skip_serializing_if = "Option::is_none")]
@@ -365,7 +370,8 @@ struct PackageSection {
     cognitive_complexity: PackageCognitiveComplexity,
     duplication: PackageDuplication,
     verbosity: PackageVerbosity,
-    import_cycles: PackageImportCycles,
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    import_cycles: Option,
 }
 
 #[derive(Debug, Serialize, Deserialize)]
@@ -1067,28 +1073,37 @@ struct SectionOptions<'a> {
     duplication: DuplicationConfig,
     orphan_files: Option<&'a OrphanFiles>,
     ownership: OwnershipOptions<'a>,
+    has_imports: bool,
 }
 
 impl SourceSetSections {
     fn new(
         source_sets: &SourceSets,
+        import_source_sets: Option<&SourceSets>,
         ranges: &ReferenceRangeScope,
         options: SectionOptions<'_>,
     ) -> Result {
         let mut sections = SourceSetSections::default();
         for (source_set, model) in source_sets.iter() {
             if !model.files.is_empty() {
+                let import_model = import_source_sets
+                    .map(|sets| sets.get(source_set))
+                    .filter(|imports| !imports.files.is_empty());
                 let source_set_options = SectionOptions {
-                    boundaries: options
-                        .boundaries
-                        .filter(|config| config.applies_to_source_set(source_set)),
+                    boundaries: options.boundaries.filter(|config| {
+                        import_model.is_some() && config.applies_to_source_set(source_set)
+                    }),
                     orphan_files: options
                         .orphan_files
-                        .filter(|_| source_set == SourceSet::Production),
+                        .filter(|_| import_model.is_some() && source_set == SourceSet::Production),
                     ..options
                 };
-                *sections.slot(source_set) =
-                    Some(SourceSetSection::new(model, ranges, source_set_options)?);
+                *sections.slot(source_set) = Some(SourceSetSection::new(
+                    model,
+                    import_model,
+                    ranges,
+                    source_set_options,
+                )?);
             }
         }
         Ok(sections)
@@ -1119,13 +1134,15 @@ impl SourceSetSections {
                         Metric::Verbosity.key(),
                         section.verbosity.header.ratio.0,
                     ),
+                ]
+                .into_iter()
+                .chain(section.import_cycles.iter().map(move |import_cycles| {
                     (
                         source_set,
                         Metric::ImportCycles.key(),
-                        section.import_cycles.header.ratio.0,
-                    ),
-                ]
-                .into_iter()
+                        import_cycles.header.ratio.0,
+                    )
+                }))
                 .chain(
                     section
                         .boundaries
@@ -1149,8 +1166,9 @@ impl SourceSetSections {
 }
 
 impl SourceSetSection {
-    fn new(
-        model: &CodeModel,
+    fn new<'a>(
+        model: &'a CodeModel,
+        import_model: Option<&'a CodeModel>,
         ranges: &ReferenceRangeScope,
         options: SectionOptions<'_>,
     ) -> Result {
@@ -1158,13 +1176,25 @@ impl SourceSetSection {
             shown: options.findings,
             ownership: options.ownership,
         };
-        let measured = Measured::new(model, options.boundaries, options.duplication);
+        let effective_import_model = import_model.filter(|_| options.has_imports);
+        let boundaries_config = effective_import_model
+            .is_some()
+            .then_some(options.boundaries)
+            .flatten();
+        let measured = Measured::new(
+            model,
+            effective_import_model,
+            boundaries_config,
+            options.duplication,
+        );
         let boundaries = measured
             .boundaries
             .as_ref()
             .map(|evaluated| BoundariesSection::new(evaluated, view));
-        let orphan_files = options
-            .orphan_files
+        let orphan_files = effective_import_model
+            .is_some()
+            .then_some(options.orphan_files)
+            .flatten()
             .map(|measured| OrphanFilesSection::new(measured, view));
         let mut external_metrics = BTreeMap::new();
         for plugin in options.metric_plugins {
@@ -1244,27 +1274,20 @@ impl SourceSetSection {
                 },
                 findings: view.map(measured.verbosity.flagged_lines()),
             },
-            import_cycles: ImportCyclesSection {
-                header: MetricHeader::new(
-                    measured.import_cycles.ratio(),
-                    ranges,
-                    Metric::ImportCycles.key(),
-                ),
-                modules_in_import_cycles: measured.import_cycles.modules_in_import_cycles(),
-                modules: measured.import_cycles.modules(),
-                findings: view.select(
-                    measured
-                        .import_cycles
-                        .cycles()
-                        .iter()
-                        .map(ImportCycleFinding::new),
-                ),
-                unresolved_imports: UnresolvedImportsSection::new(&measured.import_cycles, view),
-            },
+            import_cycles: measured
+                .import_cycles
+                .as_ref()
+                .map(|cycles| ImportCyclesSection {
+                    header: MetricHeader::new(cycles.ratio(), ranges, Metric::ImportCycles.key()),
+                    modules_in_import_cycles: cycles.modules_in_import_cycles(),
+                    modules: cycles.modules(),
+                    findings: view.select(cycles.cycles().iter().map(ImportCycleFinding::new)),
+                    unresolved_imports: UnresolvedImportsSection::new(cycles, view),
+                }),
             boundaries,
             orphan_files,
             external_metrics,
-            packages: package_sections(model, &measured),
+            packages: package_sections(model, effective_import_model, &measured),
         })
     }
 }
@@ -1479,13 +1502,14 @@ struct Measured {
     cognitive_complexity: CognitiveComplexity,
     duplication: Duplication,
     verbosity: Verbosity,
-    import_cycles: ImportCycles,
+    import_cycles: Option,
     boundaries: Option,
 }
 
 impl Measured {
     fn new(
         model: &CodeModel,
+        import_model: Option<&CodeModel>,
         boundaries: Option<&BoundariesConfig>,
         duplication_config: DuplicationConfig,
     ) -> Measured {
@@ -1499,24 +1523,30 @@ impl Measured {
             MinimumDistinctTokens::DEFAULT,
             near_clones,
         );
-        let boundaries =
-            boundaries.map(|config| Boundaries::measure(model, &ConfigBoundaryPolicy(config)));
+        let import_cycles = import_model.map(ImportCycles::measure);
+        let boundaries = import_model.and_then(|imports| {
+            boundaries.map(|config| Boundaries::measure(imports, &ConfigBoundaryPolicy(config)))
+        });
         Measured {
             erosion: Erosion::measure(model),
             cognitive_complexity: CognitiveComplexity::measure(model),
             verbosity: Verbosity::measure(model, &duplication.exact_clone_lines),
             duplication,
-            import_cycles: ImportCycles::measure(model),
+            import_cycles,
             boundaries,
         }
     }
 }
 
-fn package_sections(model: &CodeModel, measured: &Measured) -> Vec {
+fn package_sections<'a>(
+    model: &'a CodeModel,
+    import_model: Option<&'a CodeModel>,
+    measured: &Measured,
+) -> Vec {
     if !model.workspace.has_members() {
         return Vec::new();
     }
-    let mut files: BTreeMap, usize> = BTreeMap::new();
+    let mut files: BTreeMap, usize> = BTreeMap::new();
     for file in &model.files {
         *files
             .entry(model.workspace.package_of(&file.path))
@@ -1525,19 +1555,28 @@ fn package_sections(model: &CodeModel, measured: &Measured) -> Vec 0 || package_files == 0).then(|| PackageImportCycles {
+                    ratio: Decimal::rounded(modules.ratio()),
+                    modules_in_import_cycles: modules.modules_in_import_cycles,
+                })
+            });
             PackageSection {
                 path: package.to_string(),
-                files: files.get(&package).copied().unwrap_or_default(),
+                files: package_files,
                 source_lines: clone_lines.source_lines,
                 erosion: PackageErosion {
                     ratio: Decimal::rounded(masses.ratio()),
@@ -1557,10 +1596,7 @@ fn package_sections(model: &CodeModel, measured: &Measured) -> Vec {
 impl MeasuredSection {
     fn new(
         model: CodeModel,
+        import_model: Option,
         hygiene: &DependencyHygiene,
         ranges: &ReferenceRangeScope,
         options: SectionOptions<'_>,
@@ -1593,11 +1630,33 @@ impl MeasuredSection {
             shown: options.findings,
             ownership: options.ownership,
         };
-        let dependencies = DependenciesSection::from_hygiene(hygiene, view);
-        let source_sets = SourceSetSections::new(&model.into_source_sets(), ranges, options)?;
+        let dependencies = options
+            .has_imports
+            .then(|| DependenciesSection::from_hygiene(hygiene, view))
+            .flatten();
+        let import_metrics_note = (!options.has_imports).then(|| NO_IMPORTS_METRIC_NOTE.to_owned());
+        let section_options = if options.has_imports {
+            options
+        } else {
+            SectionOptions {
+                boundaries: None,
+                orphan_files: None,
+                ..options
+            }
+        };
+        let source_sets = model.into_source_sets();
+        let separate_import_source_sets = import_model.map(CodeModel::into_source_sets);
+        let import_source_sets = if options.has_imports {
+            Some(separate_import_source_sets.as_ref().unwrap_or(&source_sets))
+        } else {
+            None
+        };
+        let source_sets =
+            SourceSetSections::new(&source_sets, import_source_sets, ranges, section_options)?;
         Ok(MeasuredSection {
             files,
             source_lines: lines,
+            import_metrics_note,
             source_sets,
             dependencies,
         })
@@ -1738,14 +1797,15 @@ impl Report {
         let total_hygiene = match options.dependency_hygiene {
             Some(precomputed) => precomputed,
             None => {
-                measured_total_hygiene = DependencyHygiene::merge(
-                    languages
-                        .iter()
-                        .map(|language| DependencyHygiene::measure(&language.model, ignored)),
-                );
+                measured_total_hygiene = measure_combined_hygiene(&languages, ignored);
                 &measured_total_hygiene
             }
         };
+        let (measured, unmeasured): (Vec, Vec) = languages
+            .into_iter()
+            .partition(|language| !language.model.files.is_empty());
+        let top_has_imports =
+            measured.is_empty() || measured.iter().any(|language| language.has_imports);
         let section_options = SectionOptions {
             findings: options.findings,
             metric_plugins: options.metric_plugins,
@@ -1753,53 +1813,11 @@ impl Report {
             duplication: options.duplication,
             orphan_files: options.orphan_files,
             ownership: options.ownership,
+            has_imports: top_has_imports,
         };
-        let (measured, unmeasured): (Vec, Vec) = languages
-            .into_iter()
-            .partition(|language| !language.model.files.is_empty());
-        let (total_ranges, sections_per_language) = match measured.as_slice() {
-            [] => (
-                ReferenceRangeScope::OneLanguage(ReferenceRanges::default()),
-                BTreeMap::new(),
-            ),
-            [only] => (
-                ReferenceRangeScope::OneLanguage(only.reference_ranges.clone()),
-                BTreeMap::new(),
-            ),
-            _ => {
-                let mut per_language = BTreeMap::new();
-                for language in &measured {
-                    let measured_language_hygiene;
-                    let language_hygiene = match options
-                        .dependency_hygiene_by_language
-                        .and_then(|map| map.get(&language.plugin))
-                    {
-                        Some(precomputed) => precomputed,
-                        None => {
-                            measured_language_hygiene =
-                                DependencyHygiene::measure(&language.model, ignored);
-                            &measured_language_hygiene
-                        }
-                    };
-                    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(),
-                            language_hygiene,
-                            &ReferenceRangeScope::OneLanguage(language.reference_ranges.clone()),
-                            SectionOptions {
-                                orphan_files: language_orphans,
-                                ..section_options
-                            },
-                        )?,
-                    );
-                }
-                (ReferenceRangeScope::SeveralLanguages, per_language)
-            }
-        };
+        let (total_ranges, sections_per_language) =
+            build_per_language_sections(&measured, &options, ignored, section_options)?;
+        let import_bearing_model = collect_import_bearing_model(&measured, top_has_imports);
         let model = CodeModel::merge(
             measured
                 .into_iter()
@@ -1812,7 +1830,13 @@ impl Report {
             .iter()
             .map(RepoPath::to_string)
             .collect();
-        let measured = MeasuredSection::new(model, total_hygiene, &total_ranges, section_options)?;
+        let measured = MeasuredSection::new(
+            model,
+            import_bearing_model,
+            total_hygiene,
+            &total_ranges,
+            section_options,
+        )?;
         let mut failures = measured.source_sets.over_budget(options.budgets);
         if let Some(dependencies) = &measured.dependencies {
             failures.extend(dependencies.over_budget(options.budgets));
@@ -1849,6 +1873,103 @@ impl Report {
     }
 }
 
+fn measure_combined_hygiene(
+    languages: &[MeasuredLanguage],
+    ignored: &std::collections::BTreeSet,
+) -> DependencyHygiene {
+    DependencyHygiene::merge(
+        languages
+            .iter()
+            .filter(|language| language.has_imports)
+            .map(|language| DependencyHygiene::measure(&language.model, ignored)),
+    )
+}
+
+fn collect_import_bearing_model(
+    measured: &[MeasuredLanguage],
+    top_has_imports: bool,
+) -> Option {
+    let all_measured_have_imports = measured.iter().all(|language| language.has_imports);
+    (top_has_imports && !all_measured_have_imports).then(|| {
+        CodeModel::merge(
+            measured
+                .iter()
+                .filter(|language| language.has_imports)
+                .map(|language| language.model.clone()),
+        )
+    })
+}
+
+fn build_per_language_sections(
+    measured: &[MeasuredLanguage],
+    options: &ReportOptions<'_>,
+    ignored: &std::collections::BTreeSet,
+    section_options: SectionOptions<'_>,
+) -> Result<(ReferenceRangeScope, BTreeMap), MetricPluginError> {
+    match measured {
+        [] => Ok((
+            ReferenceRangeScope::OneLanguage(ReferenceRanges::default()),
+            BTreeMap::new(),
+        )),
+        [only] => Ok((
+            ReferenceRangeScope::OneLanguage(only.reference_ranges.clone()),
+            BTreeMap::new(),
+        )),
+        _ => {
+            let mut per_language = BTreeMap::new();
+            for language in measured {
+                let section =
+                    build_single_language_section(language, options, ignored, section_options)?;
+                per_language.insert(language.plugin.clone(), section);
+            }
+            Ok((ReferenceRangeScope::SeveralLanguages, per_language))
+        }
+    }
+}
+
+fn build_single_language_section(
+    language: &MeasuredLanguage,
+    options: &ReportOptions<'_>,
+    ignored: &std::collections::BTreeSet,
+    section_options: SectionOptions<'_>,
+) -> Result {
+    let measured_language_hygiene;
+    let language_hygiene = if language.has_imports {
+        match options
+            .dependency_hygiene_by_language
+            .and_then(|map| map.get(&language.plugin))
+        {
+            Some(precomputed) => precomputed,
+            None => {
+                measured_language_hygiene = DependencyHygiene::measure(&language.model, ignored);
+                &measured_language_hygiene
+            }
+        }
+    } else {
+        measured_language_hygiene = DependencyHygiene::default();
+        &measured_language_hygiene
+    };
+    let language_orphans = language
+        .has_imports
+        .then(|| {
+            options
+                .orphan_files_by_language
+                .and_then(|map| map.get(&language.plugin))
+        })
+        .flatten();
+    MeasuredSection::new(
+        language.model.clone(),
+        None,
+        language_hygiene,
+        &ReferenceRangeScope::OneLanguage(language.reference_ranges.clone()),
+        SectionOptions {
+            orphan_files: language_orphans,
+            has_imports: language.has_imports,
+            ..section_options
+        },
+    )
+}
+
 pub(crate) enum TextReportFormat {
     Toon,
     Json,
diff --git a/crates/report/src/markdown.rs b/crates/report/src/markdown.rs
index 58a22418..f4a291c4 100644
--- a/crates/report/src/markdown.rs
+++ b/crates/report/src/markdown.rs
@@ -26,7 +26,7 @@ pub(crate) const ERODED_FUNCTION_COLUMNS: [&str; 4] = [
 ];
 pub(crate) const COMPLEX_FUNCTION_COLUMNS: [&str; 3] =
     ["Function", "Cognitive complexity", "Source lines"];
-const PACKAGE_COLUMNS: [&str; 9] = [
+const PACKAGE_COLUMNS: [&str; 8] = [
     "Source set",
     "Package",
     "Files",
@@ -35,7 +35,6 @@ const PACKAGE_COLUMNS: [&str; 9] = [
     "Cognitive complexity",
     "Duplication",
     "Verbosity",
-    "Import cycles",
 ];
 pub(crate) const FLAGGED_LINE_COLUMNS: [&str; 2] = ["Flagged line", "Rule"];
 pub(crate) const EXTERNAL_FINDING_COLUMNS: [&str; 2] = ["Location", "Message"];
@@ -139,6 +138,9 @@ impl Noun {
 pub(crate) fn render(report: &Report) -> String {
     let sections = report.measured.source_sets.named();
     let mut blocks = vec![TITLE.to_string(), measured_summary(&report.measured)];
+    if let Some(note) = &report.measured.import_metrics_note {
+        blocks.push(prose(note));
+    }
     blocks.extend(metric_table(§ions));
     push_dependencies_summary(&mut blocks, report.measured.dependencies.as_ref());
     if !report.over_budget.is_empty() {
@@ -175,6 +177,9 @@ fn push_language_sections(
         let language_sections = language.source_sets.named();
         blocks.push(format!("## Language plugin {}", code(plugin)));
         blocks.push(measured_summary(language));
+        if let Some(note) = &language.import_metrics_note {
+            blocks.push(prose(note));
+        }
         blocks.extend(metric_table(&language_sections));
         if let Some(dependencies) = &language.dependencies {
             blocks.push(dependencies_summary_table(dependencies));
@@ -217,19 +222,29 @@ fn metric_table(sections: &[(&str, &SourceSetSection)]) -> Option {
 }
 
 fn package_table(sections: &[(&str, &SourceSetSection)]) -> Option {
+    let show_import_cycles = sections.iter().any(|(_, section)| {
+        section
+            .packages
+            .iter()
+            .any(|package| package.import_cycles.is_some())
+    });
     let package_rows: Vec> = sections
         .iter()
         .flat_map(|(name, section)| {
             section
                 .packages
                 .iter()
-                .map(|package| package_row(name, package))
+                .map(|package| package_row(name, package, show_import_cycles))
         })
         .collect();
     if package_rows.is_empty() {
         return None;
     }
-    Some(table(&PACKAGE_COLUMNS, package_rows))
+    let mut columns: Vec<&str> = PACKAGE_COLUMNS.to_vec();
+    if show_import_cycles {
+        columns.push("Import cycles");
+    }
+    Some(table(&columns, package_rows))
 }
 
 pub(crate) fn sentence_item(failure: &impl std::fmt::Display) -> String {
@@ -242,8 +257,12 @@ pub(crate) fn sentence_item(failure: &impl std::fmt::Display) -> String {
     format!("{}.", prose(&capitalized))
 }
 
-fn package_row(source_set: &str, package: &PackageSection) -> Vec {
-    vec![
+fn package_row(
+    source_set: &str,
+    package: &PackageSection,
+    show_import_cycles: bool,
+) -> Vec {
+    let mut cells = vec![
         source_set.to_string(),
         code(&package.path),
         package.files.to_string(),
@@ -252,8 +271,14 @@ fn package_row(source_set: &str, package: &PackageSection) -> Vec {
         package.cognitive_complexity.ratio.0.to_string(),
         package.duplication.ratio.0.to_string(),
         package.verbosity.ratio.0.to_string(),
-        package.import_cycles.ratio.0.to_string(),
-    ]
+    ];
+    if show_import_cycles {
+        cells.push(package.import_cycles.as_ref().map_or_else(
+            || "not measured".to_string(),
+            |cycles| cycles.ratio.0.to_string(),
+        ));
+    }
+    cells
 }
 
 fn measured_summary(measured: &MeasuredSection) -> String {
@@ -309,7 +334,6 @@ fn metric_rows(source_set: &str, section: &SourceSetSection) -> Vec>
         ),
     };
     let verbosity = §ion.verbosity;
-    let import_cycles = §ion.import_cycles;
     let mut rows = vec![
         row(
             "Erosion",
@@ -340,12 +364,14 @@ fn metric_rows(source_set: &str, section: &SourceSetSection) -> Vec>
                 CLONE_LINE.counted(verbosity.totals.clone_lines)
             ),
         ),
-        row(
+    ];
+    if let Some(import_cycles) = §ion.import_cycles {
+        rows.push(row(
             "Import cycles",
             &import_cycles.header,
             import_cycles_behind_the_value(import_cycles),
-        ),
-    ];
+        ));
+    }
     if let Some(boundaries) = §ion.boundaries {
         let total_findings = boundaries
             .findings
@@ -451,20 +477,22 @@ fn findings_blocks(section: &SourceSetSection) -> Vec {
         &FLAGGED_LINE,
         |listed| findings_table(&FLAGGED_LINE_COLUMNS, listed, flagged_line_row),
     );
-    push_findings(
-        &mut blocks,
-        "Import cycles",
-        §ion.import_cycles.findings,
-        &IMPORT_CYCLE,
-        |listed| list(listed.iter().map(import_cycle_item)),
-    );
-    push_findings(
-        &mut blocks,
-        "Unresolved imports",
-        §ion.import_cycles.unresolved_imports.imports,
-        &UNRESOLVED_IMPORT,
-        |listed| findings_table(&UNRESOLVED_IMPORT_COLUMNS, listed, unresolved_import_row),
-    );
+    if let Some(import_cycles) = §ion.import_cycles {
+        push_findings(
+            &mut blocks,
+            "Import cycles",
+            &import_cycles.findings,
+            &IMPORT_CYCLE,
+            |listed| list(listed.iter().map(import_cycle_item)),
+        );
+        push_findings(
+            &mut blocks,
+            "Unresolved imports",
+            &import_cycles.unresolved_imports.imports,
+            &UNRESOLVED_IMPORT,
+            |listed| findings_table(&UNRESOLVED_IMPORT_COLUMNS, listed, unresolved_import_row),
+        );
+    }
     if let Some(boundaries) = §ion.boundaries {
         push_findings(
             &mut blocks,
diff --git a/crates/report/src/measurement.rs b/crates/report/src/measurement.rs
index 73c692c8..abfcadec 100644
--- a/crates/report/src/measurement.rs
+++ b/crates/report/src/measurement.rs
@@ -1,8 +1,8 @@
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, BTreeSet};
 
 use codeint_config::{Boundaries as BoundariesConfig, DependenciesConfig, DuplicationConfig};
 use codeint_metrics::{DependencyHygiene, OrphanFiles};
-use codeint_model::{CodeModel, MetricPlugin, MetricPluginError, SourceSet};
+use codeint_model::{CodeModel, MetricPlugin, MetricPluginError, SourceSet, SourceSets};
 use serde::{Deserialize, Serialize};
 
 use crate::{
@@ -37,7 +37,8 @@ pub(crate) struct SourceSetMeasurement {
     pub(crate) duplication: MetricMeasurement,
     pub(crate) clone_families: Vec,
     pub(crate) verbosity: MetricMeasurement,
-    pub(crate) import_cycles: MetricMeasurement,
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub(crate) import_cycles: Option>,
     #[serde(default, skip_serializing_if = "Option::is_none")]
     pub(crate) boundaries: Option>,
     #[serde(default, skip_serializing_if = "Option::is_none")]
@@ -137,46 +138,45 @@ impl CommitMeasurement {
         let hygiene = match dependency_hygiene {
             Some(precomputed) => precomputed,
             None => {
-                measured_hygiene = DependencyHygiene::merge(
-                    languages
-                        .iter()
-                        .map(|model| DependencyHygiene::measure(model, ignored)),
-                );
+                measured_hygiene = measure_commit_hygiene(&languages, ignored);
                 &measured_hygiene
             }
         };
-        let dependencies = DependenciesMeasurement::from_hygiene(hygiene);
-        let model = CodeModel::merge(languages);
-        let source_sets = model.into_source_sets();
-        Ok(CommitMeasurement {
-            production: SourceSetMeasurement::of(
-                source_sets.get(SourceSet::Production),
-                metric_plugins,
-                boundaries.filter(|config| config.applies_to_source_set(SourceSet::Production)),
-                duplication,
-                orphan_files,
-            )?,
-            test: SourceSetMeasurement::of(
-                source_sets.get(SourceSet::Test),
-                metric_plugins,
-                boundaries.filter(|config| config.applies_to_source_set(SourceSet::Test)),
-                duplication,
-                None,
-            )?,
-            generated: SourceSetMeasurement::of(
-                source_sets.get(SourceSet::Generated),
-                metric_plugins,
-                boundaries.filter(|config| config.applies_to_source_set(SourceSet::Generated)),
-                duplication,
-                None,
-            )?,
-            vendored: SourceSetMeasurement::of(
-                source_sets.get(SourceSet::Vendored),
+        let measured: Vec<&CodeModel> = languages
+            .iter()
+            .filter(|model| !model.files.is_empty())
+            .collect();
+        let any_has_imports =
+            measured.is_empty() || measured.iter().copied().any(model_has_imports);
+        let all_have_imports = measured.iter().copied().all(model_has_imports);
+        let separate_import_source_sets =
+            (any_has_imports && !all_have_imports).then(|| build_import_source_sets(&languages));
+        let dependencies = any_has_imports
+            .then(|| DependenciesMeasurement::from_hygiene(hygiene))
+            .flatten();
+        let source_sets = CodeModel::merge(languages).into_source_sets();
+        let measure = |source_set: SourceSet, set_orphans: Option<&OrphanFiles>| {
+            let import_model = select_import_model(
+                source_set,
+                any_has_imports,
+                &source_sets,
+                separate_import_source_sets.as_ref(),
+            );
+            measure_source_set(
+                source_set,
+                source_sets.get(source_set),
+                import_model,
                 metric_plugins,
-                boundaries.filter(|config| config.applies_to_source_set(SourceSet::Vendored)),
+                boundaries,
                 duplication,
-                None,
-            )?,
+                set_orphans,
+            )
+        };
+        Ok(CommitMeasurement {
+            production: measure(SourceSet::Production, orphan_files)?,
+            test: measure(SourceSet::Test, None)?,
+            generated: measure(SourceSet::Generated, None)?,
+            vendored: measure(SourceSet::Vendored, None)?,
             dependencies,
         })
     }
@@ -236,15 +236,20 @@ impl DependenciesMeasurement {
     }
 }
 
+fn model_has_imports(model: &CodeModel) -> bool {
+    model.languages.is_empty() || model.languages.iter().any(|facts| facts.has_imports)
+}
+
 impl SourceSetMeasurement {
     fn of(
         model: &CodeModel,
+        import_model: Option<&CodeModel>,
         metric_plugins: &[&dyn MetricPlugin],
         boundaries: Option<&BoundariesConfig>,
         duplication_config: DuplicationConfig,
         orphan_files: Option<&OrphanFiles>,
     ) -> Result {
-        let measured = Measured::new(model, boundaries, duplication_config);
+        let measured = Measured::new(model, import_model, boundaries, duplication_config);
         let boundaries = measured
             .boundaries
             .as_ref()
@@ -303,12 +308,14 @@ impl SourceSetMeasurement {
                 measured.verbosity.flagged_lines(),
                 FlaggedLineRow::from,
             ),
-            import_cycles: MetricMeasurement::from_items(
-                measured.import_cycles.ratio(),
-                measured.import_cycles.modules_in_import_cycles() as f64,
-                measured.import_cycles.cycles(),
-                ImportCycleFinding::new,
-            ),
+            import_cycles: measured.import_cycles.as_ref().map(|cycles| {
+                MetricMeasurement::from_items(
+                    cycles.ratio(),
+                    cycles.modules_in_import_cycles() as f64,
+                    cycles.cycles(),
+                    ImportCycleFinding::new,
+                )
+            }),
             boundaries,
             orphan_files,
             external_metrics,
@@ -337,3 +344,66 @@ fn finding_measurement<'a, T: 'a, R: From<&'a T>>(
 ) -> MetricMeasurement {
     MetricMeasurement::from_items(ratio, findings.len() as f64, findings, R::from)
 }
+
+fn measure_commit_hygiene(
+    languages: &[CodeModel],
+    ignored: &BTreeSet,
+) -> DependencyHygiene {
+    let mut measured = Vec::new();
+    for model in languages {
+        if model_has_imports(model) {
+            measured.push(DependencyHygiene::measure(model, ignored));
+        }
+    }
+    DependencyHygiene::merge(measured)
+}
+
+fn build_import_source_sets(languages: &[CodeModel]) -> SourceSets {
+    let mut models = Vec::new();
+    for model in languages {
+        if !model.files.is_empty() && model_has_imports(model) {
+            models.push(model.clone());
+        }
+    }
+    CodeModel::merge(models).into_source_sets()
+}
+
+fn select_import_model<'a>(
+    source_set: SourceSet,
+    any_has_imports: bool,
+    source_sets: &'a SourceSets,
+    separate_import_source_sets: Option<&'a SourceSets>,
+) -> Option<&'a CodeModel> {
+    if !any_has_imports {
+        return None;
+    }
+    match separate_import_source_sets {
+        None => Some(source_sets.get(source_set)),
+        Some(sets) => {
+            let candidate = sets.get(source_set);
+            (!candidate.files.is_empty()).then_some(candidate)
+        }
+    }
+}
+
+fn measure_source_set(
+    source_set: SourceSet,
+    model: &CodeModel,
+    import_model: Option<&CodeModel>,
+    metric_plugins: &[&dyn MetricPlugin],
+    boundaries: Option<&BoundariesConfig>,
+    duplication: DuplicationConfig,
+    orphan_files: Option<&OrphanFiles>,
+) -> Result {
+    let applicable_boundaries = boundaries
+        .filter(|config| import_model.is_some() && config.applies_to_source_set(source_set));
+    let applicable_orphans = orphan_files.filter(|_| import_model.is_some());
+    SourceSetMeasurement::of(
+        model,
+        import_model,
+        metric_plugins,
+        applicable_boundaries,
+        duplication,
+        applicable_orphans,
+    )
+}
diff --git a/crates/report/src/sarif.rs b/crates/report/src/sarif.rs
index f2fc201c..e813ca5f 100644
--- a/crates/report/src/sarif.rs
+++ b/crates/report/src/sarif.rs
@@ -537,7 +537,9 @@ impl<'findings> ListedFindings<'findings> {
             clone_families: §ion.duplication.clone_families.listed,
             clustered_clone_group_ids: §ion.duplication.unlisted_clone_family_group_ids,
             flagged_lines: §ion.verbosity.findings.listed,
-            import_cycles: §ion.import_cycles.findings.listed,
+            import_cycles: section.import_cycles.as_ref().map_or(&[], |import_cycles| {
+                import_cycles.findings.listed.as_slice()
+            }),
             boundaries: section
                 .boundaries
                 .as_ref()
diff --git a/crates/report/src/sarif/tests.rs b/crates/report/src/sarif/tests.rs
index 1ab715ed..0d07bed1 100644
--- a/crates/report/src/sarif/tests.rs
+++ b/crates/report/src/sarif/tests.rs
@@ -274,7 +274,9 @@ fn sarif_does_not_leak_member_clone_groups_of_families_beyond_display_cap() {
                 functions: Vec::new(),
                 tokens,
                 flagged_lines: Vec::new(),
+                hazard_lines: Vec::new(),
                 runtime_imports: Vec::new(),
+                program_start: false,
             },
         }
     };
@@ -313,6 +315,7 @@ fn sarif_does_not_leak_member_clone_groups_of_families_beyond_display_cap() {
             plugin: "typescript-javascript".to_owned(),
             model: model.clone(),
             reference_ranges: ReferenceRanges::default(),
+            has_imports: true,
         }],
         Vec::new(),
         FindingsShown::default(),
@@ -338,6 +341,7 @@ fn sarif_does_not_leak_member_clone_groups_of_families_beyond_display_cap() {
             plugin: "typescript-javascript".to_owned(),
             model: model.clone(),
             reference_ranges: ReferenceRanges::default(),
+            has_imports: true,
         }],
         Vec::new(),
         FindingsShown::All,
diff --git a/crates/report/src/schema.rs b/crates/report/src/schema.rs
index 633b5d2b..dd77bc29 100644
--- a/crates/report/src/schema.rs
+++ b/crates/report/src/schema.rs
@@ -74,7 +74,7 @@ pub(crate) const COGNITIVE_COMPLEXITY_DESCRIPTOR: BuiltInMetricDescriptor =
 pub(crate) const ORPHAN_FILES_DESCRIPTOR: BuiltInMetricDescriptor = BuiltInMetricDescriptor {
     name: "Orphan files",
     short_description: "A Production file unreachable from any entry point",
-    full_description: "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.",
+    full_description: "Orphan files measures the share of Production files that cannot be reached through resolved runtime imports from any manifest-declared, program-start, or configured entry point, annotating files imported only by tests as test-only.",
     help: "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.",
 };
 
diff --git a/crates/report/src/tests.rs b/crates/report/src/tests.rs
index 5f7f32c8..358315f3 100644
--- a/crates/report/src/tests.rs
+++ b/crates/report/src/tests.rs
@@ -30,7 +30,9 @@ fn tiny_positive_min_similarity_preserves_nonzero_json_toon_and_markdown_display
             functions: Vec::new(),
             tokens: Vec::new(),
             flagged_lines: Vec::new(),
+            hazard_lines: Vec::new(),
             runtime_imports: Vec::new(),
+            program_start: false,
         },
     });
     let report = Report::summarize_with_config(
@@ -38,6 +40,7 @@ fn tiny_positive_min_similarity_preserves_nonzero_json_toon_and_markdown_display
             plugin: "typescript-javascript".to_owned(),
             model,
             reference_ranges: ReferenceRanges::default(),
+            has_imports: true,
         }],
         Vec::new(),
         FindingsShown::default(),
diff --git a/crates/report/src/trace.rs b/crates/report/src/trace.rs
index 3db42b86..bdedae54 100644
--- a/crates/report/src/trace.rs
+++ b/crates/report/src/trace.rs
@@ -1,17 +1,32 @@
 use codeint_config::TraceFormat;
 use codeint_metrics::{TraceError, TraceResult, trace_imports};
-use codeint_model::{CodeModel, RepoPath};
+use codeint_model::{CodeModel, RepoPath, SourceSet};
 use serde::Serialize;
 
 use crate::ReportError;
 
+const PROGRAM_START_ENTRY_POINT_REASON: &str = "program-start mark";
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct TraceMultiFileImport {
+    pub importer: String,
+    pub specifier: String,
+    pub targets: Vec,
+}
+
 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
 pub struct TraceReport {
     pub from: String,
     pub to: String,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub from_entry_point: Option,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub to_entry_point: Option,
     pub connected: bool,
     pub shortest_distance: Option,
     pub paths: Vec>,
+    #[serde(default, skip_serializing_if = "Vec::is_empty")]
+    pub multi_file_imports: Vec,
     pub truncated: bool,
 }
 
@@ -23,13 +38,19 @@ impl TraceReport {
         all_shortest: bool,
         max_paths: usize,
     ) -> Result {
-        trace_imports(model, from, to, all_shortest, max_paths).map(TraceReport::of)
+        let mut report =
+            trace_imports(model, from, to, all_shortest, max_paths).map(TraceReport::of)?;
+        report.from_entry_point = program_start_reason(model, from);
+        report.to_entry_point = program_start_reason(model, to);
+        Ok(report)
     }
 
     pub fn of(result: TraceResult) -> TraceReport {
         TraceReport {
             from: result.from.to_string(),
             to: result.to.to_string(),
+            from_entry_point: None,
+            to_entry_point: None,
             connected: result.connected,
             shortest_distance: result.shortest_distance,
             paths: result
@@ -37,6 +58,19 @@ impl TraceReport {
                 .into_iter()
                 .map(|chain| chain.into_iter().map(|path| path.to_string()).collect())
                 .collect(),
+            multi_file_imports: result
+                .multi_file_imports
+                .into_iter()
+                .map(|import| TraceMultiFileImport {
+                    importer: import.importer.to_string(),
+                    specifier: import.specifier,
+                    targets: import
+                        .targets
+                        .into_iter()
+                        .map(|target| target.to_string())
+                        .collect(),
+                })
+                .collect(),
             truncated: result.truncated,
         }
     }
@@ -46,18 +80,46 @@ impl TraceReport {
     }
 }
 
+fn program_start_reason(model: &CodeModel, path: &RepoPath) -> Option {
+    let has_imports =
+        model.languages.is_empty() || model.languages.iter().any(|facts| facts.has_imports);
+    if !has_imports || codeint_metrics::is_non_runtime_tooling_path(model, path) {
+        return None;
+    }
+    let marked_production = model.files.iter().any(|file| {
+        &file.path == path
+            && file.model.program_start
+            && file.model.source_set == SourceSet::Production
+    });
+    marked_production.then(|| PROGRAM_START_ENTRY_POINT_REASON.to_owned())
+}
+
 fn render_text(report: &TraceReport) -> String {
+    let mut lines = Vec::new();
+    if let Some(reason) = &report.from_entry_point {
+        lines.push(format!("Entry point: {} ({reason})", report.from));
+    }
+    if let Some(reason) = &report.to_entry_point
+        && report.to != report.from
+    {
+        lines.push(format!("Entry point: {} ({reason})", report.to));
+    }
     if !report.connected {
-        return format!(
+        lines.push(format!(
             "No runtime import path from {} to {}",
             report.from, report.to
-        );
+        ));
+        return lines.join("\n");
+    }
+    lines.extend(report.paths.iter().map(|chain| chain.join(" -> ")));
+    for import in &report.multi_file_imports {
+        lines.push(format!(
+            "Import {} in {} leads to: {}",
+            import.specifier,
+            import.importer,
+            import.targets.join(", ")
+        ));
     }
-    let mut lines: Vec = report
-        .paths
-        .iter()
-        .map(|chain| chain.join(" -> "))
-        .collect();
     if report.truncated {
         lines.push(format!("(truncated at {} paths)", report.paths.len()));
     }
diff --git a/crates/report/src/trend.rs b/crates/report/src/trend.rs
index 9d663490..8946e83b 100644
--- a/crates/report/src/trend.rs
+++ b/crates/report/src/trend.rs
@@ -42,7 +42,8 @@ struct TrendRow {
     cognitive_complexity: Decimal,
     duplication: Decimal,
     verbosity: Decimal,
-    import_cycles: Decimal,
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    import_cycles: Option,
     #[serde(flatten)]
     external_metrics: BTreeMap,
 }
@@ -123,7 +124,10 @@ impl TrendRow {
             cognitive_complexity: Decimal::rounded(measured.cognitive_complexity.ratio),
             duplication: Decimal::rounded(measured.duplication.ratio),
             verbosity: Decimal::rounded(measured.verbosity.ratio),
-            import_cycles: Decimal::rounded(measured.import_cycles.ratio),
+            import_cycles: measured
+                .import_cycles
+                .as_ref()
+                .map(|cycles| Decimal::rounded(cycles.ratio)),
             external_metrics: measured
                 .external_metrics
                 .iter()
diff --git a/crates/report/src/trend/markdown.rs b/crates/report/src/trend/markdown.rs
index 37e834f2..15023bfd 100644
--- a/crates/report/src/trend/markdown.rs
+++ b/crates/report/src/trend/markdown.rs
@@ -4,7 +4,7 @@ use super::{TrendReport, TrendRow};
 use crate::markdown::{code, table};
 
 const TITLE: &str = "# codeint trend";
-const BASE_COLUMNS: [&str; 8] = [
+const BASE_COLUMNS: [&str; 7] = [
     "Commit",
     "Committed on",
     "Files",
@@ -12,7 +12,6 @@ const BASE_COLUMNS: [&str; 8] = [
     "Cognitive complexity",
     "Duplication",
     "Verbosity",
-    "Import cycles",
 ];
 
 pub(super) fn render(report: &TrendReport) -> String {
@@ -24,13 +23,17 @@ pub(super) fn render(report: &TrendReport) -> String {
             .collect::>()
             .into_iter()
             .collect();
+        let show_import_cycles = rows.iter().any(|row| row.import_cycles.is_some());
         let mut columns: Vec<&str> = BASE_COLUMNS.to_vec();
+        if show_import_cycles {
+            columns.push("Import cycles");
+        }
         columns.extend(external_keys.iter().map(String::as_str));
         blocks.push(format!("## {name}"));
         blocks.push(table(
             &columns,
             rows.iter()
-                .map(|row| row_cells(row, &external_keys))
+                .map(|row| row_cells(row, show_import_cycles, &external_keys))
                 .collect(),
         ));
     }
@@ -42,7 +45,7 @@ fn measured_sentence(commits: usize) -> String {
     format!("codeint measured {commits} {noun} of the main line of HEAD, oldest first.")
 }
 
-fn row_cells(row: &TrendRow, external_keys: &[String]) -> Vec {
+fn row_cells(row: &TrendRow, show_import_cycles: bool, external_keys: &[String]) -> Vec {
     let mut cells = vec![
         code(&row.commit),
         row.committed_on.clone(),
@@ -51,8 +54,14 @@ fn row_cells(row: &TrendRow, external_keys: &[String]) -> Vec {
         row.cognitive_complexity.0.to_string(),
         row.duplication.0.to_string(),
         row.verbosity.0.to_string(),
-        row.import_cycles.0.to_string(),
     ];
+    if show_import_cycles {
+        let value = row
+            .import_cycles
+            .as_ref()
+            .map_or_else(|| "-".to_owned(), |decimal| decimal.0.to_string());
+        cells.push(value);
+    }
     for key in external_keys {
         let value = row
             .external_metrics
diff --git a/docs/guide/languages.md b/docs/guide/languages.md
index 63b96929..bc686e41 100644
--- a/docs/guide/languages.md
+++ b/docs/guide/languages.md
@@ -6,7 +6,7 @@ Each plugin parses the modern superset of its language family with no language-v
 Every built-in Language plugin extracts:
 
 - **Function names and complexity**: named functions (with `none` for anonymous lambdas) for Erosion and nesting-weighted Cognitive complexity Findings.
-- **Workspaces and entry points**: Workspace package roots and standard entry-point files discovered from language manifests for `--package` scoping and Orphan files detection.
+- **Workspaces and entry points**: Workspace package roots and standard entry-point files discovered from language manifests for `--package` scoping and Orphan files detection; Language plugins can also mark Production files as program starts from source text.
 - **Dependency manifests and built-ins**: declared runtime, dev, and optional dependencies from each ecosystem's manifest, plus standard-library and runtime built-in classification so built-in imports are never flagged as unlisted dependencies.
 
 ## Summary
diff --git a/docs/guide/philosophy-and-architecture.md b/docs/guide/philosophy-and-architecture.md
index 719e74d2..15cda297 100644
--- a/docs/guide/philosophy-and-architecture.md
+++ b/docs/guide/philosophy-and-architecture.md
@@ -30,7 +30,7 @@ Four core Metrics are calibrated against pre-2023 human-written repositories:
 Additional independent Metrics and structural checks run alongside them:
 
 - **Cognitive complexity**: the share of total nesting-weighted cognitive complexity held by functions scoring over 15.
-- **Orphan files**: Production files unreachable through runtime imports from manifest-declared and configured `entry_points`, classified as `unreferenced` or `test-only`.
+- **Orphan files**: Production files unreachable through runtime imports from manifest-declared, program-start, and configured `entry_points`, classified as `unreferenced` or `test-only`.
 - **Dependency hygiene**: three independent Metrics (`unused_dependencies`, `unlisted_dependencies`, and `dev_in_production_dependencies`) comparing package manifests against imported external packages while excluding standard-library built-ins.
 - **Import boundaries**: directional `allow`/`deny` rules and `public_files` encapsulation across named architectural zones, paired with pre-edit `codeint guard ` checks.
 
@@ -47,6 +47,7 @@ For each built-in language, codeint measures a panel of 20 public repositories p
 ### 4. Budgets and Regressions
 
 - A **Budget** (`codeint check` and `codeint diff`) sets a hard ceiling for a Metric in a Source set (or for a top-level Dependency hygiene Metric).
+  For Import cycles, Orphan files, Import boundaries, and Dependency hygiene, repository totals and Budgets count only languages with imports, and stay absent when no measured language has imports.
 - A **Regression** (`codeint diff `) compares the working tree against the Git merge-base and fails when a change introduces new Findings or raises a ratio past its limit.
   Together, Budgets cap absolute entropy while Regressions act as a ratchet on every pull request.
 
@@ -75,5 +76,5 @@ CLI + MCP + Rust SDK (crates/cli)  &  JS/TS SDK (npm/codeint)
 - **Git-native measurement (`crates/git`)**: reads tracked working-tree files and historical commits directly from Git objects via `gix`, never modifying the working tree during `diff`, `trend`, `churn`, or `coupling`, with a content-addressed result cache for fast repeated runs.
 - **Language plugins (`plugins/languages/*`)**: own every language-specific rule (parsing, named functions, decision points, cognitive complexity, tokens, Flagged lines, imports, workspaces, entry points, declared dependencies, Source-set defaults) and lower files into the language-neutral **Code model** (`crates/model`).
   TypeScript/JavaScript (including `.vue` and `.svelte` `